import { useState } from "react";
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import { Button } from "@/components/ui/button";
import { Label } from "@/components/ui/label";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogTrigger } from "@/components/ui/dialog";
import { toast } from "sonner";
import { Plus, Trash2 } from "lucide-react";

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

interface TrainerAssignmentsDialogProps {
  courseId: string;
  courseTitle?: string;
}

const TrainerAssignmentsDialog = ({ courseId, courseTitle }: TrainerAssignmentsDialogProps) => {
  const queryClient = useQueryClient();
  const [open, setOpen] = useState(false);
  const [selectedTrainerId, setSelectedTrainerId] = useState("");
  const [selectedVenueId, setSelectedVenueId] = useState("");

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

  const { data: venues } = useQuery({
    queryKey: ["venues", "active"],
    queryFn: async () => {
      const res = await fetch("/api/admin/venues?status=active");
      if (!res.ok) return [];
      return res.json();
    },
    enabled: open,
  });

  const { data: courseTrainers } = useQuery({
    queryKey: ["course_trainers"],
    queryFn: async () => {
      const res = await fetch("/api/admin/course-trainers?with=courses,trainers,venues");
      if (!res.ok) return [];
      return res.json();
    },
    enabled: open,
  });

  const assignments = (courseTrainers ?? []).filter((ct: any) => ct.course_id === courseId);

  const invalidateAll = () => {
    queryClient.invalidateQueries({ queryKey: ["course_trainers"] });
    queryClient.invalidateQueries({ queryKey: ["course-trainers", courseId] });
  };

  const assignMutation = useMutation({
    mutationFn: async ({ trainer_id, venue_id }: { trainer_id: string; venue_id: string }) => {
      const res = await fetch('/api/admin/course-trainers', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json', 'X-CSRF-TOKEN': csrfToken() },
        body: JSON.stringify({ course_id: courseId, trainer_id, venue_id }),
      });
      if (!res.ok) throw new Error('Failed to assign trainer');
    },
    onSuccess: () => {
      invalidateAll();
      toast.success("Trainer assigned to course at venue");
      setSelectedTrainerId("");
      setSelectedVenueId("");
    },
    onError: (e: Error) => toast.error(e.message),
  });

  const removeMutation = useMutation({
    mutationFn: async (id: string) => {
      const res = await fetch(`/api/admin/course-trainers/${id}`, {
        method: 'DELETE',
        headers: { 'Content-Type': 'application/json', 'X-CSRF-TOKEN': csrfToken() },
      });
      if (!res.ok) throw new Error('Failed to remove assignment');
    },
    onSuccess: () => {
      invalidateAll();
      toast.success("Assignment removed");
    },
    onError: (e: Error) => toast.error(e.message),
  });

  return (
    <Dialog open={open} onOpenChange={setOpen}>
      <DialogTrigger asChild>
        <Button type="button" variant="outline" size="sm">Manage Trainer Assignments</Button>
      </DialogTrigger>
      <DialogContent className="max-w-3xl">
        <DialogHeader>
          <DialogTitle>Trainer ↔ Venue Assignments{courseTitle ? ` — ${courseTitle}` : ''}</DialogTitle>
        </DialogHeader>

        <div className="bg-muted/30 border border-border rounded-lg p-4">
          <h3 className="font-semibold text-foreground mb-3 text-sm">Assign Trainer + Venue</h3>
          <div className="grid sm:grid-cols-3 gap-3 items-end">
            <div>
              <Label className="mb-1.5 block text-sm">Trainer</Label>
              <Select value={selectedTrainerId} onValueChange={setSelectedTrainerId}>
                <SelectTrigger><SelectValue placeholder="Select trainer" /></SelectTrigger>
                <SelectContent>
                  {trainers?.map((t: any) => (
                    <SelectItem key={t.id} value={t.id}>{t.first_name} {t.last_name}</SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </div>
            <div>
              <Label className="mb-1.5 block text-sm">Venue</Label>
              <Select value={selectedVenueId} onValueChange={setSelectedVenueId}>
                <SelectTrigger><SelectValue placeholder="Select venue" /></SelectTrigger>
                <SelectContent>
                  {venues?.map((v: any) => (
                    <SelectItem key={v.id} value={v.id}>{v.name}</SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </div>
            <Button
              type="button"
              variant="hero"
              disabled={!selectedTrainerId || !selectedVenueId || assignMutation.isPending}
              onClick={() => assignMutation.mutate({
                trainer_id: selectedTrainerId,
                venue_id: selectedVenueId,
              })}
            >
              <Plus className="h-4 w-4 mr-1" /> Assign
            </Button>
          </div>
        </div>

        <div className="bg-card border border-border rounded-lg overflow-hidden max-h-[400px] overflow-y-auto">
          <Table>
            <TableHeader>
              <TableRow>
                <TableHead>Trainer</TableHead>
                <TableHead>Venue</TableHead>
                <TableHead className="w-[80px]">Actions</TableHead>
              </TableRow>
            </TableHeader>
            <TableBody>
              {assignments.map((ct: any) => (
                <TableRow key={ct.id}>
                  <TableCell>{ct.trainers?.first_name} {ct.trainers?.last_name}</TableCell>
                  <TableCell>{ct.venues?.name || <span className="text-muted-foreground italic">No venue</span>}</TableCell>
                  <TableCell>
                    <Button type="button" variant="ghost" size="sm" onClick={() => removeMutation.mutate(ct.id)}>
                      <Trash2 className="h-3 w-3 text-destructive" />
                    </Button>
                  </TableCell>
                </TableRow>
              ))}
              {assignments.length === 0 && (
                <TableRow>
                  <TableCell colSpan={3} className="text-center text-muted-foreground py-8">
                    No trainers assigned to this course yet.
                  </TableCell>
                </TableRow>
              )}
            </TableBody>
          </Table>
        </div>
      </DialogContent>
    </Dialog>
  );
};

export default TrainerAssignmentsDialog;
