"use client";

import { useState, useEffect, useRef } from "react";
import { useRouter } from "next/navigation";
import { Card, CardContent, CardHeader } from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { Skeleton } from "@/components/ui/skeleton";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import { Search, ClipboardList } from "lucide-react";
import { usePagination } from "@/lib/pagination";
import { PaginationBar } from "@/components/common/PaginationBar";
import { useGetTasks } from "../hook/task.hook";
import { TaskListItem } from "..";
import { useTaskSocket } from "@/hooks/useTaskSocket";
import { useAppSelector } from "@/lib/store";

const STATUS_OPTIONS = [
  "ALL",
  "PENDING",
  "IN_PROGRESS",
  "CLIENT_APPROVAL",
  "FILING_PENDING",
  "COMPLETED",
  "CANCELLED",
];

const STATUS_LABELS: Record<string, string> = {
  ALL: "All Statuses",
  PENDING: "Pending",
  IN_PROGRESS: "In Progress",
  CLIENT_APPROVAL: "Client Approval",
  FILING_PENDING: "Filing Pending",
  COMPLETED: "Completed",
  CANCELLED: "Cancelled",
};

const PRIORITY_OPTIONS: { 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, ["tasks"]);
  const { pagination, setPage, setSearch } = usePagination(10);
  const [searchInput, setSearchInput] = useState("");
  const [status, setStatus] = useState("ALL");
  const [priority, setPriority] = useState("ALL");
  const debounceRef = useRef<ReturnType<typeof setTimeout> | null>(null);

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

  useEffect(() => {
    setPage(1);
  }, [status, priority]);

  const { data, isLoading } = useGetTasks({
    ...pagination,
    status: status === "ALL" ? undefined : status,
    priority: priority === "ALL" ? undefined : priority,
  });
  const tasks = data?.data ?? [];
  const meta = data?.meta;

  return (
    <div className="space-y-6">
      {/* Header */}
      <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">My Applications</h2>
            <p className="text-muted-foreground text-sm mt-1">Track and manage your service</p>
          </div>
          {/* <Button
            onClick={() => router.push("/client/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" /> New Task
          </Button> */}
        </CardHeader>
      </Card>

      {/* Main Card */}
      <Card className="border-border bg-card shadow-sm">
        {/* Filter Bar */}
        <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 tasks..."
                className="pl-8 h-9 text-sm bg-background border-border"
              />
            </div>
            <Select value={status} onValueChange={setStatus}>
              <SelectTrigger className="h-9 text-sm w-44 bg-background border-border">
                <SelectValue placeholder="All Status" />
              </SelectTrigger>
              <SelectContent>
                {STATUS_OPTIONS.map((s) => (
                  <SelectItem key={s} value={s}>
                    {STATUS_LABELS[s]}
                  </SelectItem>
                ))}
              </SelectContent>
            </Select>
            <Select value={priority} onValueChange={setPriority}>
              <SelectTrigger className="h-9 text-sm w-36 bg-background border-border">
                <SelectValue placeholder="All Priority" />
              </SelectTrigger>
              <SelectContent>
                {PRIORITY_OPTIONS.map((p) => (
                  <SelectItem key={p.value} value={p.value}>
                    {p.label}
                  </SelectItem>
                ))}
              </SelectContent>
            </Select>
          </div>
        </CardHeader>

        <CardContent className="p-0">
          {isLoading ? (
            <div className="p-4 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 || status !== "ALL" || priority !== "ALL"
                  ? "No tasks match your filters"
                  : "No tasks yet"}
              </p>
              {!pagination.search && status === "ALL" && priority === "ALL" && (
                <p className="text-xs text-muted-foreground/60">
                  Click &quot;New Task&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">Title</th>
                      <th className="py-2.5 px-4">Category</th>
                      <th className="py-2.5 px-4">Service</th>
                      <th className="py-2.5 px-4">Status</th>
                      <th className="py-2.5 px-4">Priority</th>
                      <th className="py-2.5 px-4">CreatedAt</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">
                    {tasks.map((task) => (
                      <TaskListItem key={task.id} task={task} />
                    ))}
                  </tbody>
                </table>
              </div>
              {meta && <PaginationBar meta={meta} onPageChange={setPage} />}
            </>
          )}
        </CardContent>
      </Card>
    </div>
  );
}
