"use client";

import { useState, useRef, useEffect } from "react";
import { PageHeader } from "@/components/admin/PageHeader";
import { FormSheet } from "@/components/admin/FormSheet";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Textarea } from "@/components/ui/textarea";
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table";
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import { Button } from "@/components/ui/button";
import { Skeleton } from "@/components/ui/skeleton";
import {
  Plus,
  Trash2,
  Search,
  ChevronLeft,
  ChevronRight,
  MoreHorizontal,
  Pencil,
} from "lucide-react";
import { toast } from "sonner";
import {
  getCertificates,
  createCertificate,
  updateCertificate,
  deleteCertificate,
  type Certificate,
  type PaginationMeta,
  type PaginatedCertificates,
} from "@/services/certificates";

interface FormState {
  equipment: string;
  id_number: string;
  certificate_no: string;
  inspection_date: string;
  next_due_date: string;
  location: string;
  examination: string;
  company: string;
  remark: string;
}

const emptyForm = (): FormState => ({
  equipment: "",
  id_number: "",
  certificate_no: "",
  inspection_date: "",
  next_due_date: "",
  location: "",
  examination: "",
  company: "",
  remark: "",
});

export default function CertificatesAdmin() {
  const [certificates, setCertificates] = useState<Certificate[]>([]);
  const [loading, setLoading] = useState(true);
  const [search, setSearch] = useState("");
  const [editing, setEditing] = useState<Certificate | null>(null);
  const [isAdding, setIsAdding] = useState(false);
  const [form, setForm] = useState<FormState>(emptyForm());
  const [isSaving, setIsSaving] = useState(false);
  const [deletingId, setDeletingId] = useState<number | null>(null);
  const debounceRef = useRef<ReturnType<typeof setTimeout> | null>(null);

  const [page, setPage] = useState(1);
  const [meta, setMeta] = useState<PaginationMeta | null>(null);

  useEffect(() => {
    loadCertificates();
  }, []);

  const loadCertificates = async (pageNum: number = 1, searchQuery: string = "") => {
    try {
      setLoading(true);
      const res = await getCertificates({
        search: searchQuery,
        page: pageNum,
      });
      setCertificates(res.data);
      setMeta(res.meta);
    } catch (error) {
      toast.error("Failed to load certificates");
      console.error(error);
    } finally {
      setLoading(false);
    }
  };

  const handleSearch = (value: string) => {
    setSearch(value);
    setPage(1);

    if (debounceRef.current) clearTimeout(debounceRef.current);
    debounceRef.current = setTimeout(() => {
      loadCertificates(1, value);
    }, 500);
  };

  const handleOpenAdd = () => {
    setEditing(null);
    setForm(emptyForm());
    setIsAdding(true);
  };

  const handleOpenEdit = (cert: Certificate) => {
    setEditing(cert);
    setForm({
      equipment: cert.equipment,
      id_number: cert.id_number,
      certificate_no: cert.certificate_no,
      inspection_date: cert.inspection_date,
      next_due_date: cert.next_due_date,
      location: cert.location,
      examination: cert.examination,
      company: cert.company,
      remark: cert.remark,
    });
    setIsAdding(true);
  };

  const handleSave = async () => {
    if (
      !form.equipment.trim() ||
      !form.id_number.trim() ||
      !form.certificate_no.trim() ||
      !form.inspection_date.trim() ||
      !form.next_due_date.trim() ||
      !form.location.trim() ||
      !form.company.trim()
    ) {
      toast.error("Please fill in all required fields");
      return;
    }

    setIsSaving(true);
    try {
      if (editing) {
        await updateCertificate(editing.id, form);
        toast.success("Certificate updated successfully");
      } else {
        await createCertificate(form);
        toast.success("Certificate created successfully");
      }
      setIsAdding(false);
      loadCertificates(page, search);
    } catch (error: any) {
      const errorMessage =
        error?.response?.data?.message || "Failed to save certificate";
      toast.error(errorMessage);
      console.error(error);
    } finally {
      setIsSaving(false);
    }
  };

  const handleDelete = async (cert: Certificate) => {
    if (deletingId) return;
    setDeletingId(cert.id);
    try {
      await deleteCertificate(cert.id);
      setCertificates((prev) => prev.filter((x) => x.id !== cert.id));
      toast.success("Certificate deleted successfully");
    } catch {
      // interceptor shows error toast
    } finally {
      setDeletingId(null);
    }
  };

  return (
    <div className="p-6 lg:p-8 max-w-7xl mx-auto">
      <PageHeader
        title="Inspection Certificates"
        description="Manage inspection certificate records"
        onAdd={handleOpenAdd}
        addLabel="Add Certificate"
      />

      <div className="relative max-w-sm mb-4">
        <Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
        <Input
          placeholder="Search certificates"
          value={search}
          onChange={(e) => handleSearch(e.target.value)}
          className="pl-9 h-9"
        />
      </div>

      <FormSheet
        title={editing ? `Edit: ${editing.equipment}` : "Add Certificate"}
        open={isAdding}
        onOpenChange={(open) => !open && setIsAdding(false)}
        onSave={handleSave}
        loading={isSaving}
      >
        <div className="space-y-2">
          <Label>Equipment *</Label>
          <Input
            value={form.equipment}
            onChange={(e) => setForm({ ...form, equipment: e.target.value })}
            placeholder="e.g., Compressor A"
          />
        </div>
        <div className="space-y-2">
          <Label>ID Number *</Label>
          <Input
            value={form.id_number}
            onChange={(e) => setForm({ ...form, id_number: e.target.value })}
            placeholder="e.g., EQ-1234"
          />
        </div>
        <div className="grid grid-cols-2 gap-3">
          <div className="space-y-2">
            <Label>Certificate No *</Label>
            <Input
              value={form.certificate_no}
              onChange={(e) => setForm({ ...form, certificate_no: e.target.value })}
              placeholder="e.g., CERT-2026-0001"
            />
          </div>
          <div className="space-y-2">
            <Label>Company *</Label>
            <Input
              value={form.company}
              onChange={(e) => setForm({ ...form, company: e.target.value })}
              placeholder="e.g., Acme Inspections"
            />
          </div>
        </div>
        <div className="grid grid-cols-2 gap-3">
          <div className="space-y-2">
            <Label>Inspection Date *</Label>
            <Input
              type="date"
              value={form.inspection_date}
              onChange={(e) => setForm({ ...form, inspection_date: e.target.value })}
            />
          </div>
          <div className="space-y-2">
            <Label>Next Due Date *</Label>
            <Input
              type="date"
              value={form.next_due_date}
              onChange={(e) => setForm({ ...form, next_due_date: e.target.value })}
            />
          </div>
        </div>
        <div className="space-y-2">
          <Label>Location *</Label>
          <Input
            value={form.location}
            onChange={(e) => setForm({ ...form, location: e.target.value })}
            placeholder="e.g., Site 1"
          />
        </div>
        <div className="space-y-2">
          <Label>Examination</Label>
          <Textarea
            value={form.examination}
            onChange={(e) => setForm({ ...form, examination: e.target.value })}
            placeholder="e.g., Pressure test passed"
            rows={3}
          />
        </div>
        <div className="space-y-2">
          <Label>Remark</Label>
          <Textarea
            value={form.remark}
            onChange={(e) => setForm({ ...form, remark: e.target.value })}
            placeholder="Additional notes or observations"
            rows={3}
          />
        </div>
      </FormSheet>

      {loading ? (
        <div className="space-y-2">
          {Array.from({ length: 5 }).map((_, i) => (
            <Skeleton key={i} className="h-14 w-full rounded-md" />
          ))}
        </div>
      ) : certificates.length === 0 ? (
        <div className="text-center py-12 text-sm text-muted-foreground bg-card rounded-lg border">
          No certificates found.
        </div>
      ) : (
        <div className="bg-card rounded-lg border overflow-hidden">
          <Table>
            <TableHeader>
              <TableRow className="bg-muted/50">
                <TableHead className="text-xs font-semibold uppercase tracking-wider">Equipment</TableHead>
                <TableHead className="text-xs font-semibold uppercase tracking-wider">ID Number</TableHead>
                <TableHead className="text-xs font-semibold uppercase tracking-wider">Certificate No</TableHead>
                <TableHead className="text-xs font-semibold uppercase tracking-wider">Inspection Date</TableHead>
                <TableHead className="text-xs font-semibold uppercase tracking-wider">Next Due Date</TableHead>
                <TableHead className="text-xs font-semibold uppercase tracking-wider">Location</TableHead>
                <TableHead className="text-xs font-semibold uppercase tracking-wider">Company</TableHead>
                <TableHead className="w-12" />
              </TableRow>
            </TableHeader>
            <TableBody>
              {certificates.map((cert) => (
                <TableRow key={cert.id} className="group">
                  <TableCell className="text-sm">{cert.equipment}</TableCell>
                  <TableCell className="font-mono text-sm">{cert.id_number}</TableCell>
                  <TableCell className="font-mono text-sm">{cert.certificate_no}</TableCell>
                  <TableCell className="text-sm">{cert.inspection_date}</TableCell>
                  <TableCell className="text-sm">{cert.next_due_date}</TableCell>
                  <TableCell className="text-sm">{cert.location}</TableCell>
                  <TableCell className="text-sm">{cert.company}</TableCell>
                  <TableCell className="w-12">
                    <DropdownMenu>
                      <DropdownMenuTrigger className="inline-flex h-8 w-8 items-center justify-center rounded-md opacity-0 transition-opacity group-hover:opacity-100 hover:bg-accent hover:text-accent-foreground focus-visible:outline-none">
                        <MoreHorizontal className="h-4 w-4" />
                      </DropdownMenuTrigger>
                      <DropdownMenuContent align="end">
                        <DropdownMenuItem onClick={() => handleOpenEdit(cert)}>
                          <Pencil className="mr-2 h-3.5 w-3.5" /> Edit
                        </DropdownMenuItem>
                        <DropdownMenuItem
                          onClick={() => handleDelete(cert)}
                          disabled={deletingId === cert.id}
                          className="text-destructive"
                        >
                          <Trash2 className="mr-2 h-3.5 w-3.5" /> Delete
                        </DropdownMenuItem>
                      </DropdownMenuContent>
                    </DropdownMenu>
                  </TableCell>
                </TableRow>
              ))}
            </TableBody>
          </Table>
        </div>
      )}

      {meta && meta.last_page > 1 && (
        <div className="flex items-center justify-between mt-4">
          <p className="text-sm text-muted-foreground">
            Page {meta.current_page} of {meta.last_page} &middot; {meta.total} total
          </p>
          <div className="flex items-center gap-2">
            <Button
              variant="outline"
              size="icon"
              className="h-8 w-8"
              disabled={meta.current_page <= 1}
              onClick={() => {
                const newPage = page - 1;
                setPage(newPage);
                loadCertificates(newPage, search);
              }}
            >
              <ChevronLeft className="h-4 w-4" />
            </Button>
            <Button
              variant="outline"
              size="icon"
              className="h-8 w-8"
              disabled={meta.current_page >= meta.last_page}
              onClick={() => {
                const newPage = page + 1;
                setPage(newPage);
                loadCertificates(newPage, search);
              }}
            >
              <ChevronRight className="h-4 w-4" />
            </Button>
          </div>
        </div>
      )}
    </div>
  );
}
