import { useState } from "react";
import { Card, CardContent } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Checkbox } from "@/components/ui/checkbox";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter } from "@/components/ui/dialog";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { useBatches, useCourses, useTeachers } from "@/hooks/queries";
import { lmsService } from "@/services/lms.service";
import { classroomsService } from "@/services/classrooms.service";
import { useQuery } from "@tanstack/react-query";
import { api } from "@/lib/api-client";
import { useMutation, useQueryClient } from "@tanstack/react-query";
import { Search, Plus, Trash2, Pencil } from "lucide-react";
import { Link } from "react-router-dom";
import { useToast } from "@/hooks/use-toast";
import AiBatchOptimizer from "@/components/ai/AiBatchOptimizer";
import AiCreationAssistant from "@/components/ai/AiCreationAssistant";
import AiTipBanner from "@/components/ai/AiTipBanner";

type BatchForm = {
  name: string;
  course_id: string;
  course_section_id: string;
  term_key: string;
  classroom_id: string;
  start_date: string;
  end_date: string;
  max_students: string;
  teacher_ids: number[];
};

const EMPTY_FORM: BatchForm = {
  name: "",
  course_id: "",
  course_section_id: "",
  term_key: "",
  classroom_id: "",
  start_date: "",
  end_date: "",
  max_students: "30",
  teacher_ids: [],
};

export default function AdminBatches() {
  const [search, setSearch] = useState("");
  const [createOpen, setCreateOpen] = useState(false);
  const [editOpen, setEditOpen] = useState(false);
  const [editingBatchId, setEditingBatchId] = useState<number | null>(null);
  const [form, setForm] = useState<BatchForm>(EMPTY_FORM);
  const [editForm, setEditForm] = useState<BatchForm>(EMPTY_FORM);
  const { toast } = useToast();
  const qc = useQueryClient();
  const { data: batchesData, isLoading } = useBatches();
  const { data: coursesData } = useCourses({ size: 200 });
  const { data: teachersData } = useTeachers({ size: 200 });
  const classroomsQ = useQuery({
    queryKey: ["lms-classrooms-light"],
    queryFn: async () => (await classroomsService.list({ size: 200 })).items,
  });
  const createSectionsQ = useQuery({
    queryKey: ["course-sections", form.course_id],
    queryFn: () =>
      form.course_id
        ? lmsService.listCourseSections(Number(form.course_id))
        : Promise.resolve({ items: [], total: 0 }),
    enabled: !!form.course_id,
  });
  const editSectionsQ = useQuery({
    queryKey: ["course-sections", editForm.course_id],
    queryFn: () =>
      editForm.course_id
        ? lmsService.listCourseSections(Number(editForm.course_id))
        : Promise.resolve({ items: [], total: 0 }),
    enabled: !!editForm.course_id,
  });
  const batches = batchesData?.items ?? [];
  const courses = coursesData?.items ?? [];
  const teachers = teachersData?.items ?? [];
  const classrooms = classroomsQ.data ?? [];
  const createSections = createSectionsQ.data?.items ?? [];
  const editSections = editSectionsQ.data?.items ?? [];

  const createMutation = useMutation({
    mutationFn: (data: Record<string, unknown>) => lmsService.createBatch(data as never),
    onSuccess: () => {
      qc.invalidateQueries({ queryKey: ["lms", "batches"] });
      setCreateOpen(false);
      setForm(EMPTY_FORM);
      toast({ title: "Batch created" });
    },
    onError: (err: Error) => toast({ title: "Error", description: err.message, variant: "destructive" }),
  });

  const updateMutation = useMutation({
    mutationFn: ({ id, data }: { id: number; data: Record<string, unknown> }) => lmsService.updateBatch(id, data as never),
    onSuccess: () => {
      qc.invalidateQueries({ queryKey: ["lms", "batches"] });
      setEditOpen(false);
      setEditingBatchId(null);
      setEditForm(EMPTY_FORM);
      toast({ title: "Batch updated" });
    },
    onError: (err: Error) => toast({ title: "Error", description: err.message, variant: "destructive" }),
  });

  async function handleDelete(id: number, name: string) {
    if (!window.confirm(`Delete batch "${name}"?`)) return;
    try {
      await api.delete(`/batches/${id}`);
      qc.invalidateQueries({ queryKey: ["lms", "batches"] });
      toast({ title: "Batch deleted" });
    } catch (e: unknown) {
      const msg = e instanceof Error ? e.message : String(e);
      toast({ title: "Delete failed", description: msg, variant: "destructive" });
    }
  }

  function openEdit(batch: (typeof batches)[number]) {
    setEditingBatchId(batch.id);
    setEditForm({
      name: batch.name || "",
      course_id: String(batch.course_id || ""),
      course_section_id: batch.course_section_id ? String(batch.course_section_id) : "",
      term_key: batch.term_key || "",
      classroom_id: batch.classroom_id ? String(batch.classroom_id) : "",
      start_date: batch.start_date || "",
      end_date: batch.end_date || "",
      max_students: String(batch.capacity || 30),
      teacher_ids: batch.teacher_ids || [],
    });
    setEditOpen(true);
  }

  if (isLoading) return <div className="flex items-center justify-center min-h-[400px]"><div className="animate-spin rounded-full h-8 w-8 border-b-2 border-primary" /></div>;

  const filtered = batches.filter(b => b.name.toLowerCase().includes(search.toLowerCase()));

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <div><h1 className="text-2xl font-bold">Batches</h1><p className="text-muted-foreground">Manage student batches and groups.</p></div>
        <div className="flex gap-2">
          <AiBatchOptimizer batchId={batches[0]?.id} />
          <AiCreationAssistant type="batch" />
          <Button onClick={() => setCreateOpen(true)}><Plus className="mr-2 h-4 w-4" />Create Batch</Button>
        </div>
      </div>
      <AiTipBanner context="admin-batches" variant="recommendation" />
      <div className="relative 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 batches..." value={search} onChange={e => setSearch(e.target.value)} className="pl-9" /></div>
      <Card>
        <CardContent className="pt-6">
          <Table>
            <TableHeader>
              <TableRow>
                <TableHead>Batch</TableHead>
                <TableHead>Course</TableHead>
                <TableHead>Section</TableHead>
                <TableHead>Term</TableHead>
                <TableHead>Classroom</TableHead>
                <TableHead>Teachers</TableHead>
                <TableHead>Students</TableHead>
                <TableHead>Schedule</TableHead>
                <TableHead>Status</TableHead>
                <TableHead></TableHead>
              </TableRow>
            </TableHeader>
            <TableBody>
              {filtered.map((b) => (
                <TableRow key={b.id}>
                  <TableCell className="font-medium">{b.name}</TableCell>
                  <TableCell>{b.course_name}</TableCell>
                  <TableCell>
                    {b.course_section_name ? (
                      <Badge variant="outline" className="font-mono text-xs">
                        {b.course_section_code || b.course_section_name}
                      </Badge>
                    ) : (
                      <span className="text-xs text-muted-foreground">—</span>
                    )}
                  </TableCell>
                  <TableCell className="text-xs text-muted-foreground">
                    {b.term_key || "—"}
                  </TableCell>
                  <TableCell className="text-sm text-muted-foreground">
                    {b.classroom_name || "—"}
                  </TableCell>
                  <TableCell>
                    {b.teacher_names?.length ? b.teacher_names.join(", ") : b.teacher_name || "—"}
                  </TableCell>
                  <TableCell>
                    {b.student_count}/{b.capacity}
                  </TableCell>
                  <TableCell className="text-xs">{b.schedule}</TableCell>
                  <TableCell>
                    <Badge
                      variant={b.status === "active" ? "default" : "secondary"}
                      className="capitalize"
                    >
                      {b.status}
                    </Badge>
                  </TableCell>
                  <TableCell>
                    <div className="flex gap-1">
                      <Button size="sm" variant="ghost" asChild>
                        <Link to={`/admin/batches/${b.id}`}>View</Link>
                      </Button>
                      <Button variant="ghost" size="icon" onClick={() => openEdit(b)}>
                        <Pencil className="h-4 w-4" />
                      </Button>
                      <Button
                        variant="ghost"
                        size="icon"
                        onClick={() => handleDelete(b.id, b.name)}
                      >
                        <Trash2 className="h-4 w-4 text-destructive" />
                      </Button>
                    </div>
                  </TableCell>
                </TableRow>
              ))}
            </TableBody>
          </Table>
        </CardContent>
      </Card>
      <Dialog open={createOpen} onOpenChange={setCreateOpen}>
        <DialogContent>
          <DialogHeader><DialogTitle>Create Batch</DialogTitle></DialogHeader>
          <div className="space-y-4">
            <div className="space-y-2"><Label>Batch Name *</Label><Input placeholder="e.g. IELTS Morning B" value={form.name} onChange={e => setForm(f => ({ ...f, name: e.target.value }))} /></div>
            <div className="space-y-2">
              <Label>Course *</Label>
              <Select
                value={form.course_id || "__none__"}
                onValueChange={(v) =>
                  setForm((f) => ({
                    ...f,
                    course_id: v === "__none__" ? "" : v,
                    course_section_id: "",
                  }))
                }
              >
                <SelectTrigger><SelectValue placeholder="Select course" /></SelectTrigger>
                <SelectContent>
                  <SelectItem value="__none__">— Select —</SelectItem>
                  {courses.map(c => <SelectItem key={c.id} value={String(c.id)}>{c.title}</SelectItem>)}
                </SelectContent>
              </Select>
            </div>
            <div className="grid grid-cols-2 gap-4">
              <div className="space-y-2">
                <Label>Section (optional)</Label>
                <Select
                  value={form.course_section_id || "__none__"}
                  onValueChange={(v) =>
                    setForm((f) => ({ ...f, course_section_id: v === "__none__" ? "" : v }))
                  }
                  disabled={!form.course_id}
                >
                  <SelectTrigger>
                    <SelectValue placeholder="Whole course" />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="__none__">Whole course (no section)</SelectItem>
                    {createSections.map((s) => (
                      <SelectItem key={s.id} value={String(s.id)}>
                        {s.code ? `${s.code} · ${s.name}` : s.name}
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
                <p className="text-[11px] text-muted-foreground">
                  Pick a course section template to keep batches isolated per group.
                </p>
              </div>
              <div className="space-y-2">
                <Label>Term Key (optional)</Label>
                <Input
                  placeholder="e.g. 2026-T1"
                  value={form.term_key}
                  onChange={(e) => setForm((f) => ({ ...f, term_key: e.target.value }))}
                />
                <p className="text-[11px] text-muted-foreground">
                  One batch per (classroom × course × section × term).
                </p>
              </div>
            </div>
            <div className="space-y-2">
              <Label>Classroom (optional)</Label>
              <Select value={form.classroom_id || "__none__"} onValueChange={v => setForm(f => ({ ...f, classroom_id: v === "__none__" ? "" : v }))}>
                <SelectTrigger><SelectValue placeholder="No classroom" /></SelectTrigger>
                <SelectContent>
                  <SelectItem value="__none__">No classroom</SelectItem>
                  {classrooms.map(c => <SelectItem key={c.id} value={String(c.id)}>{c.name} ({c.student_count} students)</SelectItem>)}
                </SelectContent>
              </Select>
              <p className="text-xs text-muted-foreground">Selecting a classroom links the batch to that homeroom. Use the Classrooms page to auto-enroll the roster.</p>
            </div>
            <div className="grid grid-cols-2 gap-4">
              <div className="space-y-2"><Label>Start Date *</Label><Input type="date" value={form.start_date} onChange={e => setForm(f => ({ ...f, start_date: e.target.value }))} /></div>
              <div className="space-y-2"><Label>End Date *</Label><Input type="date" value={form.end_date} onChange={e => setForm(f => ({ ...f, end_date: e.target.value }))} /></div>
            </div>
            <div className="space-y-2"><Label>Capacity</Label><Input type="number" placeholder="30" value={form.max_students} onChange={e => setForm(f => ({ ...f, max_students: e.target.value }))} /></div>
            <div className="space-y-2">
              <Label>Teachers (multi-select)</Label>
              <div className="max-h-40 overflow-y-auto rounded border p-2 space-y-1">
                {teachers.map((t) => (
                  <label key={t.id} className="flex items-center gap-2 rounded px-2 py-1 hover:bg-muted/50">
                    <Checkbox
                      checked={form.teacher_ids.includes(t.id)}
                      onCheckedChange={() =>
                        setForm((prev) => ({
                          ...prev,
                          teacher_ids: prev.teacher_ids.includes(t.id)
                            ? prev.teacher_ids.filter((id) => id !== t.id)
                            : [...prev.teacher_ids, t.id],
                        }))
                      }
                    />
                    <span className="text-sm">{t.name}</span>
                  </label>
                ))}
              </div>
            </div>
          </div>
          <DialogFooter>
            <Button variant="outline" onClick={() => setCreateOpen(false)}>Cancel</Button>
            <Button
              disabled={
                createMutation.isPending ||
                !form.name ||
                !form.course_id ||
                !form.start_date ||
                !form.end_date
              }
              onClick={() =>
                createMutation.mutate({
                  name: form.name,
                  course_id: Number(form.course_id),
                  course_section_id: form.course_section_id ? Number(form.course_section_id) : undefined,
                  term_key: form.term_key.trim() || undefined,
                  classroom_id: form.classroom_id ? Number(form.classroom_id) : undefined,
                  start_date: form.start_date,
                  end_date: form.end_date,
                  max_students: Number(form.max_students) || 30,
                  teacher_ids: form.teacher_ids,
                })
              }
            >
              Create
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
      <Dialog open={editOpen} onOpenChange={setEditOpen}>
        <DialogContent>
          <DialogHeader><DialogTitle>Edit Batch</DialogTitle></DialogHeader>
          <div className="space-y-4">
            <div className="space-y-2"><Label>Batch Name *</Label><Input value={editForm.name} onChange={e => setEditForm(f => ({ ...f, name: e.target.value }))} /></div>
            <div className="space-y-2">
              <Label>Course *</Label>
              <Select
                value={editForm.course_id || "__none__"}
                onValueChange={(v) =>
                  setEditForm((f) => ({
                    ...f,
                    course_id: v === "__none__" ? "" : v,
                    course_section_id: "",
                  }))
                }
              >
                <SelectTrigger><SelectValue placeholder="Select course" /></SelectTrigger>
                <SelectContent>
                  <SelectItem value="__none__">— Select —</SelectItem>
                  {courses.map(c => <SelectItem key={c.id} value={String(c.id)}>{c.title}</SelectItem>)}
                </SelectContent>
              </Select>
            </div>
            <div className="grid grid-cols-2 gap-4">
              <div className="space-y-2">
                <Label>Section (optional)</Label>
                <Select
                  value={editForm.course_section_id || "__none__"}
                  onValueChange={(v) =>
                    setEditForm((f) => ({
                      ...f,
                      course_section_id: v === "__none__" ? "" : v,
                    }))
                  }
                  disabled={!editForm.course_id}
                >
                  <SelectTrigger>
                    <SelectValue placeholder="Whole course" />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="__none__">Whole course (no section)</SelectItem>
                    {editSections.map((s) => (
                      <SelectItem key={s.id} value={String(s.id)}>
                        {s.code ? `${s.code} · ${s.name}` : s.name}
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              </div>
              <div className="space-y-2">
                <Label>Term Key (optional)</Label>
                <Input
                  placeholder="e.g. 2026-T1"
                  value={editForm.term_key}
                  onChange={(e) => setEditForm((f) => ({ ...f, term_key: e.target.value }))}
                />
              </div>
            </div>
            <div className="space-y-2">
              <Label>Classroom (optional)</Label>
              <Select value={editForm.classroom_id || "__none__"} onValueChange={v => setEditForm(f => ({ ...f, classroom_id: v === "__none__" ? "" : v }))}>
                <SelectTrigger><SelectValue placeholder="No classroom" /></SelectTrigger>
                <SelectContent>
                  <SelectItem value="__none__">No classroom</SelectItem>
                  {classrooms.map(c => <SelectItem key={c.id} value={String(c.id)}>{c.name} ({c.student_count} students)</SelectItem>)}
                </SelectContent>
              </Select>
            </div>
            <div className="grid grid-cols-2 gap-4">
              <div className="space-y-2"><Label>Start Date *</Label><Input type="date" value={editForm.start_date} onChange={e => setEditForm(f => ({ ...f, start_date: e.target.value }))} /></div>
              <div className="space-y-2"><Label>End Date *</Label><Input type="date" value={editForm.end_date} onChange={e => setEditForm(f => ({ ...f, end_date: e.target.value }))} /></div>
            </div>
            <div className="space-y-2"><Label>Capacity</Label><Input type="number" value={editForm.max_students} onChange={e => setEditForm(f => ({ ...f, max_students: e.target.value }))} /></div>
            <div className="space-y-2">
              <Label>Teachers (multi-select)</Label>
              <div className="max-h-40 overflow-y-auto rounded border p-2 space-y-1">
                {teachers.map((t) => (
                  <label key={t.id} className="flex items-center gap-2 rounded px-2 py-1 hover:bg-muted/50">
                    <Checkbox
                      checked={editForm.teacher_ids.includes(t.id)}
                      onCheckedChange={() =>
                        setEditForm((prev) => ({
                          ...prev,
                          teacher_ids: prev.teacher_ids.includes(t.id)
                            ? prev.teacher_ids.filter((id) => id !== t.id)
                            : [...prev.teacher_ids, t.id],
                        }))
                      }
                    />
                    <span className="text-sm">{t.name}</span>
                  </label>
                ))}
              </div>
            </div>
          </div>
          <DialogFooter>
            <Button variant="outline" onClick={() => setEditOpen(false)}>Cancel</Button>
            <Button
              disabled={updateMutation.isPending || !editingBatchId || !editForm.name || !editForm.course_id || !editForm.start_date || !editForm.end_date}
              onClick={() => {
                if (!editingBatchId) return;
                updateMutation.mutate({
                  id: editingBatchId,
                  data: {
                    name: editForm.name,
                    course_id: Number(editForm.course_id),
                    course_section_id: editForm.course_section_id
                      ? Number(editForm.course_section_id)
                      : null,
                    term_key: editForm.term_key.trim(),
                    classroom_id: editForm.classroom_id ? Number(editForm.classroom_id) : null,
                    start_date: editForm.start_date,
                    end_date: editForm.end_date,
                    max_students: Number(editForm.max_students) || 30,
                    teacher_ids: editForm.teacher_ids,
                  },
                });
              }}
            >
              Save
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  );
}
