import { useMemo, useState } from "react";
import { router } from "@inertiajs/react";
import { useQuery } from "@tanstack/react-query";
import { Search, Check, ExternalLink, Loader2 } from "lucide-react";
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog";
import { Input } from "@/components/ui/input";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";

interface VtCatalogRow {
  id: number;
  name: string;
  description: string;
  duration_minutes: number | null;
  rrp_cents: number | null;
  already_linked: boolean;
  local_course_id: string | null;
}

interface VideoTileCoursePickerProps {
  open: boolean;
  onOpenChange: (open: boolean) => void;
}

const VideoTileCoursePicker = ({ open, onOpenChange }: VideoTileCoursePickerProps) => {
  const [filter, setFilter] = useState("");

  const { data, isLoading, error } = useQuery<VtCatalogRow[]>({
    queryKey: ["videotile-catalog"],
    queryFn: async () => {
      const res = await fetch("/api/admin/videotile/catalog");
      if (!res.ok) {
        const body = await res.json().catch(() => ({}));
        throw new Error(body?.error || `Failed to load VideoTile catalog (HTTP ${res.status})`);
      }
      return res.json();
    },
    // Only hit VT when the dialog is actually open — saves a request on every
    // page load.
    enabled: open,
    staleTime: 60_000,
  });

  const filtered = useMemo(() => {
    if (!data) return [];
    const q = filter.toLowerCase().trim();
    if (!q) return data;
    return data.filter((c) =>
      c.name.toLowerCase().includes(q) || String(c.id) === q,
    );
  }, [data, filter]);

  const handlePick = (row: VtCatalogRow) => {
    if (row.already_linked && row.local_course_id) {
      // Already linked — jump to its edit screen instead of creating a duplicate.
      router.visit(`/admin/courses/${row.local_course_id}/edit`);
      return;
    }
    router.visit(`/admin/courses/new?vt=${row.id}`);
  };

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="max-w-3xl max-h-[80vh] flex flex-col">
        <DialogHeader>
          <DialogTitle>Add VideoTile Course</DialogTitle>
          <DialogDescription>
            Pick a course from VideoTile&rsquo;s catalog. We pre-fill the form with
            title, description, duration and RRP &mdash; you can adjust the price
            and any other field before saving.
          </DialogDescription>
        </DialogHeader>

        <div className="relative">
          <Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
          <Input
            placeholder="Search by name or VT id…"
            value={filter}
            onChange={(e) => setFilter(e.target.value)}
            className="pl-9"
          />
        </div>

        <div className="flex-1 overflow-y-auto border border-border rounded-lg">
          {isLoading && (
            <div className="flex items-center justify-center py-10 text-muted-foreground gap-2 text-sm">
              <Loader2 className="w-4 h-4 animate-spin" /> Loading VideoTile catalog…
            </div>
          )}

          {error instanceof Error && (
            <div className="py-10 text-center text-sm text-destructive">{error.message}</div>
          )}

          {data && filtered.length === 0 && (
            <div className="py-10 text-center text-sm text-muted-foreground">
              No courses match &ldquo;{filter}&rdquo;.
            </div>
          )}

          <ul className="divide-y divide-border">
            {filtered.map((c) => (
              <li
                key={c.id}
                className="flex items-center gap-3 px-4 py-3 hover:bg-muted/40 cursor-pointer"
                onClick={() => handlePick(c)}
              >
                <div className="flex-1 min-w-0">
                  <div className="flex items-center gap-2">
                    <p className="text-sm font-medium text-foreground truncate">{c.name}</p>
                    {c.already_linked && (
                      <Badge variant="outline" className="text-[10px] gap-1">
                        <Check className="w-3 h-3" /> already added
                      </Badge>
                    )}
                  </div>
                  <div className="text-xs text-muted-foreground mt-0.5 truncate">
                    VT #{c.id}
                    {c.duration_minutes ? ` · ${c.duration_minutes} min` : ""}
                    {c.rrp_cents != null ? ` · RRP £${(c.rrp_cents / 100).toFixed(2)}` : ""}
                  </div>
                </div>
                <Button size="sm" variant={c.already_linked ? "outline" : "default"}>
                  {c.already_linked ? "Open existing" : "Use this"}
                  <ExternalLink className="w-3 h-3 ml-1.5" />
                </Button>
              </li>
            ))}
          </ul>
        </div>
      </DialogContent>
    </Dialog>
  );
};

export default VideoTileCoursePicker;
