"use client";

import { useState } from "react";
import { useParams, useRouter } from "next/navigation";
import { Card, CardContent, CardHeader } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import { Skeleton } from "@/components/ui/skeleton";
import { ArrowLeft, FileText, ExternalLink, CheckCircle2, ClipboardList } from "lucide-react";
import { getStatusVariant } from "@/lib/status-variant";
import { DocumentVerifyDialog } from "./DocumentVerifyDialog";
import { ApproveTaskDialog } from "./ApproveTaskDialog";
import { useGetEmployeeTask } from "../hooks/task.hooks";
import { formatDateTime } from "@/lib/format-date";



export function TaskDetailPage() {
  const router = useRouter();
  const params = useParams<{ id: string }>();
  const taskId = params.id;

  const { data: taskResponse, isLoading } = useGetEmployeeTask(taskId);
  const task = taskResponse?.data;
  const [verifyOpen, setVerifyOpen] = useState(false);
  const [approveOpen, setApproveOpen] = useState(false);

  if (isLoading) {
    return (
      <div className="space-y-4 p-6">
        <Skeleton className="h-8 w-48" />
        <Skeleton className="h-40 w-full rounded-lg" />
        <Skeleton className="h-40 w-full rounded-lg" />
      </div>
    );
  }

  if (!task) {
    return (
      <div className="flex flex-col items-center justify-center py-24 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">Task not found</p>
        <Button variant="outline" size="sm" onClick={() => router.back()} className="mt-2 gap-1">
          <ArrowLeft className="h-3.5 w-3.5" />
          Go back
        </Button>
      </div>
    );
  }

  const docs = task.documents ?? [];
  const canApprove = ["EMPLOYEE_DONE", "REJECTED", "VERIFIED"].includes(task.status);

  return (
    <div className="space-y-6">
      <div className="flex items-center gap-3">
        <button
          onClick={() => router.back()}
          className="text-muted-foreground hover:text-foreground flex items-center gap-1 text-sm"
        >
          <ArrowLeft className="h-4 w-4" /> Back
        </button>
       
      </div>

       <div>
          <h2 className="text-2xl font-bold tracking-tight">{task.title}</h2>
         <p className="text-muted-foreground text-sm mt-0.5">Task details and attached documents</p>
        </div>

     <Card className="border-border bg-card shadow-sm">
  <CardHeader className="border-b border-border px-6 py-4">
    <p className="text-[11px] font-semibold uppercase tracking-wider text-muted-foreground">
      Task Info
    </p>
  </CardHeader>

  <CardContent className="px-6 py-5">
    <div className="grid grid-cols-2 gap-5 sm:grid-cols-3">
      <div>
        <p className="text-[10px] font-semibold uppercase tracking-wider text-muted-foreground">
          Category
        </p>
        <p className="mt-1 text-sm text-foreground">
          {task.service?.category ?? "—"}
        </p>
      </div>

      <div>
        <p className="text-[10px] font-semibold uppercase tracking-wider text-muted-foreground">
          Service
        </p>
        <p className="mt-1 text-sm text-foreground">
          {task.service?.name ?? "—"}
        </p>
      </div>

      <div>
        <p className="text-[10px] font-semibold uppercase tracking-wider text-muted-foreground">
          Status
        </p>
        <Badge
          variant={getStatusVariant(task.status)}
          className="mt-1 text-[10px]"
        >
          {task.status.replace(/_/g, " ")}
        </Badge>
      </div>

      <div>
        <p className="text-[10px] font-semibold uppercase tracking-wider text-muted-foreground">
          Priority
        </p>

        {task.priority ? (
          <Badge
            variant={getStatusVariant(task.priority)}
            className="mt-1 text-[10px]"
          >
            {task.priority}
          </Badge>
        ) : (
          <p className="mt-1 text-sm text-muted-foreground">—</p>
        )}
      </div>

      <div>
        <p className="text-[10px] font-semibold uppercase tracking-wider text-muted-foreground">
          Created At
        </p>
        <p className="mt-1 text-sm text-foreground">
           {formatDateTime(task.createdAt)}
        </p>
      </div>

      <div>
        <p className="text-[10px] font-semibold uppercase tracking-wider text-muted-foreground">
          Note
        </p>
        <p className="mt-1 text-sm text-foreground">
          {task.description ?? "—"}
        </p>
      </div>
    </div>
  </CardContent>
</Card>

      <Card className="border-border bg-card shadow-sm">
        <CardHeader className="border-b border-border py-3 px-5 flex flex-row items-center justify-between">
          <p className="text-[11px] font-semibold text-muted-foreground uppercase tracking-wider">
            Attached Documents
          </p>
          {docs.length > 0 && (
            <Button size="sm" variant="outline" onClick={() => setVerifyOpen(true)} className="h-7 text-[11px]">
              Verify Documents
            </Button>
          )}
        </CardHeader>
        <CardContent className="p-5">
          {docs.length > 0 ? (
            <div className="flex flex-col gap-1.5">
              {docs.map((doc) => (
                <div
                  key={doc.id}
                  className="flex items-center justify-between gap-4 rounded-md border border-border bg-muted/30 px-3 py-2"
                >
                  <div className="flex items-center gap-2 min-w-0">
                    <FileText className="h-3.5 w-3.5 shrink-0 text-muted-foreground" />
                    <span className="text-xs font-medium text-foreground truncate max-w-xs">
                      {doc.serviceDocument?.name ?? doc.fileName}
                    </span>
                    {doc.fileSizeKb && (
                      <span className="text-[10px] text-muted-foreground shrink-0">
                        {doc.fileSizeKb} KB
                      </span>
                    )}
                  </div>
                  <div className="flex items-center gap-2 shrink-0">
                    <Badge
                    variant={getStatusVariant(task.status)}
                    className="text-[10px] whitespace-nowrap"
                  >
                    {task.status.replace(/_/g, " ")}
                  </Badge>
                    <a
                      href={doc.fileUrl}
                      target="_blank"
                      rel="noopener noreferrer"
                      className="inline-flex items-center gap-1 text-[10px] text-blue-600 hover:underline"
                    >
                      View <ExternalLink className="h-3 w-3" />
                    </a>
                  </div>
                </div>
              ))}
            </div>
          ) : (
            <p className="text-xs text-muted-foreground">No documents attached.</p>
          )}
        </CardContent>
      </Card>

      {canApprove && (
        <div className="flex justify-end">
          <Button onClick={() => setApproveOpen(true)} className="gap-1.5">
            <CheckCircle2 className="h-4 w-4" />
            Approve Task
          </Button>
        </div>
      )}

      {verifyOpen && (
        <DocumentVerifyDialog
          taskId={task.id}
          documents={docs}
          open={verifyOpen}
          onClose={() => setVerifyOpen(false)}
        />
      )}

      {approveOpen && (
        <ApproveTaskDialog
          taskId={task.id}
          open={approveOpen}
          onClose={() => setApproveOpen(false)}
        />
      )}
    </div>
  );
}