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 { 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 { useGradebooks, useGradingAssignments, useCreateGradingAssignment, useUpdateGradingAssignment, useDeleteGradingAssignment, useCourses, useSubjects } from "@/hooks/queries";
import { Search, Plus, BookOpen, Pencil, Trash2 } from "lucide-react";
import { useToast } from "@/hooks/use-toast";

export default function AdminGradebook() {
  const [search, setSearch] = useState("");
  const [section, setSection] = useState<"books" | "assignments">("books");
  const [createOpen, setCreateOpen] = useState(false);
  const [editId, setEditId] = useState<number | null>(null);
  const [form, setForm] = useState({ name: "", course_id: "", subject_id: "", issued_date: "" });
  const { toast } = useToast();
  const booksQ = useGradebooks();
  const assignQ = useGradingAssignments();
  const { data: coursesData } = useCourses({ size: 200 });
  const { data: subjectsData } = useSubjects();
  const coursesList = coursesData?.items ?? [];
  const subjectsList = Array.isArray(subjectsData) ? subjectsData : subjectsData?.data ?? subjectsData?.items ?? [];
  const createMutation = useCreateGradingAssignment();
  const updateMutation = useUpdateGradingAssignment();
  const deleteMutation = useDeleteGradingAssignment();
  const loading = section === "books" ? booksQ.isLoading : assignQ.isLoading;
  const books = booksQ.data?.data ?? booksQ.data?.items ?? [];
  const assignments = assignQ.data?.data ?? assignQ.data?.items ?? [];

  if (loading) {
    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 q = search.toLowerCase();
  const filteredBooks = books.filter(
    (b) =>
      b.student_name?.toLowerCase().includes(q) || b.course_name?.toLowerCase().includes(q),
  );
  const filteredAssign = assignments.filter(
    (a) =>
      a.name?.toLowerCase().includes(q) ||
      a.course_name?.toLowerCase().includes(q) ||
      a.subject_name?.toLowerCase().includes(q),
  );

  return (
    <div className="space-y-6">
      <div className="flex flex-wrap items-center justify-between gap-4">
        <div>
          <h1 className="text-2xl font-bold">Gradebook</h1>
          <p className="text-muted-foreground">Gradebooks and grading assignments.</p>
        </div>
        {section === "assignments" && (
          <Button onClick={() => setCreateOpen(true)}>
            <Plus className="mr-2 h-4 w-4" />
            New assignment
          </Button>
        )}
      </div>
      <div className="flex flex-wrap gap-2">
        <Button variant={section === "books" ? "default" : "outline"} onClick={() => setSection("books")}>
          <BookOpen className="mr-2 h-4 w-4" />
          Gradebooks
        </Button>
        <Button
          variant={section === "assignments" ? "default" : "outline"}
          onClick={() => setSection("assignments")}
        >
          Grading assignments
        </Button>
      </div>
      <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..."
          value={search}
          onChange={(e) => setSearch(e.target.value)}
          className="pl-9"
        />
      </div>
      {section === "books" ? (
        <Card>
          <CardContent className="pt-6">
            <Table>
              <TableHeader>
                <TableRow>
                  <TableHead>#</TableHead>
                  <TableHead>Student</TableHead>
                  <TableHead>Course</TableHead>
                  <TableHead>Academic Year</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {filteredBooks.map((b, i) => (
                  <TableRow key={b.id}>
                    <TableCell>{i + 1}</TableCell>
                    <TableCell className="font-medium">{b.student_name}</TableCell>
                    <TableCell>{b.course_name}</TableCell>
                    <TableCell>{b.academic_year_name}</TableCell>
                  </TableRow>
                ))}
              </TableBody>
            </Table>
          </CardContent>
        </Card>
      ) : (
        <Card>
          <CardContent className="pt-6">
            <Table>
              <TableHeader>
                <TableRow>
                  <TableHead>#</TableHead>
                  <TableHead>Name</TableHead>
                  <TableHead>Course</TableHead>
                  <TableHead>Subject</TableHead>
                  <TableHead>State</TableHead>
                  <TableHead>Issued Date</TableHead>
                  <TableHead>Actions</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {filteredAssign.map((a, i) => (
                  <TableRow key={a.id}>
                    <TableCell>{i + 1}</TableCell>
                    <TableCell className="font-medium">{a.name}</TableCell>
                    <TableCell>{a.course_name}</TableCell>
                    <TableCell>{a.subject_name}</TableCell>
                    <TableCell>
                      <Badge variant="outline" className="capitalize">
                        {a.state}
                      </Badge>
                    </TableCell>
                    <TableCell>{a.issued_date}</TableCell>
                    <TableCell>
                      <div className="flex gap-1">
                        <Button size="sm" variant="ghost" onClick={() => { setEditId(a.id); setForm({ name: a.name || "", course_id: String(a.course_id || ""), subject_id: String(a.subject_id || ""), issued_date: a.issued_date || "" }); setCreateOpen(true); }}>
                          <Pencil className="h-4 w-4" />
                        </Button>
                        <Button size="sm" variant="ghost" className="text-destructive" onClick={() => { if (!window.confirm("Delete this assignment?")) return; deleteMutation.mutate(a.id, { onSuccess: () => toast({ title: "Deleted" }), onError: (err: Error) => toast({ title: "Error", description: err.message, variant: "destructive" }) }); }}>
                          <Trash2 className="h-4 w-4" />
                        </Button>
                      </div>
                    </TableCell>
                  </TableRow>
                ))}
              </TableBody>
            </Table>
          </CardContent>
        </Card>
      )}

      <Dialog open={createOpen} onOpenChange={(v) => { setCreateOpen(v); if (!v) setEditId(null); }}>
        <DialogContent>
          <DialogHeader>
            <DialogTitle>{editId ? "Edit grading assignment" : "Create grading assignment"}</DialogTitle>
          </DialogHeader>
          <div className="space-y-4">
            <div className="space-y-2">
              <Label>Name</Label>
              <Input 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 }))}>
                <SelectTrigger><SelectValue placeholder="Select course" /></SelectTrigger>
                <SelectContent>
                  <SelectItem value="__none__">— Select —</SelectItem>
                  {coursesList.map((c) => <SelectItem key={c.id} value={String(c.id)}>{c.title}</SelectItem>)}
                </SelectContent>
              </Select>
            </div>
            <div className="space-y-2">
              <Label>Subject</Label>
              <Select value={form.subject_id || "__none__"} onValueChange={(v) => setForm((f) => ({ ...f, subject_id: v === "__none__" ? "" : v }))}>
                <SelectTrigger><SelectValue placeholder="Select subject" /></SelectTrigger>
                <SelectContent>
                  <SelectItem value="__none__">— Select —</SelectItem>
                  {subjectsList.map((s: { id: number; name: string }) => <SelectItem key={s.id} value={String(s.id)}>{s.name}</SelectItem>)}
                </SelectContent>
              </Select>
            </div>
            <div className="space-y-2">
              <Label>Issued date</Label>
              <Input
                type="date"
                value={form.issued_date}
                onChange={(e) => setForm((f) => ({ ...f, issued_date: e.target.value }))}
              />
            </div>
          </div>
          <DialogFooter>
            <Button variant="outline" onClick={() => { setCreateOpen(false); setEditId(null); }}>
              Cancel
            </Button>
            <Button
              disabled={createMutation.isPending || updateMutation.isPending || !form.name || !form.course_id}
              onClick={() => {
                const payload = { name: form.name, course_id: Number(form.course_id), subject_id: form.subject_id ? Number(form.subject_id) : undefined, issued_date: form.issued_date };
                const cb = { onSuccess: () => { setCreateOpen(false); setEditId(null); toast({ title: editId ? "Updated" : "Created" }); }, onError: (err: Error) => toast({ title: "Error", description: err.message, variant: "destructive" }) };
                if (editId) { updateMutation.mutate({ id: editId, data: payload }, cb); }
                else { createMutation.mutate(payload, cb); }
              }}
            >
              {editId ? "Save" : "Create"}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  );
}
