"use client";

import { useState } from "react";
import { useRouter } from "next/navigation";
import {
  ArrowLeft,
  CalendarClock,
  Flag,
  Download,
  Trash2,
  Building2,
  FileText,
  Eye,
  Info,
  AlertCircle,
} from "lucide-react";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { Skeleton } from "@/components/ui/skeleton";
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
} from "@/components/ui/alert-dialog";
import { useGetTask, useDeleteTaskDocument } from "../hook/task.hook";
import { TaskDocument } from "../type/task.type";
import { getStatusVariant } from "@/lib/status-variant";
import { formatDateTime } from "@/lib/format-date";

function formatFileSize(kb?: number) {
  if (!kb) return "";
  return kb < 1024 ? `${kb} KB` : `${(kb / 1024).toFixed(1)} MB`;
}

function isImage(type?: string) {
  return !!type?.startsWith("image/");
}

function getFileLabel(type?: string) {
  if (type === "application/pdf") return "PDF";
  if (type?.includes("word")) return "DOC";
  if (type?.includes("spreadsheet") || type?.includes("excel")) return "XLS";
  return "FILE";
}

export function TaskDetailView({ taskId }: { taskId: string }) {
  const router = useRouter();
  const { data, isLoading } = useGetTask(taskId);
  const task = data?.data;

  const [deleteTarget, setDeleteTarget] = useState<TaskDocument | null>(null);
  const deleteDoc = useDeleteTaskDocument(taskId, () => setDeleteTarget(null));

  if (isLoading) {
    return (
      <div className="space-y-4">
        <Skeleton className="h-8 w-56" />
        <div className="flex flex-col md:flex-row gap-5">
          <Skeleton className="h-40 w-48 rounded-xl" />
          <Skeleton className="h-52 w-full rounded-xl" />
        </div>
      </div>
    );
  }

  if (!task) {
    return (
      <div className="py-16 text-center space-y-3">
        <p className="text-sm font-semibold text-muted-foreground">
          Task not found
        </p>
        <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>
    );
  }

  const documents = task.documents ?? [];
  const initials = task.title.trim().slice(0, 2).toUpperCase();

  return (
    <div className="space-y-4">
      <Button
        variant="ghost"
        size="sm"
        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>

      <p className="text-muted-foreground text-sm">
        View task information and documents
      </p>

      <Card className="w-full">
        <CardHeader>
          <CardTitle className="flex items-center gap-2">
            <Building2 className="h-4 w-4 text-primary" />
            Task Info
          </CardTitle>
        </CardHeader>
        <CardContent>
          <div className="divide-y divide-border border rounded-lg">
            {[
              {
                label: "Title",
                value: <span className="font-semibold">{task.title}</span>,
              },
              { label: "Service", value: task.service?.name ?? "—" },
              task.service?.category
                ? { label: "Category", value: task.service.category }
                : null,
              {
                label: "Status",
                value: (
                  // <Badge variant="outline" className={`text-[10px] ${STATUS_STYLES[task.status] ?? ""}`}>
                  //   {task.status.replace(/_/g, " ")}
                  // </Badge>
                  <Badge
                    variant={getStatusVariant(task.status)}
                    className="text-[10px]"
                  >
                    {task.status.replace(/_/g, " ")}
                  </Badge>
                ),
              },
              task.priority
                ? {
                    label: "Priority",
                    value: (
                      <Badge
                        variant={getStatusVariant(task.status)}
                        className="text-[10px]"
                      >
                        {task.priority.replace(/_/g, " ")}
                      </Badge>
                    ),
                  }
                : null,
              task.dueDate
                ? {
                    label: "Due Date",
                    value: (
                      <span className="flex items-center gap-1">
                        <CalendarClock className="h-3.5 w-3.5" />
                        {new Date(task.dueDate).toLocaleDateString("en-IN", {
                          day: "2-digit",
                          month: "short",
                          year: "numeric",
                        })}
                      </span>
                    ),
                  }
                : null,
              {
                label: "Created",
                value: formatDateTime(task.createdAt),
              },
            ]
              .filter(Boolean)
              .map(({ label, value }: any) => (
                <div
                  key={label}
                  className="flex items-center justify-between px-4 py-3"
                >
                  <span className="text-xs font-semibold text-muted-foreground uppercase tracking-wide">
                    {label}
                  </span>
                  <span className="text-sm text-foreground">{value}</span>
                </div>
              ))}
          </div>

          {task.description && (
            <div className="rounded-lg bg-muted/40 px-4 py-3 mt-4">
              <p className="text-xs text-muted-foreground mb-1 font-medium uppercase tracking-wide">
                Note
              </p>
              <p className="text-sm text-foreground whitespace-pre-wrap">
                {task.description}
              </p>
            </div>
          )}
        </CardContent>
      </Card>

      {/* Documents */}
      <Card className="w-full">
        <CardHeader className="pb-3">
          <CardTitle className="text-base">
            Documents
            {documents.length > 0 && (
              <span className="ml-2 text-xs font-normal text-muted-foreground">
                ({documents.length})
              </span>
            )}
          </CardTitle>
        </CardHeader>
        <CardContent>
          {documents.length === 0 ? (
            <div className="flex flex-col items-center gap-2 rounded-xl border border-dashed p-8 text-center">
              <FileText className="w-8 h-8 text-muted-foreground/50" />
              <p className="text-sm font-medium text-muted-foreground">
                No documents uploaded
              </p>
            </div>
          ) : (
            <div className="grid grid-cols-2 sm:grid-cols-3 gap-3">
              {documents.map((doc) => {
                const isRejected = doc.status === "REJECTED";

                return (
                  <div
                    key={doc.id}
                    className="group relative rounded-xl border overflow-hidden hover:shadow-sm transition-shadow"
                  >
                    <a
                      href={doc.fileUrl}
                      target="_blank"
                      rel="noopener noreferrer"
                      className="block relative"
                    >
                      {isImage(doc.fileType) ? (
                        <div className="aspect-square bg-muted overflow-hidden">
                          <img
                            src={doc.fileUrl}
                            alt={doc.fileName}
                            className="w-full h-full object-cover"
                          />
                        </div>
                      ) : (
                        <div className="aspect-square bg-muted flex flex-col items-center justify-center gap-1.5">
                          <div className="rounded-md bg-primary/10 px-2 py-1 text-[11px] font-bold text-primary">
                            {getFileLabel(doc.fileType)}
                          </div>
                          <FileText className="h-6 w-6 text-muted-foreground/60" />
                        </div>
                      )}

                      {/* Status badge overlay on thumbnail */}
                      <Badge
                        variant={getStatusVariant(doc.status)}
                        className="absolute top-1.5 left-1.5 text-[9px] px-1.5 py-0 h-5 backdrop-blur-sm"
                      >
                        {doc.status}
                      </Badge>

                      <div className="absolute inset-0 bg-black/0 group-hover:bg-black/20 transition-colors flex items-center justify-center">
                        <Eye className="h-5 w-5 text-white opacity-0 group-hover:opacity-100 transition-opacity" />
                      </div>
                    </a>

                    <div className="p-2 space-y-1">
                      <p
                        className="text-xs font-medium truncate"
                        title={doc.fileName}
                      >
                        {doc.fileName}
                      </p>
                      <p className="text-[11px] text-muted-foreground truncate">
                        {formatFileSize(doc.fileSizeKb)}
                        {doc.serviceDocument?.name &&
                          ` · ${doc.serviceDocument.name}`}
                      </p>

                      {isRejected && doc.aiVerificationNotes && (
                        <div className="flex items-start gap-1 rounded-md bg-red-50 border border-red-100 px-1.5 py-1 mt-1">
                          <span className="text-[10px] font-semibold text-red-900 leading-snug">
                            Note:
                          </span>

                          <p className="text-[10px] text-red-700 leading-snug line-clamp-2">
                            {doc.aiVerificationNotes}
                          </p>
                        </div>
                      )}
                    </div>

                    <div className="absolute top-1.5 right-1.5 flex items-center gap-1 opacity-0 group-hover:opacity-100 transition-opacity">
                      <Button
                        size="icon"
                        variant="secondary"
                        className="h-6 w-6"
                        asChild
                        aria-label="Download"
                      >
                        <a
                          href={doc.fileUrl}
                          target="_blank"
                          rel="noopener noreferrer"
                          download
                        >
                          <Download className="h-3 w-3" />
                        </a>
                      </Button>
                      <Button
                        size="icon"
                        variant="secondary"
                        className="h-6 w-6 hover:text-destructive"
                        onClick={(e) => {
                          e.preventDefault();
                          setDeleteTarget(doc);
                        }}
                        aria-label="Delete document"
                      >
                        <Trash2 className="h-3 w-3" />
                      </Button>
                    </div>
                  </div>
                );
              })}
            </div>
          )}
        </CardContent>
      </Card>

      {/* Delete Document Dialog */}
      <AlertDialog
        open={!!deleteTarget}
        onOpenChange={(open) => !open && setDeleteTarget(null)}
      >
        <AlertDialogContent>
          <AlertDialogHeader>
            <AlertDialogTitle>Delete Document</AlertDialogTitle>
            <AlertDialogDescription>
              Are you sure you want to delete{" "}
              <span className="font-medium">{deleteTarget?.fileName}</span>?
              This action cannot be undone.
            </AlertDialogDescription>
          </AlertDialogHeader>
          <AlertDialogFooter>
            <AlertDialogCancel disabled={deleteDoc.isPending}>
              Cancel
            </AlertDialogCancel>
            <AlertDialogAction
              onClick={() => deleteTarget && deleteDoc.mutate(deleteTarget.id)}
              disabled={deleteDoc.isPending}
              className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
            >
              {deleteDoc.isPending ? "Deleting..." : "Delete"}
            </AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>
    </div>
  );
}
