import { useState, useMemo } 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 { Checkbox } from "@/components/ui/checkbox";
import { useStudents, useCreateStudent, useCourses, useBatches } from "@/hooks/queries";
import { lmsStudentToUser } from "@/services/lms.service";
import { api } from "@/lib/api-client";
import { useQueryClient } from "@tanstack/react-query";
import { Search, Plus, Trash2 } from "lucide-react";
import { useToast } from "@/hooks/use-toast";
import AiRiskBadge from "@/components/ai/AiRiskBadge";
import AiCreationAssistant from "@/components/ai/AiCreationAssistant";
import AiTipBanner from "@/components/ai/AiTipBanner";

export default function AdminStudents() {
  const [search, setSearch] = useState("");
  const [addOpen, setAddOpen] = useState(false);
  const [firstName, setFirstName] = useState("");
  const [lastName, setLastName] = useState("");
  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");
  const [gender, setGender] = useState<string>("m");
  const [courseIdStr, setCourseIdStr] = useState<string>("");
  const [batchIdStr, setBatchIdStr] = useState<string>("");
  const [createPortal, setCreatePortal] = useState(true);
  const { toast } = useToast();

  const { data: studentsData, isLoading } = useStudents({ size: 500 });
  const { data: coursesData } = useCourses({ size: 200 });
  const { data: batchesData } = useBatches({ size: 200 });
  const createStudent = useCreateStudent();
  const qc = useQueryClient();

  const courses = coursesData?.items ?? [];
  const batches = batchesData?.items ?? [];
  const courseId = courseIdStr ? Number(courseIdStr) : undefined;
  const batchesForCourse = useMemo(
    () => (courseId ? batches.filter((b) => b.course_id === courseId) : batches),
    [batches, courseId],
  );

  const rows = studentsData?.items ?? [];
  const displayRows = search.trim()
    ? rows.filter(
        (s) =>
          s.name.toLowerCase().includes(search.toLowerCase()) ||
          (s.email || "").toLowerCase().includes(search.toLowerCase()),
      )
    : rows;

  const resetForm = () => {
    setFirstName("");
    setLastName("");
    setEmail("");
    setPassword("");
    setGender("m");
    setCourseIdStr("");
    setBatchIdStr("");
    setCreatePortal(true);
  };

  const handleAdd = () => {
    if (!email.trim()) {
      toast({ title: "Email required", variant: "destructive" });
      return;
    }
    if (!firstName.trim() && !lastName.trim()) {
      toast({ title: "Name required", description: "Enter first or last name.", variant: "destructive" });
      return;
    }
    const course_id = courseIdStr ? Number(courseIdStr) : undefined;
    const batch_id = batchIdStr ? Number(batchIdStr) : undefined;
    if ((course_id && !batch_id) || (!course_id && batch_id)) {
      toast({
        title: "Course and batch",
        description: "Select both course and batch to enroll, or leave both empty.",
        variant: "destructive",
      });
      return;
    }

    createStudent.mutate(
      {
        first_name: firstName.trim(),
        last_name: lastName.trim() || "-",
        email: email.trim().toLowerCase(),
        gender,
        ...(password.trim() ? { password: password.trim() } : {}),
        create_portal_user: createPortal,
        ...(course_id && batch_id ? { course_id, batch_id } : {}),
      },
      {
        onSuccess: () => {
          setAddOpen(false);
          resetForm();
          toast({
            title: "Student created",
            description: createPortal
              ? "Saved in OpenEduCat. Portal user created — student can log in with this email and password."
              : "Saved in OpenEduCat (op.student) only.",
          });
        },
        onError: (e: Error) => {
          toast({ title: "Could not create student", description: e.message, variant: "destructive" });
        },
      },
    );
  };

  async function handleDeleteStudent(id: number, name: string) {
    if (!window.confirm(`Delete student "${name}"?`)) return;
    try {
      await api.delete(`/students/${id}`);
      qc.invalidateQueries({ queryKey: ["lms", "students"] });
      toast({ title: "Student deleted" });
    } catch (e: unknown) {
      const msg = e instanceof Error ? e.message : String(e);
      toast({ title: "Delete failed", description: msg, 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">Students</h1>
          <p className="text-muted-foreground">OpenEduCat students — same records as in Odoo LMS.</p>
        </div>
        <div className="flex gap-2">
          <AiCreationAssistant type="student" />
          <Button onClick={() => setAddOpen(true)}>
            <Plus className="mr-2 h-4 w-4" />
            Add Student
          </Button>
        </div>
      </div>
      <AiTipBanner context="admin-students" variant="insight" />
      <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 students..."
          value={search}
          onChange={(e) => setSearch(e.target.value)}
          className="pl-9"
        />
      </div>
      <Card>
        <CardContent className="pt-6">
          <Table>
            <TableHeader>
              <TableRow>
                <TableHead>Student</TableHead>
                <TableHead>Batch</TableHead>
                <TableHead>Attendance</TableHead>
                <TableHead>Avg Grade</TableHead>
                <TableHead>AI Risk</TableHead>
                <TableHead>Status</TableHead>
                <TableHead className="w-[60px]" />
              </TableRow>
            </TableHeader>
            <TableBody>
              {displayRows.map((s) => {
                const u = lmsStudentToUser(s);
                const initials =
                  u.name
                    ?.split(" ")
                    .map((w) => w[0])
                    .join("")
                    .slice(0, 2)
                    .toUpperCase() ?? "??";
                return (
                  <TableRow key={s.id}>
                    <TableCell>
                      <div className="flex items-center gap-2">
                        <div className="h-7 w-7 rounded-full bg-primary/10 flex items-center justify-center text-xs font-medium text-primary">
                          {initials}
                        </div>
                        <div>
                          <p className="text-sm font-medium">{s.name}</p>
                          <p className="text-xs text-muted-foreground">{s.email || "—"}</p>
                        </div>
                      </div>
                    </TableCell>
                    <TableCell>{s.batch_name || "—"}</TableCell>
                    <TableCell>—</TableCell>
                    <TableCell>—</TableCell>
                    <TableCell>
                      <AiRiskBadge />
                    </TableCell>
                    <TableCell>
                      <Badge variant="outline" className="capitalize">
                        {s.status || "active"}
                      </Badge>
                    </TableCell>
                    <TableCell>
                      <Button variant="ghost" size="icon" onClick={() => handleDeleteStudent(s.id, s.name)}><Trash2 className="h-4 w-4 text-destructive" /></Button>
                    </TableCell>
                  </TableRow>
                );
              })}
            </TableBody>
          </Table>
        </CardContent>
      </Card>
      <Dialog
        open={addOpen}
        onOpenChange={(o) => {
          setAddOpen(o);
          if (!o) resetForm();
        }}
      >
        <DialogContent className="max-h-[90vh] overflow-y-auto">
          <DialogHeader>
            <DialogTitle>Add Student</DialogTitle>
          </DialogHeader>
          <div className="space-y-4">
            <div className="grid grid-cols-2 gap-4">
              <div className="space-y-2">
                <Label htmlFor="fn">First Name</Label>
                <Input id="fn" value={firstName} onChange={(e) => setFirstName(e.target.value)} />
              </div>
              <div className="space-y-2">
                <Label htmlFor="ln">Last Name</Label>
                <Input id="ln" value={lastName} onChange={(e) => setLastName(e.target.value)} />
              </div>
            </div>
            <div className="space-y-2">
              <Label>Gender</Label>
              <Select value={gender} onValueChange={setGender}>
                <SelectTrigger><SelectValue /></SelectTrigger>
                <SelectContent>
                  <SelectItem value="m">Male</SelectItem>
                  <SelectItem value="f">Female</SelectItem>
                </SelectContent>
              </Select>
            </div>
            <div className="space-y-2">
              <Label htmlFor="em">Email (login)</Label>
              <Input id="em" type="email" value={email} onChange={(e) => setEmail(e.target.value)} />
            </div>
            <div className="space-y-2">
              <Label htmlFor="pw">Password</Label>
              <Input
                id="pw"
                type="password"
                autoComplete="new-password"
                placeholder="Empty = Student123!"
                value={password}
                onChange={(e) => setPassword(e.target.value)}
              />
            </div>
            <div className="flex items-center gap-2">
              <Checkbox id="portal" checked={createPortal} onCheckedChange={(v) => setCreatePortal(v === true)} />
              <Label htmlFor="portal" className="text-sm font-normal cursor-pointer">
                Create portal login (res.users) for the SPA
              </Label>
            </div>
            <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
              <div className="space-y-2">
                <Label>Course (optional)</Label>
                <Select
                  value={courseIdStr || "__none__"}
                  onValueChange={(v) => {
                    setCourseIdStr(v === "__none__" ? "" : v);
                    setBatchIdStr("");
                  }}
                >
                  <SelectTrigger>
                    <SelectValue placeholder="Select course" />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="__none__">— None —</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 (optional)</Label>
                <Select
                  value={batchIdStr || "__none__"}
                  onValueChange={(v) => setBatchIdStr(v === "__none__" ? "" : v)}
                  disabled={!courseIdStr}
                >
                  <SelectTrigger>
                    <SelectValue placeholder={courseIdStr ? "Select batch" : "Pick a course first"} />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="__none__">— None —</SelectItem>
                    {batchesForCourse.map((b) => (
                      <SelectItem key={b.id} value={String(b.id)}>
                        {b.name}
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              </div>
            </div>
            <p className="text-xs text-muted-foreground">
              Creates <code className="text-xs">op.student</code> in Odoo. With portal enabled, also{" "}
              <code className="text-xs">res.users</code> (<code className="text-xs">base.group_portal</code>) linked via{" "}
              <code className="text-xs">op_student_id</code>.
            </p>
          </div>
          <DialogFooter>
            <Button variant="outline" onClick={() => setAddOpen(false)}>
              Cancel
            </Button>
            <Button onClick={handleAdd} disabled={createStudent.isPending}>
              {createStudent.isPending ? "Saving…" : "Add"}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  );
}
