"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 {
  ClipboardList,
  Eye,
  Pencil,
  Plus,
  Search,
  Trash2,
  Clock,
  CheckCircle2,
  XCircle,
  Loader2,
} from "lucide-react";
import { usePagination } from "@/lib/pagination";
import { PaginationBar } from "@/components/common/PaginationBar";
import { useConfirmDelete } from "@/components/common/useConfirmDelete";
import {
  useAdminGetTasks,
  useAdminDeleteTask,
  useAdminTaskStats,
} from "../hooks/task.hooks";
import { useRouter } from "next/navigation";
import { getStatusVariant } from "@/lib/status-variant";
import {
  Tooltip,
  TooltipContent,
  TooltipTrigger,
} from "@/components/ui/tooltip";
import { useTaskSocket } from "@/hooks/useTaskSocket";
import { useAppSelector } from "@/lib/store";

const TASK_STATUSES: { label: string; value: string }[] = [
  { label: "All Status", value: "ALL" },
  { label: "Pending", value: "PENDING" },
  { label: "In Progress", value: "IN_PROGRESS" },
  { label: "Employee Done", value: "EMPLOYEE_DONE" },
  { label: "Manager Approval", value: "MANAGER_APPROVAL" },
  { label: "Client Approval", value: "CLIENT_APPROVAL" },
  { label: "Filing Pending", value: "FILING_PENDING" },
  { label: "Completed", value: "COMPLETED" },
  { label: "Rejected", value: "REJECTED" },
];

const PRIORITIES: { label: string; value: string }[] = [
  { label: "All Priority", value: "ALL" },
  { label: "Low", value: "LOW" },
  { label: "Medium", value: "MEDIUM" },
  { label: "High", value: "HIGH" },
  { label: "Urgent", value: "URGENT" },
];

export function TaskDashboard() {
  const router = useRouter();
  const orgId = useAppSelector((s) => s.auth.user?.organizationId);
  useTaskSocket(orgId, ["admin-tasks"]);
  const { pagination, setPage, setSearch } = usePagination(10);
  const [statusFilter, setStatusFilter] = useState("ALL");
  const [priorityFilter, setPriorityFilter] = 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/tasks/${id}`);
  };

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

  const { mutateAsync: deleteAsync } = useAdminDeleteTask();
  const { open: openDelete, Dialog: DeleteDialog } = useConfirmDelete(
    (id) => deleteAsync(id),
    { title: "Delete Task" }
  );
  const { data: stats, isLoading: statsLoading } = useAdminTaskStats();

  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 } : {}),
    ...(priorityFilter !== "ALL" ? { priority: priorityFilter } : {}),
  };

  const { data, isLoading } = useAdminGetTasks(params);
  const tasks = 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">
              Tasks
            </h2>
            <p className="text-muted-foreground text-sm mt-1">
              Manage all client tasks, assign employees and update status
            </p>
          </div>
          <Button
            onClick={() => router.push("/admin/tasks/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 Task
          </Button>
        </CardHeader>
      </Card>

      {/* Stat Cards — 3 in one row */}
      <div
        style={{
          display: "grid",
          gridTemplateColumns: "repeat(3, 1fr)",
          gap: "1rem",
        }}
      >
        {[
          {
            label: "Pending",
            value: stats?.pending ?? 0,
            icon: Clock,
            color: "#D97706",
            bg: "#FFFBEB",
          },
          {
            label: "Completed",
            value: stats?.completed ?? 0,
            icon: CheckCircle2,
            color: "#059669",
            bg: "#ECFDF5",
          },
          {
            label: "Rejected",
            value: stats?.rejected ?? 0,
            icon: XCircle,
            color: "#DC2626",
            bg: "#FEF2F2",
          },
        ].map(({ label, value, icon: Icon, color, bg }) => (
          <div
            key={label}
            style={{
              background: "hsl(var(--card))",
              border: "1px solid hsl(var(--border))",
              borderRadius: 8,
              padding: "14px 16px",
              display: "flex",
              alignItems: "center",
              justifyContent: "space-between",
            }}
          >
            <div>
              <p
                style={{
                  fontSize: 10,
                  fontWeight: 600,
                  textTransform: "uppercase",
                  letterSpacing: "0.06em",
                  color: "hsl(var(--muted-foreground))",
                }}
              >
                {label}
              </p>
              <p
                style={{
                  fontSize: 26,
                  fontWeight: 700,
                  marginTop: 2,
                  color: "hsl(var(--foreground))",
                }}
              >
                {statsLoading ? (
                  <span
                    style={{
                      display: "inline-block",
                      width: 32,
                      height: 24,
                      background: "hsl(var(--muted))",
                      borderRadius: 4,
                    }}
                  />
                ) : (
                  value
                )}
              </p>
            </div>
            <div
              style={{
                width: 36,
                height: 36,
                borderRadius: 10,
                background: bg,
                display: "flex",
                alignItems: "center",
                justifyContent: "center",
                flexShrink: 0,
              }}
            >
              <Icon size={18} color={color} />
            </div>
          </div>
        ))}
      </div>

      <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 flex-wrap">
            <div className="relative flex-1 min-w-[200px] 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 title, client, service..."
                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-44 bg-background border-border">
                <SelectValue placeholder="All Status" />
              </SelectTrigger>
              <SelectContent>
                {TASK_STATUSES.map((s) => (
                  <SelectItem key={s.value} value={s.value}>
                    {s.label}
                  </SelectItem>
                ))}
              </SelectContent>
            </Select>
            <Select
              value={priorityFilter}
              onValueChange={(v) => {
                setPriorityFilter(v);
                setPage(1);
              }}
            >
              <SelectTrigger className="h-9 text-sm w-36 bg-background border-border">
                <SelectValue placeholder="All Priority" />
              </SelectTrigger>
              <SelectContent>
                {PRIORITIES.map((p) => (
                  <SelectItem key={p.value} value={p.value}>
                    {p.label}
                  </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>
          ) : tasks.length === 0 ? (
            <div className="flex flex-col items-center justify-center py-16 text-center gap-2">
              <div className="rounded-full bg-muted p-4">
                <ClipboardList className="h-8 w-8 text-muted-foreground/50" />
              </div>
              <p className="text-sm font-semibold text-muted-foreground">
                {pagination.search ||
                statusFilter !== "ALL" ||
                priorityFilter !== "ALL"
                  ? "No tasks match your filters"
                  : "No tasks yet"}
              </p>
              {!pagination.search &&
                statusFilter === "ALL" &&
                priorityFilter === "ALL" && (
                  <p className="text-xs text-muted-foreground/60">
                    Tasks will appear here once available.
                  </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">Title</th>
                      <th className="py-2.5 px-4">Client</th>
                      <th className="py-2.5 px-4">Service</th>
                      <th className="py-2.5 px-4">Assigned To</th>
                      <th className="py-2.5 px-4">Priority</th>
                      <th className="py-2.5 px-4">Status</th>
                      <th className="py-2.5 px-4">Payment</th>
                      <th className="py-2.5 px-4">Docs</th>
                      <th className="py-2.5 px-4 hidden lg:table-cell">
                        Due Date
                      </th>
                      <th className="py-2.5 px-4 text-center">Actions</th>
                    </tr>
                  </thead>
                  <tbody className="divide-y divide-border text-xs text-foreground">
                    {tasks.map((task, idx) => {
                      const isViewLoading =
                        navigating?.id === task.id &&
                        navigating?.type === "view";
                      const isEditLoading =
                        navigating?.id === task.id &&
                        navigating?.type === "edit";
                      const isRowDisabled = navigating !== null;
                      return (
                        <tr
                          key={task.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 max-w-[160px]">
                            <Tooltip>
                              <TooltipTrigger asChild>
                                <span className="block max-w-[160px] truncate cursor-default">
                                  {task.title}
                                </span>
                              </TooltipTrigger>

                              <TooltipContent>
                                <span>{task.title}</span>
                              </TooltipContent>
                            </Tooltip>
                          </td>
                          <td className="py-3 px-4">
                            <div className="font-medium">
                              {task.client.name}
                            </div>
                            <div className="text-muted-foreground text-[10px]">
                              {task.client.email}
                            </div>
                          </td>
                          <td className="py-3 px-4 text-muted-foreground">
                            {task.service.name}
                          </td>
                          <td className="py-3 px-4">
                            {task.assignedEmployee ? (
                              <div>
                                <div className="font-medium">
                                  {task.assignedEmployee.name}
                                </div>
                                <div className="text-muted-foreground text-[10px] capitalize">
                                  {task.assignedEmployee.role.toLowerCase()}
                                </div>
                              </div>
                            ) : (
                              <span className="text-muted-foreground/40">
                                Unassigned
                              </span>
                            )}
                          </td>
                          <td className="py-3 px-4">
                            <Badge
                              variant={getStatusVariant(task.priority)}
                              className="text-[10px]"
                            >
                              {task.priority}
                            </Badge>
                          </td>
                          <td className="py-3 px-4">
                            <Badge
                              variant={getStatusVariant(task.status)}
                              className="text-[10px]"
                            >
                              {task.status.replace(/_/g, " ")}
                            </Badge>
                          </td>
                          <td className="py-3 px-4">
                            {task.invoice ? (
                              <Badge
                                variant={getStatusVariant(task.invoice.status)}
                                className="text-[10px] capitalize"
                              >
                                {task.invoice.status.replace(/_/g, " ")}
                              </Badge>
                            ) : (
                              <span className="text-muted-foreground/40 text-xs">
                                —
                              </span>
                            )}
                          </td>
                          <td className="py-3 px-4 text-muted-foreground">
                            {task.documents.length}
                          </td>
                          <td className="py-3 px-4 hidden lg:table-cell text-muted-foreground whitespace-nowrap">
                            {task.dueDate ? (
                              new Date(task.dueDate).toLocaleDateString(
                                "en-IN",
                                {
                                  day: "2-digit",
                                  month: "short",
                                  year: "numeric",
                                }
                              )
                            ) : (
                              <span className="text-muted-foreground/40">
                                —
                              </span>
                            )}
                          </td>
                          <td className="py-3 px-4">
                            <div className="flex items-center justify-end gap-1">
                              <Button
                                variant="ghost"
                                size="icon"
                                onClick={() => handleView(task.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(task.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(task.id, task.title)}
                                //  disabled={isRowDisabled}
                                disabled
                                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>
  );
}
