import { useState, useMemo } from "react";
import { Card, CardContent } from "@/components/ui/card";
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 { useLessons, useCreateLesson, useUpdateLesson, useDeleteLesson, useCourses, useBatches, useSubjects } from "@/hooks/queries";
import { Search, Plus, Trash2, Edit } from "lucide-react";
import { useToast } from "@/hooks/use-toast";
import type { Lesson } from "@/types/lesson";

export default function AdminLessons() {
  const [search, setSearch] = useState("");
  const [createOpen, setCreateOpen] = useState(false);
  const [editOpen, setEditOpen] = useState(false);
  const [editing, setEditing] = useState<Lesson | null>(null);
  const [form, setForm] = useState({ lesson_topic: "", course_id: "", batch_id: "", subject_id: "" });
  const { toast } = useToast();
  const { data, isLoading } = useLessons();
  const items = data?.data ?? data?.items ?? [];
  const createMutation = useCreateLesson();
  const updateMutation = useUpdateLesson();
  const deleteMutation = useDeleteLesson();

  const { data: coursesData } = useCourses({ size: 200 });
  const { data: batchesData } = useBatches({ size: 200 });
  const { data: subjectsData } = useSubjects();
  const courses = coursesData?.items ?? [];
  const allBatches = batchesData?.items ?? [];
  const subjects = Array.isArray(subjectsData) ? subjectsData : subjectsData?.data ?? subjectsData?.items ?? [];
  const batchesForCourse = useMemo(
    () => (form.course_id ? allBatches.filter((b) => b.course_id === Number(form.course_id)) : allBatches),
    [allBatches, form.course_id],
  );

  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 q = search.toLowerCase();
  const filtered = items.filter(
    (l) =>
      l.name?.toLowerCase().includes(q) ||
      l.subject_name?.toLowerCase().includes(q) ||
      l.session_name?.toLowerCase().includes(q),
  );

  const openEdit = (l: Lesson) => {
    setEditing(l);
    setForm({
      lesson_topic: l.name,
      course_id: "",
      batch_id: "",
      subject_id: String(l.subject_id ?? ""),
    });
    setEditOpen(true);
  };

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-2xl font-bold">Lessons</h1>
          <p className="text-muted-foreground">Manage lessons, subjects, and sessions.</p>
        </div>
        <Button
          onClick={() => {
            setForm({ lesson_topic: "", course_id: "", batch_id: "", subject_id: "" });
            setCreateOpen(true);
          }}
        >
          <Plus className="mr-2 h-4 w-4" />
          Create lesson
        </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 lessons..."
          value={search}
          onChange={(e) => setSearch(e.target.value)}
          className="pl-9"
        />
      </div>
      <Card>
        <CardContent className="pt-6">
          <Table>
            <TableHeader>
              <TableRow>
                <TableHead>#</TableHead>
                <TableHead>Name</TableHead>
                <TableHead>Subject</TableHead>
                <TableHead>Session</TableHead>
                <TableHead>Actions</TableHead>
              </TableRow>
            </TableHeader>
            <TableBody>
              {filtered.map((l, i) => (
                <TableRow key={l.id}>
                  <TableCell>{i + 1}</TableCell>
                  <TableCell className="font-medium">{l.name}</TableCell>
                  <TableCell>{l.subject_name}</TableCell>
                  <TableCell>{l.session_name}</TableCell>
                  <TableCell>
                    <div className="flex gap-1">
                      <Button size="sm" variant="ghost" onClick={() => openEdit(l)}>
                        <Edit className="h-4 w-4" />
                      </Button>
                      <Button
                        size="sm"
                        variant="ghost"
                        className="text-destructive"
                        onClick={() => {
                          if (!window.confirm("Delete this lesson?")) return;
                          deleteMutation.mutate(l.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={setCreateOpen}>
        <DialogContent>
          <DialogHeader>
            <DialogTitle>Create lesson</DialogTitle>
          </DialogHeader>
          <div className="space-y-4">
            <div className="space-y-2">
              <Label>Lesson Topic *</Label>
              <Input value={form.lesson_topic} onChange={(e) => setForm((f) => ({ ...f, lesson_topic: e.target.value }))} placeholder="e.g. Introduction to Algebra" />
            </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, batch_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="space-y-2">
              <Label>Batch *</Label>
              <Select value={form.batch_id || "__none__"} onValueChange={(v) => setForm((f) => ({ ...f, batch_id: v === "__none__" ? "" : v }))} disabled={!form.course_id}>
                <SelectTrigger><SelectValue placeholder={form.course_id ? "Select batch" : "Pick course first"} /></SelectTrigger>
                <SelectContent>
                  <SelectItem value="__none__">— Select —</SelectItem>
                  {batchesForCourse.map((b) => <SelectItem key={b.id} value={String(b.id)}>{b.name}</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>
                  {subjects.map((s: { id: number; name: string }) => <SelectItem key={s.id} value={String(s.id)}>{s.name}</SelectItem>)}
                </SelectContent>
              </Select>
            </div>
          </div>
          <DialogFooter>
            <Button variant="outline" onClick={() => setCreateOpen(false)}>
              Cancel
            </Button>
            <Button
              disabled={createMutation.isPending || !form.lesson_topic || !form.course_id || !form.batch_id || !form.subject_id}
              onClick={() =>
                createMutation.mutate(
                  {
                    lesson_topic: form.lesson_topic,
                    name: form.lesson_topic,
                    course_id: Number(form.course_id),
                    batch_id: Number(form.batch_id),
                    subject_id: Number(form.subject_id),
                  } as Record<string, unknown>,
                  {
                    onSuccess: () => {
                      setCreateOpen(false);
                      setForm({ lesson_topic: "", course_id: "", batch_id: "", subject_id: "" });
                      toast({ title: "Created successfully" });
                    },
                    onError: (err: Error) =>
                      toast({ title: "Error", description: err.message, variant: "destructive" }),
                  },
                )
              }
            >
              Create
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      <Dialog open={editOpen} onOpenChange={setEditOpen}>
        <DialogContent>
          <DialogHeader>
            <DialogTitle>Edit lesson</DialogTitle>
          </DialogHeader>
          <div className="space-y-4">
            <div className="space-y-2">
              <Label>Lesson Topic</Label>
              <Input value={form.lesson_topic} onChange={(e) => setForm((f) => ({ ...f, lesson_topic: e.target.value }))} />
            </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>
                  {subjects.map((s: { id: number; name: string }) => <SelectItem key={s.id} value={String(s.id)}>{s.name}</SelectItem>)}
                </SelectContent>
              </Select>
            </div>
          </div>
          <DialogFooter>
            <Button variant="outline" onClick={() => setEditOpen(false)}>
              Cancel
            </Button>
            <Button
              disabled={updateMutation.isPending || !editing}
              onClick={() => {
                if (!editing) return;
                updateMutation.mutate(
                  {
                    id: editing.id,
                    data: {
                      lesson_topic: form.lesson_topic,
                      name: form.lesson_topic,
                      subject_id: form.subject_id ? Number(form.subject_id) : undefined,
                    },
                  },
                  {
                    onSuccess: () => {
                      setEditOpen(false);
                      toast({ title: "Updated successfully" });
                    },
                    onError: (err: Error) =>
                      toast({ title: "Error", description: err.message, variant: "destructive" }),
                  },
                );
              }}
            >
              Save
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  );
}
