import { useState } from "react";
import { Card, CardContent } from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter } from "@/components/ui/dialog";
import { Label } from "@/components/ui/label";
import { Search, Plus, Download, MoreHorizontal } from "lucide-react";
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from "@/components/ui/dropdown-menu";
import { useStudents, useTeachers, useCreateStudent, useCreateTeacher } from "@/hooks/queries";
import { lmsService } from "@/services/lms.service";
import { useMutation, useQueryClient } from "@tanstack/react-query";
import { useToast } from "@/hooks/use-toast";
import { ApiError } from "@/lib/api-client";

function messageFromCreateError(err: unknown): string {
  if (err instanceof ApiError && err.data && typeof err.data === "object" && err.data !== null && "error" in err.data) {
    const e = (err.data as { error: unknown }).error;
    if (e != null && String(e).trim()) return String(e);
  }
  if (err instanceof Error) return err.message;
  return "Something went wrong.";
}

function toastForCreateUserError(err: unknown): { title: string; description: string; variant?: "default" | "destructive" } {
  const msg = messageFromCreateError(err).toLowerCase();
  const isDuplicate =
    msg.includes("already exists") ||
    msg.includes("duplicate") ||
    msg.includes("unique") ||
    msg.includes("already registered");
  if (isDuplicate) {
    return {
      title: "Email already in use",
      description:
        messageFromCreateError(err) +
        " Try another address, or find the existing user in the Students or Teachers tab.",
      variant: "destructive",
    };
  }
  return { title: "Could not create user", description: messageFromCreateError(err), variant: "destructive" };
}

export default function UsersPage() {
  const [search, setSearch] = useState("");
  const [createOpen, setCreateOpen] = useState(false);
  const [form, setForm] = useState({ first_name: "", last_name: "", email: "", role: "student", phone: "", gender: "" });
  const { toast } = useToast();
  const qc = useQueryClient();

  const studentsQ = useStudents({ search: search || undefined, size: 200 });
  const teachersQ = useTeachers({ search: search || undefined, size: 200 });
  const createStudentMut = useCreateStudent();
  const createTeacherMut = useCreateTeacher();

  const students = studentsQ.data?.items ?? [];
  const teachers = teachersQ.data?.items ?? [];

  const deleteMut = useMutation({
    mutationFn: async ({ type, id }: { type: "student" | "teacher"; id: number }) => {
      if (type === "student") return lmsService.deleteStudent?.(id) ?? lmsService.updateStudent(id, { status: "inactive" });
      return lmsService.updateTeacher?.(id, {}) ?? Promise.resolve();
    },
    onSuccess: () => {
      qc.invalidateQueries({ queryKey: ["lms"] });
      toast({ title: "Done" });
    },
    onError: (err: Error) => toast({ title: "Error", description: err.message, variant: "destructive" }),
  });

  function handleCreate() {
    const email = form.email.trim();
    const first_name = form.first_name.trim();
    const last_name = form.last_name.trim();
    const emailKey = email.toLowerCase();
    const dupStudent = students.some((s) => (s.email || "").trim().toLowerCase() === emailKey);
    const dupTeacher = teachers.some((t) => (t.email || "").trim().toLowerCase() === emailKey);
    if (dupStudent || dupTeacher) {
      toast({
        title: "Email already in use",
        description:
          "That address matches someone already listed on this page (search may hide them). Use another email or clear search to find the user.",
        variant: "destructive",
      });
      return;
    }
    const cb = {
      onSuccess: () => {
        setCreateOpen(false);
        resetForm();
        toast({ title: "User created successfully" });
      },
      onError: (err: unknown) => toast(toastForCreateUserError(err)),
    };
    if (form.role === "teacher") {
      createTeacherMut.mutate(
        {
          first_name,
          last_name,
          email,
          phone: form.phone?.trim() || undefined,
          gender: (form.gender as "male" | "female") || undefined,
        },
        cb,
      );
    } else {
      createStudentMut.mutate(
        {
          first_name,
          last_name,
          email,
          phone: form.phone?.trim() || undefined,
          gender: form.gender || undefined,
          create_portal_user: true,
        },
        cb,
      );
    }
  }

  function resetForm() {
    setForm({ first_name: "", last_name: "", email: "", role: "student", phone: "", gender: "" });
  }

  function exportCsv() {
    const rows = [["Name", "Email", "Role", "Status"]];
    students.forEach(s => rows.push([s.name, s.email, "Student", s.status || "active"]));
    teachers.forEach(t => rows.push([t.name, t.email, "Teacher", "active"]));
    const csv = rows.map(r => r.join(",")).join("\n");
    const blob = new Blob([csv], { type: "text/csv" });
    const url = URL.createObjectURL(blob);
    const a = document.createElement("a");
    a.href = url;
    a.download = "users_export.csv";
    a.click();
    URL.revokeObjectURL(url);
  }

  const isPending = createStudentMut.isPending || createTeacherMut.isPending;
  const loading = studentsQ.isLoading || teachersQ.isLoading;

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-2xl font-bold tracking-tight">Users</h1>
          <p className="text-muted-foreground">Manage platform users across all roles.</p>
        </div>
        <div className="flex gap-2">
          <Button variant="outline" size="sm" onClick={exportCsv}>
            <Download className="h-4 w-4 mr-1" /> Export
          </Button>
          <Button size="sm" onClick={() => setCreateOpen(true)}>
            <Plus className="h-4 w-4 mr-1" /> Create User
          </Button>
        </div>
      </div>

      <div className="flex gap-3 items-center">
        <div className="relative flex-1 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 users..." className="pl-9" value={search} onChange={(e) => setSearch(e.target.value)} />
        </div>
      </div>

      {loading ? (
        <div className="flex items-center justify-center min-h-[300px]">
          <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-primary" />
        </div>
      ) : (
        <Tabs defaultValue="students">
          <TabsList>
            <TabsTrigger value="students">Students ({students.length})</TabsTrigger>
            <TabsTrigger value="teachers">Teachers ({teachers.length})</TabsTrigger>
          </TabsList>
          <TabsContent value="students" className="mt-4">
            <Card className="border-0 shadow-sm">
              <CardContent className="p-0">
                <Table>
                  <TableHeader>
                    <TableRow>
                      <TableHead>Name</TableHead>
                      <TableHead>Email</TableHead>
                      <TableHead>Phone</TableHead>
                      <TableHead>Batch</TableHead>
                      <TableHead>Status</TableHead>
                      <TableHead>Enrollment</TableHead>
                      <TableHead className="w-10" />
                    </TableRow>
                  </TableHeader>
                  <TableBody>
                    {students.length === 0 && (
                      <TableRow><TableCell colSpan={7} className="text-center text-muted-foreground py-8">No students found.</TableCell></TableRow>
                    )}
                    {students.map((s) => (
                      <TableRow key={s.id}>
                        <TableCell className="font-medium">{s.name}</TableCell>
                        <TableCell>{s.email}</TableCell>
                        <TableCell>{s.phone || "—"}</TableCell>
                        <TableCell>{s.batch_name || "—"}</TableCell>
                        <TableCell>
                          <Badge variant={s.status === "active" ? "default" : "secondary"} className="capitalize">{s.status || "active"}</Badge>
                        </TableCell>
                        <TableCell>{s.enrollment_date || "—"}</TableCell>
                        <TableCell>
                          <DropdownMenu>
                            <DropdownMenuTrigger asChild>
                              <Button variant="ghost" size="icon" className="h-8 w-8"><MoreHorizontal className="h-4 w-4" /></Button>
                            </DropdownMenuTrigger>
                            <DropdownMenuContent align="end">
                              <DropdownMenuItem className="text-destructive" onClick={() => { if (window.confirm(`Deactivate student "${s.name}"?`)) deleteMut.mutate({ type: "student", id: s.id }); }}>
                                Deactivate
                              </DropdownMenuItem>
                            </DropdownMenuContent>
                          </DropdownMenu>
                        </TableCell>
                      </TableRow>
                    ))}
                  </TableBody>
                </Table>
              </CardContent>
            </Card>
          </TabsContent>
          <TabsContent value="teachers" className="mt-4">
            <Card className="border-0 shadow-sm">
              <CardContent className="p-0">
                <Table>
                  <TableHeader>
                    <TableRow>
                      <TableHead>Name</TableHead>
                      <TableHead>Email</TableHead>
                      <TableHead>Phone</TableHead>
                      <TableHead>Department</TableHead>
                      <TableHead>Specialization</TableHead>
                      <TableHead className="w-10" />
                    </TableRow>
                  </TableHeader>
                  <TableBody>
                    {teachers.length === 0 && (
                      <TableRow><TableCell colSpan={6} className="text-center text-muted-foreground py-8">No teachers found.</TableCell></TableRow>
                    )}
                    {teachers.map((t) => (
                      <TableRow key={t.id}>
                        <TableCell className="font-medium">{t.name}</TableCell>
                        <TableCell>{t.email}</TableCell>
                        <TableCell>{t.phone || "—"}</TableCell>
                        <TableCell>{t.department_name || "—"}</TableCell>
                        <TableCell>{t.specialization || "—"}</TableCell>
                        <TableCell>
                          <DropdownMenu>
                            <DropdownMenuTrigger asChild>
                              <Button variant="ghost" size="icon" className="h-8 w-8"><MoreHorizontal className="h-4 w-4" /></Button>
                            </DropdownMenuTrigger>
                            <DropdownMenuContent align="end">
                              <DropdownMenuItem className="text-destructive" onClick={() => { if (window.confirm(`Remove teacher "${t.name}"?`)) deleteMut.mutate({ type: "teacher", id: t.id }); }}>
                                Remove
                              </DropdownMenuItem>
                            </DropdownMenuContent>
                          </DropdownMenu>
                        </TableCell>
                      </TableRow>
                    ))}
                  </TableBody>
                </Table>
              </CardContent>
            </Card>
          </TabsContent>
        </Tabs>
      )}

      <Dialog open={createOpen} onOpenChange={(v) => { setCreateOpen(v); if (!v) resetForm(); }}>
        <DialogContent>
          <DialogHeader><DialogTitle>Create New User</DialogTitle></DialogHeader>
          <div className="space-y-4">
            <div className="grid grid-cols-2 gap-3">
              <div className="space-y-2">
                <Label>First Name</Label>
                <Input value={form.first_name} onChange={(e) => setForm(f => ({ ...f, first_name: e.target.value }))} placeholder="John" />
              </div>
              <div className="space-y-2">
                <Label>Last Name</Label>
                <Input value={form.last_name} onChange={(e) => setForm(f => ({ ...f, last_name: e.target.value }))} placeholder="Doe" />
              </div>
            </div>
            <div className="space-y-2">
              <Label>Email</Label>
              <Input type="email" value={form.email} onChange={(e) => setForm(f => ({ ...f, email: e.target.value }))} placeholder="john@email.com" />
              <p className="text-xs text-muted-foreground">
                Must be unique in Odoo for students and teachers. If create fails, the address may already exist outside the current list.
              </p>
            </div>
            <div className="space-y-2">
              <Label>Phone</Label>
              <Input value={form.phone} onChange={(e) => setForm(f => ({ ...f, phone: e.target.value }))} placeholder="+1234567890" />
            </div>
            <div className="grid grid-cols-2 gap-3">
              <div className="space-y-2">
                <Label>Role</Label>
                <Select value={form.role} onValueChange={(v) => setForm(f => ({ ...f, role: v }))}>
                  <SelectTrigger><SelectValue /></SelectTrigger>
                  <SelectContent>
                    <SelectItem value="student">Student</SelectItem>
                    <SelectItem value="teacher">Teacher</SelectItem>
                  </SelectContent>
                </Select>
              </div>
              <div className="space-y-2">
                <Label>Gender</Label>
                <Select value={form.gender} onValueChange={(v) => setForm(f => ({ ...f, gender: v }))}>
                  <SelectTrigger><SelectValue placeholder="Select" /></SelectTrigger>
                  <SelectContent>
                    <SelectItem value="male">Male</SelectItem>
                    <SelectItem value="female">Female</SelectItem>
                  </SelectContent>
                </Select>
              </div>
            </div>
          </div>
          <DialogFooter>
            <Button variant="outline" onClick={() => { setCreateOpen(false); resetForm(); }}>Cancel</Button>
            <Button
              disabled={isPending || !form.first_name.trim() || !form.last_name.trim() || !form.email.trim()}
              onClick={handleCreate}
            >
              {isPending ? "Creating..." : "Create"}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  );
}
