import { useState } from "react";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Badge } from "@/components/ui/badge";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle, DialogTrigger } from "@/components/ui/dialog";
import { Collapsible, CollapsibleContent, CollapsibleTrigger } from "@/components/ui/collapsible";
import { Label } from "@/components/ui/label";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Plus, Trash2, ChevronRight, RefreshCw, Loader2 } from "lucide-react";
import {
  useAcademicYears,
  useCreateAcademicYear,
  useDeleteAcademicYear,
  useGenerateTerms,
  useAcademicTerms,
} from "@/hooks/queries/useAcademic";
import { useToast } from "@/hooks/use-toast";
import type { AcademicYear, AcademicYearCreateRequest } from "@/types/academic";

const TERM_STRUCTURES: { value: AcademicYear["term_structure"]; label: string }[] = [
  { value: "two_sem", label: "Two Semesters" },
  { value: "two_sem_qua", label: "Two Semesters + Quarter" },
  { value: "three_sem", label: "Three Semesters" },
  { value: "four_Quarter", label: "Four Quarters" },
  { value: "final_year", label: "Final Year" },
  { value: "others", label: "Others" },
];

export default function AcademicYearManager() {
  const { toast } = useToast();
  const { data: yearsData, isLoading } = useAcademicYears();
  const years = yearsData?.items ?? [];
  const createYear = useCreateAcademicYear();
  const deleteYear = useDeleteAcademicYear();
  const generateTerms = useGenerateTerms();
  const [showCreate, setShowCreate] = useState(false);
  const [expandedId, setExpandedId] = useState<number | null>(null);
  const [form, setForm] = useState<AcademicYearCreateRequest>({
    name: "",
    start_date: "",
    end_date: "",
    term_structure: "two_sem",
  });

  const { data: termsData } = useAcademicTerms(expandedId ?? undefined);
  const terms = termsData?.items ?? [];

  const handleCreate = () => {
    createYear.mutate(form, {
      onSuccess: () => {
        toast({ title: "Academic year created" });
        setShowCreate(false);
        setForm({ name: "", start_date: "", end_date: "", term_structure: "two_sem" });
      },
      onError: () => toast({ title: "Error", description: "Failed to create academic year", variant: "destructive" }),
    });
  };

  const handleDelete = (id: number) => {
    if (!window.confirm("Delete this academic year?")) return;
    deleteYear.mutate(id, {
      onSuccess: () => toast({ title: "Academic year deleted" }),
      onError: () => toast({ title: "Error", description: "Failed to delete", variant: "destructive" }),
    });
  };

  const handleGenerateTerms = (yearId: number) => {
    generateTerms.mutate(yearId, {
      onSuccess: () => toast({ title: "Terms generated" }),
      onError: () => toast({ title: "Error", description: "Failed to generate terms", variant: "destructive" }),
    });
  };

  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>;

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-2xl font-bold">Academic Years</h1>
          <p className="text-muted-foreground">Manage academic years and their terms.</p>
        </div>
        <Dialog open={showCreate} onOpenChange={setShowCreate}>
          <DialogTrigger asChild>
            <Button><Plus className="mr-2 h-4 w-4" /> Create Academic Year</Button>
          </DialogTrigger>
          <DialogContent>
            <DialogHeader>
              <DialogTitle>Create Academic Year</DialogTitle>
              <DialogDescription>Define the academic year range and term structure.</DialogDescription>
            </DialogHeader>
            <div className="space-y-4 pt-4">
              <div className="space-y-2">
                <Label>Name</Label>
                <Input placeholder="e.g. 2025-2026" value={form.name} onChange={e => setForm({ ...form, name: e.target.value })} />
              </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({ ...form, 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({ ...form, end_date: e.target.value })} />
                </div>
              </div>
              <div className="space-y-2">
                <Label>Term Structure</Label>
                <Select value={form.term_structure} onValueChange={v => setForm({ ...form, term_structure: v as AcademicYear["term_structure"] })}>
                  <SelectTrigger><SelectValue /></SelectTrigger>
                  <SelectContent>
                    {TERM_STRUCTURES.map(ts => (
                      <SelectItem key={ts.value} value={ts.value}>{ts.label}</SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              </div>
              <Button className="w-full" onClick={handleCreate} disabled={createYear.isPending || !form.name || !form.start_date || !form.end_date}>
                {createYear.isPending && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
                Create
              </Button>
            </div>
          </DialogContent>
        </Dialog>
      </div>

      <Card>
        <CardContent className="pt-6">
          <Table>
            <TableHeader>
              <TableRow>
                <TableHead />
                <TableHead>Name</TableHead>
                <TableHead>Start Date</TableHead>
                <TableHead>End Date</TableHead>
                <TableHead>Term Structure</TableHead>
                <TableHead>Terms</TableHead>
                <TableHead className="text-right">Actions</TableHead>
              </TableRow>
            </TableHeader>
            <TableBody>
              {years.map((year: AcademicYear) => (
                <Collapsible key={year.id} asChild open={expandedId === year.id} onOpenChange={open => setExpandedId(open ? year.id : null)}>
                  <>
                    <TableRow>
                      <TableCell>
                        <CollapsibleTrigger asChild>
                          <Button variant="ghost" size="icon" className="h-6 w-6">
                            <ChevronRight className={`h-4 w-4 transition-transform ${expandedId === year.id ? "rotate-90" : ""}`} />
                          </Button>
                        </CollapsibleTrigger>
                      </TableCell>
                      <TableCell className="font-medium">{year.name}</TableCell>
                      <TableCell>{year.start_date}</TableCell>
                      <TableCell>{year.end_date}</TableCell>
                      <TableCell>
                        <Badge variant="outline">{TERM_STRUCTURES.find(t => t.value === year.term_structure)?.label ?? year.term_structure}</Badge>
                      </TableCell>
                      <TableCell>
                        <Badge variant="secondary">{year.terms?.length ?? 0}</Badge>
                      </TableCell>
                      <TableCell className="text-right">
                        <div className="flex items-center justify-end gap-1">
                          <Button variant="ghost" size="sm" onClick={() => handleGenerateTerms(year.id)} disabled={generateTerms.isPending}>
                            <RefreshCw className="mr-1 h-3 w-3" /> Generate Terms
                          </Button>
                          <Button variant="ghost" size="icon" onClick={() => handleDelete(year.id)} disabled={deleteYear.isPending}>
                            <Trash2 className="h-4 w-4 text-destructive" />
                          </Button>
                        </div>
                      </TableCell>
                    </TableRow>
                    <CollapsibleContent asChild>
                      <TableRow>
                        <TableCell colSpan={7} className="bg-muted/50 p-4">
                          {expandedId === year.id && (
                            <div className="space-y-2">
                              <h4 className="text-sm font-medium">Terms</h4>
                              {terms.length > 0 ? (
                                <div className="grid gap-2">
                                  {terms.map(term => (
                                    <div key={term.id} className="flex items-center justify-between rounded border p-3 bg-background">
                                      <span className="text-sm font-medium">{term.name}</span>
                                      <span className="text-sm text-muted-foreground">{term.term_start_date} — {term.term_end_date}</span>
                                    </div>
                                  ))}
                                </div>
                              ) : (
                                <p className="text-sm text-muted-foreground">No terms yet. Click "Generate Terms" to auto-create.</p>
                              )}
                            </div>
                          )}
                        </TableCell>
                      </TableRow>
                    </CollapsibleContent>
                  </>
                </Collapsible>
              ))}
              {years.length === 0 && (
                <TableRow>
                  <TableCell colSpan={7} className="text-center py-8 text-muted-foreground">No academic years found.</TableCell>
                </TableRow>
              )}
            </TableBody>
          </Table>
        </CardContent>
      </Card>
    </div>
  );
}
