'use client';

import { useState, useEffect, useCallback } from 'react';
import { Tag, Plus, CheckCircle2, XCircle, Trash2, ToggleLeft, ToggleRight } from 'lucide-react';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from '@/components/ui/table';
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from '@/components/ui/dialog';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select';
import {
  apiListPromos,
  apiCreatePromo,
  apiDeletePromo,
  apiUpdatePromo,
  type ApiPromo,
} from '@/lib/api';

function formatDate(iso: string) {
  return new Date(iso).toLocaleDateString('en-US', {
    month: 'short',
    day: 'numeric',
    year: 'numeric',
  });
}

function formatDiscount(promo: ApiPromo): string {
  if (promo.percentOff) return `${promo.percentOff}% off`;
  if (promo.amountOff) return `$${(promo.amountOff / 100).toFixed(2)} off`;
  return '—';
}

export default function PromosPage() {
  const [promos, setPromos] = useState<ApiPromo[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [showCreate, setShowCreate] = useState(false);

  // Create form
  const [newCode, setNewCode] = useState('');
  const [discountType, setDiscountType] = useState('percent');
  const [newPercentOff, setNewPercentOff] = useState('20');
  const [newAmountOff, setNewAmountOff] = useState('500');
  const [newDuration, setNewDuration] = useState('once');
  const [newMaxRedemptions, setNewMaxRedemptions] = useState('');
  const [creating, setCreating] = useState(false);

  const handleDelete = async (id: string) => {
    if (!confirm('Delete this promo code? This cannot be undone.')) return;
    const { error: err } = await apiDeletePromo(id);
    if (!err) setPromos(prev => prev.filter(p => p.id !== id));
  };

  const handleToggleActive = async (promo: ApiPromo) => {
    const { data } = await apiUpdatePromo(promo.id, { active: !promo.active });
    if (data)
      setPromos(prev => prev.map(p => (p.id === promo.id ? { ...p, active: !p.active } : p)));
  };

  const loadPromos = useCallback(async () => {
    setLoading(true);
    setError(null);
    const { data, error: err } = await apiListPromos();
    if (data) {
      setPromos(data.promos);
    } else {
      setError(err || 'Failed to load promos');
    }
    setLoading(false);
  }, []);

  useEffect(() => {
    void loadPromos();
  }, [loadPromos]);

  async function handleCreate() {
    if (!newCode.trim()) return;
    setCreating(true);
    const body: Record<string, unknown> = {
      code: newCode.trim(),
      duration: newDuration,
    };
    if (discountType === 'percent') {
      body.percentOff = parseFloat(newPercentOff);
    } else {
      body.amountOff = parseInt(newAmountOff);
      body.currency = 'usd';
    }
    if (newMaxRedemptions) {
      body.maxRedemptions = parseInt(newMaxRedemptions);
    }

    const { error: err } = await apiCreatePromo(body as Parameters<typeof apiCreatePromo>[0]);
    setCreating(false);
    if (!err) {
      setShowCreate(false);
      setNewCode('');
      setNewPercentOff('20');
      setNewAmountOff('500');
      setNewDuration('once');
      setNewMaxRedemptions('');
      loadPromos();
    } else {
      alert(err);
    }
  }

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-2xl font-bold">Promo Codes</h1>
          <p className="text-sm text-muted-foreground">
            Stripe promotion codes for discounts on subscriptions
          </p>
        </div>
        <Button onClick={() => setShowCreate(true)}>
          <Plus className="mr-2 h-4 w-4" /> Create Promo
        </Button>
      </div>

      <div className="grid gap-4 md:grid-cols-3">
        <Card>
          <CardHeader className="pb-2">
            <CardTitle className="text-sm font-medium text-muted-foreground">
              Total Promos
            </CardTitle>
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">{promos.length}</div>
          </CardContent>
        </Card>
        <Card>
          <CardHeader className="pb-2">
            <CardTitle className="text-sm font-medium text-muted-foreground">
              Active Promos
            </CardTitle>
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">{promos.filter(p => p.active).length}</div>
          </CardContent>
        </Card>
        <Card>
          <CardHeader className="pb-2">
            <CardTitle className="text-sm font-medium text-muted-foreground">
              Total Redemptions
            </CardTitle>
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">
              {promos.reduce((sum, p) => sum + p.timesRedeemed, 0)}
            </div>
          </CardContent>
        </Card>
      </div>

      <Card>
        <CardContent className="p-0">
          {loading ? (
            <div className="p-8 text-center text-muted-foreground">Loading...</div>
          ) : error ? (
            <div className="p-8 text-center text-muted-foreground">
              <p className="text-sm">{error}</p>
              <p className="text-xs mt-1">Ensure STRIPE_SECRET_KEY is set in admin .env.local</p>
            </div>
          ) : promos.length === 0 ? (
            <div className="p-8 text-center text-muted-foreground">
              <Tag className="mx-auto mb-2 h-8 w-8 opacity-40" />
              No promo codes yet. Create one in Stripe or via the button above.
            </div>
          ) : (
            <Table>
              <TableHeader>
                <TableRow>
                  <TableHead>Code</TableHead>
                  <TableHead>Discount</TableHead>
                  <TableHead>Duration</TableHead>
                  <TableHead>Redemptions</TableHead>
                  <TableHead>Status</TableHead>
                  <TableHead>Created</TableHead>
                  <TableHead>Expires</TableHead>
                  <TableHead>Actions</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {promos.map(promo => (
                  <TableRow key={promo.id}>
                    <TableCell>
                      <code className="text-sm font-mono font-bold">{promo.code}</code>
                    </TableCell>
                    <TableCell>{formatDiscount(promo)}</TableCell>
                    <TableCell className="capitalize">{promo.duration || '—'}</TableCell>
                    <TableCell>
                      {promo.timesRedeemed}
                      {promo.maxRedemptions ? ` / ${promo.maxRedemptions}` : ''}
                    </TableCell>
                    <TableCell>
                      <Badge
                        className={`border-0 gap-1 ${
                          promo.active ? 'bg-emerald-50 text-emerald-700' : 'bg-red-50 text-red-700'
                        }`}
                      >
                        {promo.active ? (
                          <CheckCircle2 className="h-3 w-3" />
                        ) : (
                          <XCircle className="h-3 w-3" />
                        )}
                        {promo.active ? 'Active' : 'Inactive'}
                      </Badge>
                    </TableCell>
                    <TableCell className="text-muted-foreground text-xs">
                      {formatDate(promo.created)}
                    </TableCell>
                    <TableCell className="text-muted-foreground text-xs">
                      {promo.expiresAt ? formatDate(promo.expiresAt) : 'Never'}
                    </TableCell>
                    <TableCell>
                      <div className="flex items-center gap-1">
                        <Button
                          variant="ghost"
                          size="sm"
                          className="h-7 w-7 p-0"
                          onClick={() => handleToggleActive(promo)}
                          title={promo.active ? 'Deactivate' : 'Activate'}
                        >
                          {promo.active ? (
                            <ToggleRight className="h-4 w-4 text-emerald-600" />
                          ) : (
                            <ToggleLeft className="h-4 w-4 text-muted-foreground" />
                          )}
                        </Button>
                        <Button
                          variant="ghost"
                          size="sm"
                          className="h-7 w-7 p-0 text-destructive hover:text-destructive"
                          onClick={() => handleDelete(promo.id)}
                          title="Delete promo"
                        >
                          <Trash2 className="h-4 w-4" />
                        </Button>
                      </div>
                    </TableCell>
                  </TableRow>
                ))}
              </TableBody>
            </Table>
          )}
        </CardContent>
      </Card>

      <Dialog open={showCreate} onOpenChange={setShowCreate}>
        <DialogContent>
          <DialogHeader>
            <DialogTitle>Create Promo Code</DialogTitle>
            <DialogDescription>
              Creates a Stripe coupon + promotion code. Users can enter this at checkout.
            </DialogDescription>
          </DialogHeader>
          <div className="space-y-4">
            <div className="space-y-2">
              <Label>Promo Code</Label>
              <Input
                placeholder="e.g. LAUNCH20"
                value={newCode}
                onChange={e => setNewCode(e.target.value)}
              />
            </div>
            <div className="grid grid-cols-2 gap-4">
              <div className="space-y-2">
                <Label>Discount Type</Label>
                <Select value={discountType} onValueChange={setDiscountType}>
                  <SelectTrigger>
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="percent">Percentage</SelectItem>
                    <SelectItem value="amount">Fixed Amount</SelectItem>
                  </SelectContent>
                </Select>
              </div>
              <div className="space-y-2">
                <Label>{discountType === 'percent' ? 'Percent Off' : 'Amount Off (cents)'}</Label>
                <Input
                  type="number"
                  min="1"
                  value={discountType === 'percent' ? newPercentOff : newAmountOff}
                  onChange={e =>
                    discountType === 'percent'
                      ? setNewPercentOff(e.target.value)
                      : setNewAmountOff(e.target.value)
                  }
                />
              </div>
            </div>
            <div className="grid grid-cols-2 gap-4">
              <div className="space-y-2">
                <Label>Duration</Label>
                <Select value={newDuration} onValueChange={setNewDuration}>
                  <SelectTrigger>
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="once">Once</SelectItem>
                    <SelectItem value="repeating">Repeating</SelectItem>
                    <SelectItem value="forever">Forever</SelectItem>
                  </SelectContent>
                </Select>
              </div>
              <div className="space-y-2">
                <Label>Max Redemptions (empty = unlimited)</Label>
                <Input
                  type="number"
                  min="1"
                  placeholder="Unlimited"
                  value={newMaxRedemptions}
                  onChange={e => setNewMaxRedemptions(e.target.value)}
                />
              </div>
            </div>
          </div>
          <DialogFooter>
            <Button variant="outline" onClick={() => setShowCreate(false)}>
              Cancel
            </Button>
            <Button onClick={handleCreate} disabled={creating || !newCode.trim()}>
              {creating ? 'Creating...' : 'Create Promo'}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  );
}
