import { useState, ReactNode } from "react";
import { router } from "@inertiajs/react";
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import { Button } from "@/components/ui/button";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import { Badge } from "@/components/ui/badge";
import { Switch } from "@/components/ui/switch";
import { Label } from "@/components/ui/label";
import { Dialog, DialogContent, DialogHeader, DialogTitle } from "@/components/ui/dialog";
import { toast } from "sonner";
import { Plus, Pencil, Trash2, ShoppingCart, ClipboardCheck, Check, X } from "lucide-react";
import AdminLayout from "@/layouts/AdminLayout";
import { useCategories } from "@/hooks/useCategories";
import { useAuth } from "@/hooks/useAuth";

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

const pendingKeys = (c: any): string[] =>
  c?.pending_changes && typeof c.pending_changes === "object" ? Object.keys(c.pending_changes) : [];
// A course needs sys-admin attention if it's never been approved or has queued edits.
const needsApproval = (c: any): boolean => c?.marketplace_status === "pending" || pendingKeys(c).length > 0;

const fmtVal = (v: any): string => {
  if (v === null || v === undefined || v === "") return "—";
  if (typeof v === "boolean") return v ? "Yes" : "No";
  return String(v);
};

const Courses = () => {
  const queryClient = useQueryClient();
  const { isSysLevel } = useAuth();
  const sysLevel = isSysLevel();
  const [categoryFilter, setCategoryFilter] = useState("all");
  const [showInactive, setShowInactive] = useState(false);
  const [reviewing, setReviewing] = useState<any | null>(null);
  // Filter only shows non-E-Learning categories (E-Learning has its own admin page).
  const { data: mainCategories = [] } = useCategories("main");
  const filterOptions = mainCategories.filter((c) => c.name !== "E-Learning");

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

  const deleteMutation = useMutation({
    mutationFn: async (id: string) => {
      const res = await fetch(`/api/admin/courses/${id}`, {
        method: 'DELETE',
        headers: { 'Content-Type': 'application/json', 'X-CSRF-TOKEN': csrfToken() },
      });
      if (!res.ok) {
        const data = await res.json().catch(() => null);
        throw new Error(data?.error || 'Failed to delete course');
      }
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["admin-courses"] });
      toast.success("Course deleted");
    },
    onError: (e: Error) => toast.error(e.message, { duration: 8000 }),
  });

  const moderateMutation = useMutation({
    mutationFn: async ({ id, action }: { id: string; action: "approve" | "reject" }) => {
      const res = await fetch(`/api/admin/courses/${id}/${action}`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json', 'X-CSRF-TOKEN': csrfToken() },
      });
      if (!res.ok) throw new Error(`Failed to ${action} course`);
    },
    onSuccess: (_d, { action }) => {
      queryClient.invalidateQueries({ queryKey: ["admin-courses"] });
      toast.success(action === "approve" ? "Course approved — now live" : "Changes rejected");
      setReviewing(null);
    },
    onError: (e: Error) => toast.error(e.message),
  });

  const filtered = courses?.filter(
    (c: any) =>
      c.category !== "E-Learning"
      && (categoryFilter === "all" || c.category === categoryFilter)
      && (showInactive || c.is_active)
  );

  const approvalBadge = (c: any) => {
    if (c.marketplace_status === "pending") return <Badge className="bg-amber-500 text-white">Pending approval</Badge>;
    if (pendingKeys(c).length > 0) return <Badge className="bg-amber-500 text-white">Changes pending</Badge>;
    if (c.marketplace_status === "rejected") return <Badge variant="destructive">Rejected</Badge>;
    return null;
  };

  return (
    <div>
      <div className="flex items-center justify-between mb-6">
        <h1 className="text-2xl font-bold text-foreground">Courses</h1>
        <div className="flex items-center gap-3">
          <div className="flex items-center gap-2">
            <Switch id="show-inactive" checked={showInactive} onCheckedChange={setShowInactive} />
            <Label htmlFor="show-inactive" className="text-sm text-muted-foreground cursor-pointer">
              Show inactive
            </Label>
          </div>
          <Select value={categoryFilter} onValueChange={setCategoryFilter}>
            <SelectTrigger className="w-[160px]">
              <SelectValue />
            </SelectTrigger>
            <SelectContent>
              <SelectItem value="all">All Categories</SelectItem>
              {filterOptions.map((o) => (
                <SelectItem key={o.id} value={o.name}>{o.name}</SelectItem>
              ))}
            </SelectContent>
          </Select>
          <Button variant="hero" onClick={() => router.visit("/admin/courses/new")}>
            <Plus className="mr-2 h-4 w-4" /> Add Course
          </Button>
        </div>
      </div>

      {isLoading ? (
        <p className="text-muted-foreground">Loading courses...</p>
      ) : (
        <div className="bg-card border border-border rounded-xl overflow-hidden">
          <Table>
            <TableHeader>
              <TableRow>
                <TableHead>Title</TableHead>
                <TableHead>Category</TableHead>
                <TableHead>Owner</TableHead>
                <TableHead>Days</TableHead>
                <TableHead>Price</TableHead>
                <TableHead>Status</TableHead>
                <TableHead className="w-[160px]">Actions</TableHead>
              </TableRow>
            </TableHeader>
            <TableBody>
              {filtered?.map((c: any) => (
                <TableRow
                  key={c.id}
                  className="cursor-pointer hover:bg-muted/50"
                  onClick={() => router.visit(`/admin/courses/${c.id}/edit`)}
                >
                  <TableCell className="font-medium">{c.title}</TableCell>
                  <TableCell>{c.category}</TableCell>
                  <TableCell className="text-sm">
                    {c.owner_company_id
                      ? (c.owner_company_name || "Company")
                      : <span className="text-muted-foreground">UTC</span>}
                  </TableCell>
                  <TableCell>{c.days}</TableCell>
                  <TableCell>£{(c.price_cents / 100).toFixed(2)}</TableCell>
                  <TableCell>
                    <div className="flex flex-wrap items-center gap-1.5">
                      <Badge variant={c.is_active ? "default" : "secondary"}>
                        {c.is_active ? "Active" : "Inactive"}
                      </Badge>
                      {approvalBadge(c)}
                    </div>
                  </TableCell>
                  <TableCell>
                    {/* stopPropagation so the action buttons don't also trigger the row's edit-navigation */}
                    <div className="flex gap-1" onClick={(e) => e.stopPropagation()}>
                      {sysLevel && needsApproval(c) && (
                        <Button variant="ghost" size="sm" title="Review for approval" onClick={() => setReviewing(c)}>
                          <ClipboardCheck className="h-3 w-3 text-amber-600" />
                        </Button>
                      )}
                      <Button
                        variant="ghost"
                        size="sm"
                        title="View orders for this course"
                        onClick={() => router.visit(`/admin/orders?course_id=${c.id}`)}
                      >
                        <ShoppingCart className="h-3 w-3" />
                      </Button>
                      <Button variant="ghost" size="sm" title="Edit course" onClick={() => router.visit(`/admin/courses/${c.id}/edit`)}>
                        <Pencil className="h-3 w-3" />
                      </Button>
                      <Button variant="ghost" size="sm" title="Delete course" onClick={() => deleteMutation.mutate(c.id)}>
                        <Trash2 className="h-3 w-3 text-destructive" />
                      </Button>
                    </div>
                  </TableCell>
                </TableRow>
              ))}
              {filtered?.length === 0 && (
                <TableRow>
                  <TableCell colSpan={7} className="text-center text-muted-foreground py-8">No courses found.</TableCell>
                </TableRow>
              )}
            </TableBody>
          </Table>
        </div>
      )}

      {/* Approval review dialog (sys-level) */}
      <Dialog open={!!reviewing} onOpenChange={(o) => !o && setReviewing(null)}>
        <DialogContent className="sm:max-w-2xl max-h-[85vh] overflow-y-auto">
          <DialogHeader>
            <DialogTitle className="flex items-center gap-2">
              <ClipboardCheck className="h-5 w-5 text-amber-600" />
              Review course
            </DialogTitle>
          </DialogHeader>

          {reviewing && (
            <div className="space-y-4">
              <div>
                <p className="text-sm font-semibold text-foreground">{reviewing.title}</p>
                <p className="text-xs text-muted-foreground">
                  {reviewing.owner_company_name || "Company"} · {reviewing.category}
                </p>
              </div>

              {reviewing.marketplace_status === "pending" ? (
                <div className="rounded-lg border border-amber-500/30 bg-amber-500/10 p-3 space-y-2">
                  <p className="text-sm font-medium text-foreground">New course — not yet live</p>
                  <p className="text-xs text-muted-foreground">Approving publishes it to the company's storefront and the main marketplace.</p>
                  <div className="grid grid-cols-2 gap-2 text-sm pt-1">
                    <div><span className="text-muted-foreground text-xs">Price</span><p>£{(reviewing.price_cents / 100).toFixed(2)}</p></div>
                    <div><span className="text-muted-foreground text-xs">Duration</span><p>{reviewing.days} day{reviewing.days > 1 ? "s" : ""}</p></div>
                    {reviewing.certification && <div className="col-span-2"><span className="text-muted-foreground text-xs">Certification</span><p>{reviewing.certification}</p></div>}
                    {reviewing.description && <div className="col-span-2"><span className="text-muted-foreground text-xs">Description</span><p className="whitespace-pre-line">{reviewing.description}</p></div>}
                  </div>
                </div>
              ) : (
                <div className="space-y-2">
                  <p className="text-sm font-medium text-foreground">Proposed changes to a live course</p>
                  <div className="rounded-lg border border-border overflow-hidden">
                    <Table>
                      <TableHeader>
                        <TableRow>
                          <TableHead>Field</TableHead>
                          <TableHead>Current</TableHead>
                          <TableHead>Proposed</TableHead>
                        </TableRow>
                      </TableHeader>
                      <TableBody>
                        {pendingKeys(reviewing).map((k) => (
                          <TableRow key={k}>
                            <TableCell className="font-medium text-xs">{k}</TableCell>
                            <TableCell className="text-xs text-muted-foreground max-w-[180px] truncate" title={fmtVal(reviewing[k])}>{fmtVal(reviewing[k])}</TableCell>
                            <TableCell className="text-xs max-w-[180px] truncate" title={fmtVal(reviewing.pending_changes[k])}>{fmtVal(reviewing.pending_changes[k])}</TableCell>
                          </TableRow>
                        ))}
                      </TableBody>
                    </Table>
                  </div>
                </div>
              )}

              <div className="flex justify-end gap-2 pt-2">
                <Button
                  variant="outline"
                  onClick={() => moderateMutation.mutate({ id: reviewing.id, action: "reject" })}
                  disabled={moderateMutation.isPending}
                >
                  <X className="h-4 w-4 mr-1.5" /> Reject
                </Button>
                <Button
                  onClick={() => moderateMutation.mutate({ id: reviewing.id, action: "approve" })}
                  disabled={moderateMutation.isPending}
                >
                  <Check className="h-4 w-4 mr-1.5" /> Approve
                </Button>
              </div>
            </div>
          )}
        </DialogContent>
      </Dialog>
    </div>
  );
};

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

export default Courses;
