import { useState, ReactNode } from "react";
import { Head } from '@inertiajs/react';
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import AdminLayout from '@/layouts/AdminLayout';
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Input } from "@/components/ui/input";
import { toast } from "sonner";
import { format } from "date-fns";
import { Clock, CheckCircle2, XCircle, Download, Bell, Search } from "lucide-react";
import { exportToCSV } from "@/lib/csv-export";

const csrfToken = () =>
  (document.querySelector('meta[name="csrf-token"]') as HTMLMetaElement | null)?.content ?? '';

const statusColors: Record<string, string> = {
  waiting: "bg-amber-500 text-white",
  notified: "bg-blue-500 text-white",
  booked: "bg-green-600 text-white",
  cancelled: "bg-destructive text-destructive-foreground",
};

const Waitlist = () => {
  const queryClient = useQueryClient();
  const [statusFilter, setStatusFilter] = useState("all");
  const [search, setSearch] = useState("");

  const { data: waitlist, isLoading } = useQuery({
    queryKey: ["admin-waitlist"],
    queryFn: async () => {
      const res = await fetch('/api/admin/waitlist');
      if (!res.ok) return [];
      return res.json();
    },
  });

  const { data: courses } = useQuery({
    queryKey: ["courses"],
    queryFn: async () => {
      const res = await fetch('/api/admin/courses');
      if (!res.ok) return [];
      return res.json();
    },
  });

  const updateStatusMutation = useMutation({
    mutationFn: async ({ id, status }: { id: string; status: string }) => {
      const res = await fetch(`/api/admin/waitlist/${id}`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json', 'X-CSRF-TOKEN': csrfToken() },
        body: JSON.stringify({ status }),
      });
      if (!res.ok) throw new Error('Failed to update');
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["admin-waitlist"] });
      toast.success("Waitlist entry updated");
    },
    onError: (e: Error) => toast.error(e.message),
  });

  const getCourseName = (id: string) => courses?.find((c: any) => c.id === id)?.title || "Unknown";

  const filtered = waitlist?.filter((w: any) => {
    if (statusFilter !== "all" && w.status !== statusFilter) return false;
    if (search) {
      const s = search.toLowerCase();
      return w.contact_name.toLowerCase().includes(s) || w.contact_email.toLowerCase().includes(s);
    }
    return true;
  });

  const handleExport = () => {
    if (!filtered?.length) return;
    exportToCSV(
      filtered.map((w: any) => ({
        Course: getCourseName(w.course_id),
        "Start Date": w.start_date,
        Name: w.contact_name,
        Email: w.contact_email,
        Phone: w.contact_phone || "",
        Delegates: w.num_delegates,
        Status: w.status,
        "Created At": format(new Date(w.created_at), "dd/MM/yyyy HH:mm"),
      })),
      "waitlist-export"
    );
  };

  return (
    <>
      <Head title="Course Waitlist" />
      <div>
        <div className="flex items-center justify-between mb-6">
          <div className="flex items-center gap-3">
            <Clock className="h-6 w-6 text-primary" />
            <h1 className="text-2xl font-bold text-foreground">Course Waitlist</h1>
            {waitlist && (
              <Badge variant="outline">{waitlist.filter((w: any) => w.status === "waiting").length} waiting</Badge>
            )}
          </div>
          <Button variant="outline" size="sm" onClick={handleExport}>
            <Download className="h-4 w-4 mr-1" /> Export CSV
          </Button>
        </div>

        <div className="flex gap-3 mb-6">
          <div className="relative flex-1 max-w-sm">
            <Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
            <Input
              placeholder="Search name or email..."
              value={search}
              onChange={(e) => setSearch(e.target.value)}
              className="pl-10"
            />
          </div>
          <Select value={statusFilter} onValueChange={setStatusFilter}>
            <SelectTrigger className="w-[160px]">
              <SelectValue placeholder="All statuses" />
            </SelectTrigger>
            <SelectContent>
              <SelectItem value="all">All Statuses</SelectItem>
              <SelectItem value="waiting">Waiting</SelectItem>
              <SelectItem value="notified">Notified</SelectItem>
              <SelectItem value="booked">Booked</SelectItem>
              <SelectItem value="cancelled">Cancelled</SelectItem>
            </SelectContent>
          </Select>
        </div>

        <div className="bg-card border border-border rounded-xl overflow-hidden">
          <Table>
            <TableHeader>
              <TableRow>
                <TableHead>Course</TableHead>
                <TableHead>Date</TableHead>
                <TableHead>Contact</TableHead>
                <TableHead>Delegates</TableHead>
                <TableHead>Status</TableHead>
                <TableHead>Requested</TableHead>
                <TableHead className="w-[140px]">Actions</TableHead>
              </TableRow>
            </TableHeader>
            <TableBody>
              {filtered?.map((w: any) => (
                <TableRow key={w.id}>
                  <TableCell className="font-medium">{getCourseName(w.course_id)}</TableCell>
                  <TableCell>{format(new Date(w.start_date), "dd/MM/yyyy")}</TableCell>
                  <TableCell>
                    <div className="text-sm font-medium">{w.contact_name}</div>
                    <div className="text-xs text-muted-foreground">{w.contact_email}</div>
                  </TableCell>
                  <TableCell>{w.num_delegates}</TableCell>
                  <TableCell>
                    <Badge className={statusColors[w.status] || ""}>{w.status}</Badge>
                  </TableCell>
                  <TableCell className="text-sm text-muted-foreground">
                    {format(new Date(w.created_at), "dd/MM/yyyy")}
                  </TableCell>
                  <TableCell>
                    <div className="flex gap-1">
                      {w.status === "waiting" && (
                        <>
                          <Button
                            variant="ghost"
                            size="sm"
                            title="Mark as notified"
                            onClick={() => updateStatusMutation.mutate({ id: w.id, status: "notified" })}
                          >
                            <Bell className="h-3 w-3 text-blue-500" />
                          </Button>
                          <Button
                            variant="ghost"
                            size="sm"
                            title="Mark as booked"
                            onClick={() => updateStatusMutation.mutate({ id: w.id, status: "booked" })}
                          >
                            <CheckCircle2 className="h-3 w-3 text-green-500" />
                          </Button>
                        </>
                      )}
                      {w.status === "notified" && (
                        <Button
                          variant="ghost"
                          size="sm"
                          title="Mark as booked"
                          onClick={() => updateStatusMutation.mutate({ id: w.id, status: "booked" })}
                        >
                          <CheckCircle2 className="h-3 w-3 text-green-500" />
                        </Button>
                      )}
                      {(w.status === "waiting" || w.status === "notified") && (
                        <Button
                          variant="ghost"
                          size="sm"
                          title="Cancel"
                          onClick={() => updateStatusMutation.mutate({ id: w.id, status: "cancelled" })}
                        >
                          <XCircle className="h-3 w-3 text-destructive" />
                        </Button>
                      )}
                    </div>
                  </TableCell>
                </TableRow>
              ))}
              {(!filtered || filtered.length === 0) && (
                <TableRow>
                  <TableCell colSpan={7} className="text-center text-muted-foreground py-8">
                    No waitlist entries found.
                  </TableCell>
                </TableRow>
              )}
            </TableBody>
          </Table>
        </div>
      </div>
    </>
  );
};

Waitlist.layout = (page: ReactNode) => <AdminLayout>{page}</AdminLayout>;

export default Waitlist;
