"use client";

import { useState } from "react";
import { useRouter } from "next/navigation";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Pencil, Trash2, Eye, Flag, Loader2, CreditCard } from "lucide-react";

import { Task } from "../type/task.type";
import { getStatusVariant } from "@/lib/status-variant";
import { useConfirmDelete } from "@/components/common/useConfirmDelete";
import { useDeleteTask } from "../hook/task.hook";
import { useCreateCheckoutSession } from "../../payment/hook/payment.hook";
import { formatDateTime } from "@/lib/format-date";

export function TaskListItem({ task }: { task: Task }) {
  const router = useRouter();
  const [deleteOpen, setDeleteOpen] = useState(false);
  const [navigatingTo, setNavigatingTo] = useState<"view" | "edit" | null>(
    null
  );
  const { mutate: checkout, isPending: checkoutPending } =
    useCreateCheckoutSession();

  const showPayNow =
    task.status === "COMPLETED" &&
    task.invoice &&
    task.invoice.status !== "PAID" &&
    task.invoice.status !== "CANCELLED";

  const handleView = () => {
    setNavigatingTo("view");
    router.push(`/client/tasks/${task.id}`);
  };

  const handleEdit = () => {
    setNavigatingTo("edit");
    router.push(`/client/tasks/${task.id}/edit`);
  };

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

  return (
    <>
      <tr className="hover:bg-secondary/20 transition-colors">
        {/* Title */}
        <td className="py-3 px-4 font-semibold text-foreground whitespace-nowrap">
          {task.title}
        </td>

        <td className="py-3 px-4 font-semibold text-foreground whitespace-nowrap">
          {task.service?.category}
        </td>

        {/* Service */}
        <td className="py-3 px-4 text-muted-foreground">
          <span className="text-xs">{task.service?.name ?? "—"}</span>
        </td>

        {/* Status */}
        <td className="py-3 px-4">
          <Badge
            variant={getStatusVariant(task.status)}
            className="text-[10px] whitespace-nowrap"
          >
            {task.status.replace(/_/g, " ")}
          </Badge>
        </td>

        {/* Priority */}
        <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>

        {/* Due Date */}
        <td className="py-3 px-4 text-muted-foreground whitespace-nowrap">
          {task.createdAt ? (
            <div className="text-xs">{formatDateTime(task.createdAt)}</div>
          ) : (
            <span className="text-xs">—</span>
          )}
        </td>

        {/* Actions */}
        <td className="py-3 px-4 whitespace-nowrap min-w-[190px]">
          <div className="flex justify-end items-center gap-1 flex-nowrap">
            {showPayNow && (
              <Button
                variant="success"
                onClick={() => checkout(task.invoice!.id)}
                disabled={checkoutPending || navigatingTo !== null}
                className="h-auto min-h-0 px-2.5 py-1 rounded-md text-[10px] font-medium leading-none whitespace-nowrap shrink-0"
              >
                {checkoutPending ? (
                  <Loader2 className="h-3 w-3 animate-spin" />
                ) : (
                  "Pay Now"
                )}
              </Button>
            )}

            <Button
              variant="ghost"
              size="icon"
              onClick={handleView}
              disabled={navigatingTo !== null}
              className="h-7 w-7 shrink-0 rounded-lg text-muted-foreground hover:text-primary hover:bg-primary/10"
              title="View"
            >
              {navigatingTo === "view" ? (
                <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}
              disabled={navigatingTo !== null}
              className="h-7 w-7 shrink-0 rounded-lg text-muted-foreground hover:text-amber-600 hover:bg-amber-500/10"
              title="Edit"
            >
              {navigatingTo === "edit" ? (
                <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={navigatingTo !== null}
              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>

      <DeleteDialog />
    </>
  );
}
