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 {
  useStudentLeaves,
  useStudentLeaveTypes,
  useCreateStudentLeave,
  useApproveStudentLeave,
  useRejectStudentLeave,
  useStudents,
} from "@/hooks/queries";
import { Search, Plus, Check, X } from "lucide-react";
import { useToast } from "@/hooks/use-toast";

function leaveBadge(state: string) {
  switch (state) {
    case "draft":
      return <Badge variant="secondary">draft</Badge>;
    case "confirm":
      return <Badge variant="outline">confirm</Badge>;
    case "approve":
    case "validate":
      return (
        <Badge variant="default" className="bg-green-600 hover:bg-green-600">
          {state}
        </Badge>
      );
    case "refuse":
      return <Badge variant="destructive">refuse</Badge>;
    case "cancel":
      return <Badge variant="secondary">cancel</Badge>;
    default:
      return <Badge variant="outline">{state}</Badge>;
  }
}

export default function AdminStudentLeave() {
  const [search, setSearch] = useState("");
  const [createOpen, setCreateOpen] = useState(false);
  const [form, setForm] = useState({
    student_id: "",
    leave_type: "",
    start_date: "",
    end_date: "",
    description: "",
  });
  const { toast } = useToast();
  const { data, isLoading } = useStudentLeaves();
  const items = data?.data ?? data?.items ?? [];
  const createMutation = useCreateStudentLeave();
  const approveMutation = useApproveStudentLeave();
  const rejectMutation = useRejectStudentLeave();
  const { data: studentsData } = useStudents({ size: 500 });
  const studentsList = studentsData?.items ?? [];
  const { data: leaveTypesData } = useStudentLeaveTypes();
  const leaveTypes = leaveTypesData?.data ?? leaveTypesData?.items ?? [];

  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(
    (r) =>
      r.student_name?.toLowerCase().includes(q) ||
      r.leave_type?.toLowerCase().includes(q) ||
      r.description?.toLowerCase().includes(q),
  );

  const canAct = (state: string) => !["approve", "refuse", "cancel"].includes(state);

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-2xl font-bold">Student leave</h1>
          <p className="text-muted-foreground">Review and create leave requests.</p>
        </div>
        <Button onClick={() => setCreateOpen(true)}>
          <Plus className="mr-2 h-4 w-4" />
          New request
        </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 by student or type..."
          value={search}
          onChange={(e) => setSearch(e.target.value)}
          className="pl-9"
        />
      </div>
      <Card>
        <CardContent className="pt-6">
          <Table>
            <TableHeader>
              <TableRow>
                <TableHead>#</TableHead>
                <TableHead>Student</TableHead>
                <TableHead>Leave Type</TableHead>
                <TableHead>Start Date</TableHead>
                <TableHead>End Date</TableHead>
                <TableHead>Duration</TableHead>
                <TableHead>State</TableHead>
                <TableHead>Actions</TableHead>
              </TableRow>
            </TableHeader>
            <TableBody>
              {filtered.map((row, i) => (
                <TableRow key={row.id}>
                  <TableCell>{i + 1}</TableCell>
                  <TableCell className="font-medium">{row.student_name}</TableCell>
                  <TableCell>{row.leave_type}</TableCell>
                  <TableCell>{row.start_date}</TableCell>
                  <TableCell>{row.end_date}</TableCell>
                  <TableCell>{row.duration}</TableCell>
                  <TableCell>{leaveBadge(row.state)}</TableCell>
                  <TableCell>
                    <div className="flex gap-1">
                      <Button
                        size="sm"
                        variant="outline"
                        disabled={!canAct(row.state) || approveMutation.isPending}
                        onClick={() =>
                          approveMutation.mutate(row.id, {
                            onSuccess: () => toast({ title: "Approved" }),
                            onError: (err: Error) =>
                              toast({ title: "Error", description: err.message, variant: "destructive" }),
                          })
                        }
                      >
                        <Check className="h-4 w-4" />
                      </Button>
                      <Button
                        size="sm"
                        variant="destructive"
                        disabled={!canAct(row.state) || rejectMutation.isPending}
                        onClick={() =>
                          rejectMutation.mutate(row.id, {
                            onSuccess: () => toast({ title: "Rejected" }),
                            onError: (err: Error) =>
                              toast({ title: "Error", description: err.message, variant: "destructive" }),
                          })
                        }
                      >
                        <X className="h-4 w-4" />
                      </Button>
                    </div>
                  </TableCell>
                </TableRow>
              ))}
            </TableBody>
          </Table>
        </CardContent>
      </Card>

      <Dialog open={createOpen} onOpenChange={setCreateOpen}>
        <DialogContent>
          <DialogHeader>
            <DialogTitle>Create leave request</DialogTitle>
          </DialogHeader>
          <div className="space-y-4">
            <div className="space-y-2">
              <Label>Student *</Label>
              <Select value={form.student_id || "__none__"} onValueChange={(v) => setForm((f) => ({ ...f, student_id: v === "__none__" ? "" : v }))}>
                <SelectTrigger><SelectValue placeholder="Select student" /></SelectTrigger>
                <SelectContent>
                  <SelectItem value="__none__">— Select —</SelectItem>
                  {studentsList.map((s) => <SelectItem key={s.id} value={String(s.id)}>{s.name}</SelectItem>)}
                </SelectContent>
              </Select>
            </div>
            <div className="space-y-2">
              <Label>Leave Type *</Label>
              <Select value={form.leave_type || "__none__"} onValueChange={(v) => setForm((f) => ({ ...f, leave_type: v === "__none__" ? "" : v }))}>
                <SelectTrigger><SelectValue placeholder="Select leave type" /></SelectTrigger>
                <SelectContent>
                  <SelectItem value="__none__">— Select —</SelectItem>
                  {leaveTypes.map((t: { id: number; name: string }) => <SelectItem key={t.id} value={String(t.id)}>{t.name}</SelectItem>)}
                </SelectContent>
              </Select>
            </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((f) => ({ ...f, 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((f) => ({ ...f, end_date: e.target.value }))}
                />
              </div>
            </div>
            <div className="space-y-2">
              <Label>Description</Label>
              <Input
                value={form.description}
                onChange={(e) => setForm((f) => ({ ...f, description: e.target.value }))}
              />
            </div>
          </div>
          <DialogFooter>
            <Button variant="outline" onClick={() => setCreateOpen(false)}>
              Cancel
            </Button>
            <Button
              disabled={createMutation.isPending || !form.student_id || !form.leave_type || !form.start_date || !form.end_date}
              onClick={() => {
                createMutation.mutate(
                  {
                    student_id: Number(form.student_id),
                    leave_type: Number(form.leave_type),
                    start_date: form.start_date,
                    end_date: form.end_date,
                    description: form.description || undefined,
                  },
                  {
                    onSuccess: () => {
                      setCreateOpen(false);
                      setForm({ student_id: "", leave_type: "", start_date: "", end_date: "", description: "" });
                      toast({ title: "Created successfully" });
                    },
                    onError: (err: Error) =>
                      toast({ title: "Error", description: err.message, variant: "destructive" }),
                  },
                );
              }}
            >
              Create
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  );
}
