"use client";

import { useState, useEffect, useRef } 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 {
  Users,
  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 { useGetClients, useDeleteClient } from "../hooks/client.hooks";
import { useRouter } from "next/navigation";
import { getStatusVariant } from "@/lib/status-variant";

export function ClientDashboard() {
  const router = useRouter();
  const { pagination, setPage, setSearch } = usePagination(10);
  const [statusFilter, setStatusFilter] = 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/clients/${id}`);
  };

  const handleEdit = (id: string) => {
    setNavigating({ id, type: "edit" });
    router.push(`/admin/clients/${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 = {
    ...pagination,
    ...(statusFilter !== "ALL" ? { status: statusFilter } : {}),
  };

  const { data, isLoading } = useGetClients(params);
  const { mutateAsync: deleteAsync } = useDeleteClient();

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

  const clients = 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">
              Clients
            </h2>
            <p className="text-muted-foreground text-sm mt-1">
              Manage and invite your organization&apos;s clients
            </p>
          </div>
          <Button
            onClick={() => router.push("/admin/clients/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 Client
          </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 or email (min 3 chars)..."
                className="pl-8 h-9 text-sm bg-background border-border"
              />
            </div>
            <Select
              value={statusFilter}
              onValueChange={(v) => {
                setStatusFilter(v);
                setPage(1);
              }}
            >
              <SelectTrigger className="h-9 text-sm w-36 bg-background border-border">
                <SelectValue placeholder="All Status" />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="ALL">All Status</SelectItem>
                <SelectItem value="ACTIVE">Active</SelectItem>
                <SelectItem value="INVITED">Invited</SelectItem>
                <SelectItem value="INACTIVE">Inactive</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>
          ) : clients.length === 0 ? (
            <div className="flex flex-col items-center justify-center py-16 text-center">
              <Users className="h-10 w-10 text-muted-foreground/30 mb-3" />
              <p className="text-sm font-semibold text-muted-foreground">
                {pagination.search || statusFilter !== "ALL"
                  ? "No clients match your filters"
                  : "No clients yet"}
              </p>
              {!pagination.search && statusFilter === "ALL" && (
                <p className="text-xs text-muted-foreground/60 mt-1">
                  Click &quot;Invite Client&quot; 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">Email</th>
                      <th className="py-2.5 px-4">Company</th>
                      <th className="py-2.5 px-4">Phone</th>
                      <th className="py-2.5 px-4">Status</th>
                      <th className="py-2.5 px-4 hidden lg:table-cell">
                        Added
                      </th>
                      <th className="py-2.5 px-4 text-center">Actions</th>
                    </tr>
                  </thead>
                  <tbody className="divide-y divide-border text-xs text-foreground">
                    {clients.map((client, idx) => {
                      const isViewLoading =
                        navigating?.id === client.id &&
                        navigating?.type === "view";
                      const isEditLoading =
                        navigating?.id === client.id &&
                        navigating?.type === "edit";
                      const isRowDisabled = navigating !== null;
                      return (
                        <tr
                          key={client.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">
                            {client.name}
                          </td>
                          <td className="py-3 px-4 text-muted-foreground">
                            {client.email}
                          </td>
                          <td className="py-3 px-4 text-muted-foreground">
                            {client.companyName ?? (
                              <span className="text-muted-foreground/40">
                                —
                              </span>
                            )}
                          </td>
                          <td className="py-3 px-4 text-muted-foreground">
                            {client.phone ?? (
                              <span className="text-muted-foreground/40">
                                —
                              </span>
                            )}
                          </td>
                          <td className="py-3 px-4">
                            <Badge
                              variant={getStatusVariant(client.status)}
                              className="text-[10px]"
                            >
                              {client.status}
                            </Badge>
                          </td>
                          <td className="py-3 px-4 hidden lg:table-cell text-muted-foreground whitespace-nowrap">
                            {new Date(client.createdAt).toLocaleDateString(
                              "en-IN",
                              {
                                day: "2-digit",
                                month: "short",
                                year: "numeric",
                              }
                            )}
                          </td>
                          <td className="py-3 px-4">
                            <div className="flex items-center justify-center gap-1">
                              {/* <Button
                              variant="ghost"
                              size="icon"
                              onClick={() =>
                                router.push(`/admin/clients/${client.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(client.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(client.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(client.id, client.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>
  );
}
