"use client";

import { useState, useEffect, useRef, useMemo } from "react";
import { Card, CardContent, CardHeader } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Badge } from "@/components/ui/badge";
import { Skeleton } from "@/components/ui/skeleton";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import {
  Briefcase,
  Plus,
  Search,
  Eye,
  Pencil,
  Trash2,
  Loader2,
} from "lucide-react";
import { usePagination } from "@/lib/pagination";
import { PaginationBar } from "@/components/common/PaginationBar";
import { useConfirmDelete } from "@/components/common/useConfirmDelete";
import { useGetServices, useDeleteService } from "../hooks/service.hook";
import { useRouter } from "next/navigation";
import { ServiceCategory } from "../types/service.type";
import { formatDateTime } from "@/lib/format-date";

const CATEGORIES: ServiceCategory[] = [
  "GST",
  "ITR",
  "TDS",
  "AUDIT",
  "ROC",
  "MSME",
  "PAN",
  "TAN",
  "DSC",
  "IEC",
  "TRADEMARK",
  "OTHER",
];

const categoryLabel: Record<ServiceCategory, string> = {
  GST: "GST",
  ITR: "ITR",
  TDS: "TDS",
  AUDIT: "Audit",
  ROC: "ROC",
  MSME: "MSME",
  PAN: "PAN",
  TAN: "TAN",
  DSC: "DSC",
  IEC: "IEC",
  TRADEMARK: "Trademark",
  OTHER: "Other",
};

const categoryColor: Record<ServiceCategory, string> = {
  GST: "text-blue-600 border-blue-600/30 bg-blue-500/10",
  ITR: "text-emerald-600 border-emerald-600/30 bg-emerald-500/10",
  TDS: "text-amber-600 border-amber-600/30 bg-amber-500/10",
  AUDIT: "text-purple-600 border-purple-600/30 bg-purple-500/10",
  ROC: "text-sky-600 border-sky-600/30 bg-sky-500/10",
  MSME: "text-orange-600 border-orange-600/30 bg-orange-500/10",
  PAN: "text-rose-600 border-rose-600/30 bg-rose-500/10",
  TAN: "text-teal-600 border-teal-600/30 bg-teal-500/10",
  DSC: "text-indigo-600 border-indigo-600/30 bg-indigo-500/10",
  IEC: "text-cyan-600 border-cyan-600/30 bg-cyan-500/10",
  TRADEMARK: "text-pink-600 border-pink-600/30 bg-pink-500/10",
  OTHER: "text-muted-foreground border-border bg-muted",
};

export function ServiceDashboard() {
  const router = useRouter();
  const { pagination, setPage, setSearch } = usePagination(10);
  const [categoryFilter, setCategoryFilter] = useState("ALL");
  const [searchInput, setSearchInput] = useState("");
  const debounceRef = useRef<ReturnType<typeof setTimeout> | null>(null);
  const [navigating, setNavigating] = useState<{
    id: string;
    type: "view" | "edit";
  } | null>(null);

  const handleView = (id: string) => {
    setNavigating({ id, type: "view" });
    router.push(`/admin/services/${id}`);
  };

  const handleEdit = (id: string) => {
    setNavigating({ id, type: "edit" });
    router.push(`/admin/services/${id}/edit`);
  };

  useEffect(() => {
    if (debounceRef.current) clearTimeout(debounceRef.current);
    debounceRef.current = setTimeout(() => {
      if (searchInput.length === 0 || searchInput.length >= 3) {
        setSearch(searchInput);
      }
    }, 400);
    return () => {
      if (debounceRef.current) clearTimeout(debounceRef.current);
    };
  }, [searchInput]);

  const params = useMemo(
    () => ({
      ...pagination,
      ...(categoryFilter !== "ALL" ? { category: categoryFilter } : {}),
    }),
    [pagination, categoryFilter]
  );

  const { data, isLoading } = useGetServices(params);
  // const { mutate: deleteMutate } = useDeleteService();
  const { mutateAsync: deleteAsync } = useDeleteService();

  const { open: openDelete, Dialog: DeleteDialog } = useConfirmDelete(
    (id) => deleteAsync(id),
    { title: "Delete Service" }
  );

  const services = data?.data ?? [];
  const meta = data?.meta;

  return (
    <div className="space-y-6">
      <Card className="border-border bg-card shadow-sm">
        <CardHeader className="flex flex-col sm:flex-row items-start sm:items-center justify-between gap-4 py-4 px-5">
          <div>
            <h2 className="text-2xl font-bold tracking-tight text-foreground">
              Services
            </h2>
            <p className="text-muted-foreground text-sm mt-1">
              Manage your organization&apos;s service offerings
            </p>
          </div>
          <Button
            onClick={() => router.push("/admin/services/create")}
            className="bg-primary hover:bg-primary/90 text-primary-foreground font-semibold text-xs h-9 flex items-center gap-2"
          >
            <Plus className="h-4 w-4" /> Add Service
          </Button>
        </CardHeader>
      </Card>

      <Card className="border-border bg-card shadow-sm">
        <CardHeader className="border-b border-border py-3 px-5">
          <div className="flex flex-col sm:flex-row items-start sm:items-center gap-2">
            <div className="relative flex-1 sm:w-72">
              <Search className="absolute left-2.5 top-1/2 -translate-y-1/2 h-3.5 w-3.5 text-muted-foreground" />
              <Input
                value={searchInput}
                onChange={(e) => setSearchInput(e.target.value)}
                placeholder="Search by name (min 3 chars)..."
                className="pl-8 h-9 text-sm bg-background border-border"
              />
            </div>
            <Select
              value={categoryFilter}
              onValueChange={(v) => {
                setCategoryFilter(v);
                setPage(1);
              }}
            >
              <SelectTrigger className="h-9 text-sm w-44 bg-background border-border">
                <SelectValue placeholder="All Categories" />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="ALL">All Categories</SelectItem>
                {CATEGORIES.map((c) => (
                  <SelectItem key={c} value={c}>
                    {categoryLabel[c]}
                  </SelectItem>
                ))}
              </SelectContent>
            </Select>
          </div>
        </CardHeader>

        <CardContent className="p-0">
          {isLoading ? (
            <div className="p-6 space-y-3">
              {[1, 2, 3].map((i) => (
                <Skeleton key={i} className="h-12 w-full rounded-lg" />
              ))}
            </div>
          ) : services.length === 0 ? (
            <div className="flex flex-col items-center justify-center py-16 text-center">
              <Briefcase className="h-10 w-10 text-muted-foreground/30 mb-3" />
              <p className="text-sm font-semibold text-muted-foreground">
                {pagination.search || categoryFilter !== "ALL"
                  ? "No services match your filters"
                  : "No services yet"}
              </p>
              {!pagination.search && categoryFilter === "ALL" && (
                <p className="text-xs text-muted-foreground/60 mt-1">
                  Click "Add Service" to get started
                </p>
              )}
            </div>
          ) : (
            <>
              <div className="overflow-x-auto">
                <table className="w-full text-left">
                  <thead>
                    <tr className="bg-muted border-b border-border text-[11px] font-bold text-muted-foreground uppercase tracking-wider">
                      <th className="py-2.5 px-4">#</th>
                      <th className="py-2.5 px-4">Name</th>
                      <th className="py-2.5 px-4">Category</th>
                      <th className="py-2.5 px-4">Price</th>
                      <th className="py-2.5 px-4 hidden md:table-cell">
                        Description
                      </th>
                      <th className="py-2.5 px-4">DIY</th>
                      <th className="py-2.5 px-4 hidden lg:table-cell">
                        Created
                      </th>
                      <th className="py-2.5 px-4 text-center w-32">Actions</th>
                    </tr>
                  </thead>
                  <tbody className="divide-y divide-border text-xs text-foreground">
                    {services.map((svc, idx) => {
                      const isViewLoading =
                        navigating?.id === svc.id &&
                        navigating?.type === "view";
                      const isEditLoading =
                        navigating?.id === svc.id &&
                        navigating?.type === "edit";
                      const isRowDisabled = navigating !== null;
                      return (
                        <tr
                          key={svc.id}
                          className="hover:bg-secondary/20 transition-colors"
                        >
                          <td className="py-3 px-4 text-muted-foreground font-mono">
                            {(pagination.page - 1) * pagination.limit + idx + 1}
                          </td>
                          <td className="py-3 px-4 font-semibold text-foreground whitespace-nowrap">
                            {svc.name}
                          </td>
                          <td className="py-3 px-4">
                            <Badge
                              variant="outline"
                              className={`text-[10px] ${
                                categoryColor[svc.category]
                              }`}
                            >
                              {categoryLabel[svc.category]}
                            </Badge>
                          </td>
                          <td className="py-3 px-4 font-mono text-foreground whitespace-nowrap">
                            ₹{svc.price.toLocaleString("en-IN")}
                          </td>
                          <td className="py-3 px-4 hidden md:table-cell text-muted-foreground max-w-[200px] truncate">
                            {svc.description || (
                              <span className="text-muted-foreground/40">
                                —
                              </span>
                            )}
                          </td>
                          <td className="py-3 px-4">
                            <Badge
                              variant="outline"
                              className={
                                svc.isDiyEnabled
                                  ? "text-emerald-600 border-emerald-600/30 bg-emerald-500/10 text-[10px]"
                                  : "text-muted-foreground border-border bg-muted text-[10px]"
                              }
                            >
                              {svc.isDiyEnabled ? "Yes" : "No"}
                            </Badge>
                          </td>
                          <td className="py-3 px-4 hidden lg:table-cell text-muted-foreground whitespace-nowrap">
                            {formatDateTime(svc.createdAt)}
                          </td>
                          <td className="py-3 px-4 w-32">
                            <div className="flex items-center justify-end  gap-1">
                              {/* <Button
                              variant="ghost"
                              size="icon"
                              onClick={() =>
                                router.push(`/admin/services/${svc.id}`)
                              }
                              className="h-7 w-7 rounded-lg text-muted-foreground hover:text-primary hover:bg-primary/10"
                              title="View"
                            >
                              <Eye className="h-3.5 w-3.5" />
                            </Button> */}
                              <Button
                                variant="ghost"
                                size="icon"
                                onClick={() => handleView(svc.id)}
                                disabled={isRowDisabled}
                                className="h-7 w-7 rounded-lg text-muted-foreground hover:text-primary hover:bg-primary/10"
                                title="View"
                              >
                                {isViewLoading ? (
                                  <Loader2 className="h-3.5 w-3.5 animate-spin" />
                                ) : (
                                  <Eye className="h-3.5 w-3.5" />
                                )}
                              </Button>
                              <Button
                                variant="ghost"
                                size="icon"
                                onClick={() => handleEdit(svc.id)}
                                disabled={isRowDisabled}
                                className="h-7 w-7 rounded-lg text-muted-foreground hover:text-amber-600 hover:bg-amber-500/10"
                                title="Edit"
                              >
                                {isEditLoading ? (
                                  <Loader2 className="h-3.5 w-3.5 animate-spin" />
                                ) : (
                                  <Pencil className="h-3.5 w-3.5" />
                                )}
                              </Button>
                              <Button
                                variant="ghost"
                                size="icon"
                                onClick={() => openDelete(svc.id, svc.name)}
                                disabled={isRowDisabled}
                                className="h-7 w-7 rounded-lg text-muted-foreground hover:text-destructive hover:bg-destructive/10"
                                title="Delete"
                              >
                                <Trash2 className="h-3.5 w-3.5" />
                              </Button>
                            </div>
                          </td>
                        </tr>
                      );
                    })}
                  </tbody>
                </table>
              </div>
              {meta && <PaginationBar meta={meta} onPageChange={setPage} />}
            </>
          )}
        </CardContent>
      </Card>

      <DeleteDialog />
    </div>
  );
}
