'use client';

import { createProxyFetch } from '@/lib/proxy-fetch';

import { useState, useEffect, useCallback } from 'react';
import {
  ListOrdered,
  MoreHorizontal,
  Search,
  Download,
  Send,
  CheckCircle2,
  Clock,
  Mail,
} 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 {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from '@/components/ui/table';
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select';

interface WaitlistEntry {
  id: string;
  email: string;
  name?: string;
  position: number;
  status: string;
  referralCode?: string;
  referredBy?: string;
  invitedAt?: string;
  convertedAt?: string;
  createdAt: string;
}

const statusConfig: Record<string, { label: string; color: string; icon: typeof Clock }> = {
  waiting: { label: 'Waiting', color: 'bg-blue-50 text-blue-700', icon: Clock },
  invited: { label: 'Invited', color: 'bg-amber-50 text-amber-700', icon: Mail },
  converted: { label: 'Converted', color: 'bg-emerald-50 text-emerald-700', icon: CheckCircle2 },
  unsubscribed: { label: 'Unsubscribed', color: 'bg-gray-50 text-gray-600', icon: Clock },
};

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

const apiFetch = createProxyFetch('/api/waitlist');

export default function WaitlistPage() {
  const [entries, setEntries] = useState<WaitlistEntry[]>([]);
  const [total, setTotal] = useState(0);
  const [loading, setLoading] = useState(true);
  const [statusFilter, setStatusFilter] = useState<string>('all');
  const [search, setSearch] = useState('');
  const [selected, setSelected] = useState<Set<string>>(new Set());
  const [inviting, setInviting] = useState(false);
  const [exporting, setExporting] = useState(false);

  const loadEntries = useCallback(async () => {
    setLoading(true);
    const params = new URLSearchParams();
    if (statusFilter !== 'all') params.set('status', statusFilter);
    if (search) params.set('search', search);
    const qs = params.toString() ? `?${params.toString()}` : '';
    const data = await apiFetch(`${qs}`);
    if (data?.entries) {
      setEntries(data.entries);
      setTotal(data.total ?? data.entries.length);
    } else if (Array.isArray(data)) {
      setEntries(data);
      setTotal(data.length);
    }
    setLoading(false);
  }, [statusFilter, search]);

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

  function toggleSelect(id: string) {
    setSelected(prev => {
      const next = new Set(prev);
      if (next.has(id)) next.delete(id);
      else next.add(id);
      return next;
    });
  }

  function toggleAll() {
    if (selected.size === entries.length) {
      setSelected(new Set());
    } else {
      setSelected(new Set(entries.map(e => e.id)));
    }
  }

  async function handleBatchInvite() {
    if (selected.size === 0) return;
    setInviting(true);
    await apiFetch('invite', {
      method: 'POST',
      body: JSON.stringify({ entryIds: Array.from(selected) }),
    });
    setInviting(false);
    setSelected(new Set());
    loadEntries();
  }

  async function handleExport() {
    setExporting(true);
    try {
      const res = await fetch('/api/waitlist/export', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
      });
      if (res.ok) {
        const blob = await res.blob();
        const url = URL.createObjectURL(blob);
        const a = document.createElement('a');
        a.href = url;
        a.download = `waitlist-export-${new Date().toISOString().slice(0, 10)}.csv`;
        a.click();
        URL.revokeObjectURL(url);
      }
    } catch {
      // ignore
    }
    setExporting(false);
  }

  async function handleStatusChange(id: string, status: string) {
    await apiFetch(`${id}`, {
      method: 'PUT',
      body: JSON.stringify({ status }),
    });
    loadEntries();
  }

  const waitingCount = entries.filter(e => e.status === 'waiting').length;
  const invitedCount = entries.filter(e => e.status === 'invited').length;
  const convertedCount = entries.filter(e => e.status === 'converted').length;

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-2xl font-bold">Waitlist Management</h1>
          <p className="text-sm text-muted-foreground">
            Manage pre-launch signups, send invitations, and track conversions
          </p>
        </div>
        <div className="flex gap-2">
          <Button variant="outline" onClick={handleExport} disabled={exporting}>
            <Download className="mr-2 h-4 w-4" />
            {exporting ? 'Exporting...' : 'CSV Export'}
          </Button>
          {selected.size > 0 && (
            <Button onClick={handleBatchInvite} disabled={inviting}>
              <Send className="mr-2 h-4 w-4" />
              {inviting ? 'Inviting...' : `Invite ${selected.size} Selected`}
            </Button>
          )}
        </div>
      </div>

      <div className="grid gap-4 md:grid-cols-4">
        <Card>
          <CardHeader className="pb-2">
            <CardTitle className="text-sm font-medium text-muted-foreground">
              Total Signups
            </CardTitle>
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">{total}</div>
          </CardContent>
        </Card>
        <Card>
          <CardHeader className="pb-2">
            <CardTitle className="text-sm font-medium text-muted-foreground">Waiting</CardTitle>
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold text-blue-600">{waitingCount}</div>
          </CardContent>
        </Card>
        <Card>
          <CardHeader className="pb-2">
            <CardTitle className="text-sm font-medium text-muted-foreground">Invited</CardTitle>
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold text-amber-600">{invitedCount}</div>
          </CardContent>
        </Card>
        <Card>
          <CardHeader className="pb-2">
            <CardTitle className="text-sm font-medium text-muted-foreground">Converted</CardTitle>
          </CardHeader>
          <CardContent>
            <div className="flex items-center gap-2">
              <div className="text-2xl font-bold text-emerald-600">{convertedCount}</div>
              {total > 0 && (
                <span className="text-xs text-muted-foreground">
                  ({Math.round((convertedCount / total) * 100)}%)
                </span>
              )}
            </div>
          </CardContent>
        </Card>
      </div>

      <div className="flex items-center gap-4">
        <div className="relative flex-1 max-w-sm">
          <Search className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" />
          <Input
            placeholder="Search by email or name..."
            value={search}
            onChange={e => setSearch(e.target.value)}
            className="pl-9"
          />
        </div>
        <Select value={statusFilter} onValueChange={setStatusFilter}>
          <SelectTrigger className="w-[180px]">
            <SelectValue placeholder="Filter by status" />
          </SelectTrigger>
          <SelectContent>
            <SelectItem value="all">All Statuses</SelectItem>
            <SelectItem value="waiting">Waiting</SelectItem>
            <SelectItem value="invited">Invited</SelectItem>
            <SelectItem value="converted">Converted</SelectItem>
            <SelectItem value="unsubscribed">Unsubscribed</SelectItem>
          </SelectContent>
        </Select>
      </div>

      <Card>
        <CardContent className="p-0">
          {loading ? (
            <div className="p-8 text-center text-muted-foreground">Loading...</div>
          ) : entries.length === 0 ? (
            <div className="p-8 text-center text-muted-foreground">
              <ListOrdered className="mx-auto mb-2 h-8 w-8 opacity-40" />
              No waitlist entries found.
            </div>
          ) : (
            <Table>
              <TableHeader>
                <TableRow>
                  <TableHead className="w-[40px]">
                    <input
                      type="checkbox"
                      checked={selected.size === entries.length && entries.length > 0}
                      onChange={toggleAll}
                      className="rounded border-gray-300"
                    />
                  </TableHead>
                  <TableHead>#</TableHead>
                  <TableHead>Email</TableHead>
                  <TableHead>Name</TableHead>
                  <TableHead>Status</TableHead>
                  <TableHead>Referral</TableHead>
                  <TableHead>Signed Up</TableHead>
                  <TableHead className="w-[50px]" />
                </TableRow>
              </TableHeader>
              <TableBody>
                {entries.map(entry => {
                  const cfg = statusConfig[entry.status] || statusConfig.waiting;
                  const StatusIcon = cfg.icon;
                  return (
                    <TableRow key={entry.id}>
                      <TableCell onClick={e => e.stopPropagation()}>
                        <input
                          type="checkbox"
                          checked={selected.has(entry.id)}
                          onChange={() => toggleSelect(entry.id)}
                          className="rounded border-gray-300"
                        />
                      </TableCell>
                      <TableCell className="text-muted-foreground font-mono text-xs">
                        {entry.position}
                      </TableCell>
                      <TableCell className="font-medium">{entry.email}</TableCell>
                      <TableCell className="text-sm">{entry.name || '—'}</TableCell>
                      <TableCell>
                        <Badge className={`${cfg.color} border-0 gap-1`}>
                          <StatusIcon className="h-3 w-3" />
                          {cfg.label}
                        </Badge>
                      </TableCell>
                      <TableCell className="text-xs text-muted-foreground">
                        {entry.referralCode ? <code>{entry.referralCode}</code> : '—'}
                      </TableCell>
                      <TableCell className="text-muted-foreground text-xs">
                        {formatDate(entry.createdAt)}
                      </TableCell>
                      <TableCell>
                        <DropdownMenu>
                          <DropdownMenuTrigger asChild>
                            <Button variant="ghost" size="icon" className="h-8 w-8">
                              <MoreHorizontal className="h-4 w-4" />
                            </Button>
                          </DropdownMenuTrigger>
                          <DropdownMenuContent align="end">
                            {entry.status === 'waiting' && (
                              <DropdownMenuItem
                                onClick={() => handleStatusChange(entry.id, 'invited')}
                              >
                                <Send className="mr-2 h-4 w-4" /> Send Invite
                              </DropdownMenuItem>
                            )}
                            <DropdownMenuItem
                              onClick={() => handleStatusChange(entry.id, 'unsubscribed')}
                            >
                              Unsubscribe
                            </DropdownMenuItem>
                          </DropdownMenuContent>
                        </DropdownMenu>
                      </TableCell>
                    </TableRow>
                  );
                })}
              </TableBody>
            </Table>
          )}
        </CardContent>
      </Card>
    </div>
  );
}
