"use client";

import { useState, useEffect, useRef } from "react";
import { Card, CardContent, CardHeader } from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import { Search } from "lucide-react";
import { usePagination } from "@/lib/pagination";
import { PaginationBar } from "@/components/common/PaginationBar";
import { ManagerTaskList } from "./ManagerTaskList";
import { useGetManagerTasks } from "../hooks/task.hooks";
import { useTaskSocket } from "@/hooks/useTaskSocket";
import { useAppSelector } from "@/lib/store";

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

const STATUS_LABELS: Record<string, string> = {
  ALL: "All Statuses",
  PENDING: "Pending",
  IN_PROGRESS: "In Progress",
  EMPLOYEE_DONE: "Employee Done",
  MANAGER_APPROVAL: "Manager Approval",
  CLIENT_APPROVAL: "Client Approval",
  FILING_PENDING: "Filing Pending",
  COMPLETED: "Completed",
  REJECTED: "Rejected",
  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 { pagination, setPage, setSearch } = usePagination(10);
  const orgId = useAppSelector((s) => s.auth.user?.organizationId);
  useTaskSocket(orgId, ["manager-tasks"]);
  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 value = searchInput.trim();
      if (value.length === 0 || value.length >= 3) {
        setSearch(value);
      }
    }, 600);

    return () => {
      if (debounceRef.current) {
        clearTimeout(debounceRef.current);
      }
    };
  }, [searchInput, setSearch]);

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

  const { data, isLoading } = useGetManagerTasks({
    ...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">
      <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 Tasks
            </h2>
            <p className="text-muted-foreground text-sm mt-1">
              Track and manage tasks assigned to you.
            </p>
          </div>
        </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 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={(event) => setSearchInput(event.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((option) => (
                  <SelectItem key={option} value={option}>
                    {STATUS_LABELS[option]}
                  </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">
          <ManagerTaskList
            tasks={tasks}
            isLoading={isLoading}
            search={pagination.search}
            status={status}
          />
          {meta && <PaginationBar meta={meta} onPageChange={setPage} />}
        </CardContent>
      </Card>
    </div>
  );
}
