"use client";

import { Badge } from "@/components/ui/badge";
import { Skeleton } from "@/components/ui/skeleton";
import { ClipboardList, FileText, Flag, Eye, Loader2 } from "lucide-react";
import { Task } from "@/modules/manager/tasks/types";
import { Button } from "@/components/ui/button";
import { useRouter } from "next/navigation";
import { getStatusVariant } from "@/lib/status-variant";
import { useState } from "react";
import { formatDateTime } from "@/lib/format-date";

export function ManagerTaskList({
  tasks,
  isLoading,
  search,
  status,
}: {
  tasks: Task[];
  isLoading: boolean;
  search?: string;
  status: string;
}) {
  const router = useRouter();
   const [navigatingTo, setNavigatingTo] = useState<{id:string; type:"view" } | null>(
      null
    );
const [navigating, setNavigating] = useState<string | null>(null);

const handleView = (id: string) => {
  setNavigating(id);
  router.push(`/manager/tasks/${id}`);
};


  if (isLoading) {
    return (
      <div className="p-4 space-y-3">
        {[1, 2, 3].map((i) => (
          <Skeleton key={i} className="h-12 w-full rounded-lg" />
        ))}
      </div>
    );
  }

  if (tasks.length === 0) {
    return (
      <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">
          {search || status !== "ALL"
            ? "No tasks match your filters"
            : "No tasks yet"}
        </p>
        {!search && status === "ALL" && (
          <p className="text-xs text-muted-foreground/60">
            Tasks will appear here once available.
          </p>
        )}
      </div>
    );
  }

  return (
    <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">Client</th>
            <th className="py-2.5 px-4">Employee</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">Created At</th>
            <th className="py-2.5 px-4">Documents</th>
            <th className="py-2.5 px-4 text-center">Action</th>
          </tr>
        </thead>
        <tbody className="divide-y divide-border text-xs text-foreground">
          {tasks.map((task) => {
             const isViewLoading = navigating === task.id;
            const docs = task.documents ?? [];
            return (
              <tr key={task.id} className="hover:bg-secondary/20 transition-colors">
                <td className="py-3 px-4 font-semibold text-foreground whitespace-nowrap">
                  {task.title}
                </td>
                <td className="py-3 px-4 text-muted-foreground capitalize whitespace-nowrap">
                  <div>{task.client?.name ?? "—"}</div>
                  {task.client?.companyName && (
                    <div className="text-[10px]">{task.client.companyName}</div>
                  )}
                </td>
                <td className="py-3 px-4 text-muted-foreground capitalize whitespace-nowrap">
                  {task.assignedEmployee?.name ?? "—"}
                </td>
                <td className="py-3 px-4 text-muted-foreground whitespace-nowrap">
                  {task.service?.category ?? "—"}
                </td>
                <td className="py-3 px-4 text-muted-foreground">
                  {task.service?.name ?? "—"}
                </td>
                <td className="py-3 px-4">
                  <Badge
                    variant={getStatusVariant(task.status)}
                    className="text-[10px] whitespace-nowrap"
                  >
                    {task.status.replace(/_/g, " ")}
                  </Badge>
                </td>
                <td className="py-3 px-4">
                  {task.priority ? (
                    <Badge variant={getStatusVariant(task.priority)} className="text-[10px]">
                      {task.priority}
                    </Badge>
                  ) : (
                    <span className="text-muted-foreground text-xs">—</span>
                  )}
                </td>
                <td className="py-3 px-4 text-muted-foreground whitespace-nowrap">
                  {formatDateTime(task.createdAt)}
                </td>
                <td className="py-3 px-4">
                  {docs.length > 0 ? (
                    <span className="inline-flex items-center gap-1 text-blue-600 font-medium">
                      <FileText className="h-3.5 w-3.5" />
                      {docs.length} file{docs.length > 1 ? "s" : ""}
                    </span>
                  ) : (
                    <span className="text-muted-foreground">—</span>
                  )}
                </td>
                <td className="py-3 px-4 text-center">
                 <Button
                  variant="ghost"
                  size="icon"
                  onClick={() => handleView(task.id)}
                  disabled={isViewLoading}
                  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>
                </td>
              </tr>
            );
          })}
        </tbody>
      </table>
    </div>
  );
}