import { useState, ReactNode } from "react";
import { Head } from '@inertiajs/react';
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import AdminLayout from '@/layouts/AdminLayout';
import { format } from "date-fns";
import { toast } from "sonner";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Textarea } from "@/components/ui/textarea";
import {
  Table, TableBody, TableCell, TableHead, TableHeader, TableRow,
} from "@/components/ui/table";
import {
  Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter,
} from "@/components/ui/dialog";
import { CalendarClock, Check, X } from "lucide-react";

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

const statusColor: Record<string, string> = {
  pending: "bg-yellow-100 text-yellow-800 border-yellow-300",
  approved: "bg-green-100 text-green-800 border-green-300",
  rejected: "bg-red-100 text-red-800 border-red-300",
};

const DateChangeRequests = () => {
  const queryClient = useQueryClient();
  const [actionDialog, setActionDialog] = useState<{ id: string; action: "approved" | "rejected" } | null>(null);
  const [adminNotes, setAdminNotes] = useState("");

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

  const updateMutation = useMutation({
    mutationFn: async ({ id, status, notes }: { id: string; status: "approved" | "rejected"; notes: string }) => {
      const action = status === "approved" ? "approve" : "reject";
      const res = await fetch(`/api/admin/date-change-requests/${id}/${action}`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'Accept': 'application/json',
          'X-Requested-With': 'XMLHttpRequest',
          'X-CSRF-TOKEN': csrfToken(),
        },
        body: JSON.stringify({ admin_notes: notes }),
      });
      if (!res.ok) {
        const err = await res.json().catch(() => ({ error: 'Failed' }));
        throw new Error(err.error || err.message || 'Failed to update');
      }
      return res.json();
    },
    onSuccess: (data: any) => {
      if (actionDialog?.action === "approved") {
        toast.success(
          data?.email_sent
            ? `Request approved — customer emailed about the new date.`
            : "Request approved — booking date updated.",
        );
      } else {
        toast.success("Request rejected.");
      }
      // Refresh every list that shows an order date so the change is
      // reflected immediately across the admin UI.
      queryClient.invalidateQueries({ queryKey: ["date-change-requests"] });
      queryClient.invalidateQueries({ queryKey: ["admin-orders"] });
      queryClient.invalidateQueries({ queryKey: ["calendar-bookings-week"] });
      queryClient.invalidateQueries({ queryKey: ["calendar-orders-week"] });
      queryClient.invalidateQueries({ queryKey: ["order-delegates"] });
      queryClient.invalidateQueries({ queryKey: ["pending-date-changes"] });
      queryClient.invalidateQueries({ queryKey: ["notif-pending-reschedules"] });
      setActionDialog(null);
      setAdminNotes("");
    },
    onError: (err: Error) => toast.error(err.message),
  });

  const pendingCount = requests?.filter((r: any) => r.status === "pending").length ?? 0;

  return (
    <>
      <Head title="Date Change Requests" />
      <div className="space-y-6">
        <div className="flex items-center justify-between">
          <div>
            <h1 className="text-2xl font-bold flex items-center gap-2">
              <CalendarClock className="w-6 h-6 text-primary" />
              Date Change Requests
            </h1>
            <p className="text-muted-foreground text-sm mt-1">
              {pendingCount} pending request{pendingCount !== 1 ? "s" : ""} awaiting review
            </p>
          </div>
        </div>

        {isLoading ? (
          <p className="text-muted-foreground">Loading…</p>
        ) : !requests?.length ? (
          <p className="text-muted-foreground">No date change requests yet.</p>
        ) : (
          <div className="rounded-lg border bg-card overflow-hidden">
            <Table>
              <TableHeader>
                <TableRow>
                  <TableHead className="text-xs">Course</TableHead>
                  <TableHead className="text-xs">Customer</TableHead>
                  <TableHead className="text-xs">Current</TableHead>
                  <TableHead className="text-xs">Requested</TableHead>
                  <TableHead className="text-xs">Trainer</TableHead>
                  <TableHead className="text-xs">Reason</TableHead>
                  <TableHead className="text-xs">Status</TableHead>
                  <TableHead className="text-xs">Decided by</TableHead>
                  <TableHead className="text-xs text-right">Actions</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {requests.map((r: any) => {
                  const order = r.course_orders;
                  return (
                    <TableRow key={r.id}>
                      <TableCell className="text-xs font-medium max-w-[160px]">
                        <span className="line-clamp-2">{order?.courses?.title ?? "—"}</span>
                      </TableCell>
                      <TableCell className="text-xs">
                        <div>{order?.customer_name}</div>
                        <div className="text-[10px] text-muted-foreground">{order?.customer_email}</div>
                      </TableCell>
                      <TableCell className="text-xs whitespace-nowrap">
                        {order?.start_date ? format(new Date(order.start_date + "T00:00:00"), "d MMM yy") : "—"}
                      </TableCell>
                      <TableCell className="text-xs whitespace-nowrap font-medium">
                        {format(new Date(r.requested_date + "T00:00:00"), "d MMM yy")}
                      </TableCell>
                      <TableCell className="text-xs whitespace-nowrap">
                        {order?.trainers
                          ? `${order.trainers.first_name} ${order.trainers.last_name}`
                          : "—"}
                      </TableCell>
                      <TableCell className="text-xs max-w-[120px]">
                        <span className="line-clamp-2">{r.reason || "—"}</span>
                      </TableCell>
                      <TableCell>
                        <Badge variant="outline" className={`text-[10px] px-1.5 py-0 ${statusColor[r.status] ?? ""}`}>
                          {r.status}
                        </Badge>
                      </TableCell>
                      <TableCell className="text-xs whitespace-nowrap">
                        {r.decided_by_user ? (
                          <div>
                            <div className="font-medium">{r.decided_by_user.name || r.decided_by_user.email}</div>
                            {r.decided_at && (
                              <div className="text-[10px] text-muted-foreground">
                                {format(new Date(r.decided_at), "d MMM yy, HH:mm")}
                              </div>
                            )}
                          </div>
                        ) : (
                          <span className="text-muted-foreground">—</span>
                        )}
                      </TableCell>
                      <TableCell className="text-right">
                        {r.status === "pending" ? (
                          <div className="flex gap-1 justify-end">
                            <Button
                              size="sm"
                              variant="outline"
                              className="h-7 text-xs text-green-700 border-green-300 hover:bg-green-50"
                              onClick={() => { setActionDialog({ id: r.id, action: "approved" }); setAdminNotes(""); }}
                            >
                              <Check className="w-3 h-3 mr-1" /> Approve
                            </Button>
                            <Button
                              size="sm"
                              variant="outline"
                              className="h-7 text-xs text-destructive border-destructive/30 hover:bg-destructive/10"
                              onClick={() => { setActionDialog({ id: r.id, action: "rejected" }); setAdminNotes(""); }}
                            >
                              <X className="w-3 h-3 mr-1" /> Reject
                            </Button>
                          </div>
                        ) : (
                          <span className="text-[10px] text-muted-foreground line-clamp-2">{r.admin_notes || "—"}</span>
                        )}
                      </TableCell>
                    </TableRow>
                  );
                })}
              </TableBody>
            </Table>
          </div>
        )}

        <Dialog open={!!actionDialog} onOpenChange={() => setActionDialog(null)}>
          <DialogContent className="sm:max-w-md">
            <DialogHeader>
              <DialogTitle>
                {actionDialog?.action === "approved" ? "Approve" : "Reject"} Date Change
              </DialogTitle>
            </DialogHeader>
            <div className="space-y-3">
              <p className="text-sm text-muted-foreground">
                {actionDialog?.action === "approved"
                  ? "Approving will update the booking to the new requested date."
                  : "Please provide a reason for rejecting this request."}
              </p>
              <Textarea
                value={adminNotes}
                onChange={(e) => setAdminNotes(e.target.value)}
                placeholder="Notes (optional for approval, recommended for rejection)"
                rows={3}
              />
            </div>
            <DialogFooter>
              <Button variant="outline" onClick={() => setActionDialog(null)}>Cancel</Button>
              <Button
                variant={actionDialog?.action === "approved" ? "default" : "destructive"}
                disabled={updateMutation.isPending}
                onClick={() => {
                  if (actionDialog) {
                    updateMutation.mutate({ id: actionDialog.id, status: actionDialog.action, notes: adminNotes });
                  }
                }}
              >
                {updateMutation.isPending ? "Saving…" : actionDialog?.action === "approved" ? "Approve" : "Reject"}
              </Button>
            </DialogFooter>
          </DialogContent>
        </Dialog>
      </div>
    </>
  );
};

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

export default DateChangeRequests;
