"use client";

import { useState } from "react";
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogFooter,
  DialogDescription,
} from "@/components/ui/dialog";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import { FileText, ExternalLink, CheckCircle2, Flag } from "lucide-react";
import { Task } from "@/modules/client/task/type/task.type";
import { getStatusVariant } from "@/lib/status-variant";
import { DocumentVerifyDialog } from "./DocumentVerifyDialog";
import { ApproveTaskDialog } from "./ApproveTaskDialog";

interface TaskViewDialogProps {
  task: Task;
  open: boolean;
  onClose: () => void;
}

export function TaskViewDialog({ task, open, onClose }: TaskViewDialogProps) {
  const [verifyOpen, setVerifyOpen] = useState(false);
  const [approveOpen, setApproveOpen] = useState(false);

  const docs = task.documents ?? [];
  const canApprove = ["EMPLOYEE_DONE", "REJECTED", "VERIFIED"].includes(task.status);

  return (
    <>
      <Dialog open={open} onOpenChange={(isOpen) => { if (!isOpen) onClose(); }}>
        <DialogContent className="max-w-xl">
          <DialogHeader>
            <DialogTitle className="text-base">{task.title}</DialogTitle>
            <DialogDescription className="text-xs">
              Task details and attached documents.
            </DialogDescription>
          </DialogHeader>

          <div className="space-y-4">
            {/* Task info grid */}
            <div className="grid grid-cols-2 gap-3 rounded-lg border border-border bg-muted/30 p-3">
              <div>
                <p className="text-[10px] font-semibold text-muted-foreground uppercase tracking-wider">
                  Category
                </p>
                <p className="text-xs text-foreground mt-0.5">
                  {task.service?.category ?? "—"}
                </p>
              </div>
              <div>
                <p className="text-[10px] font-semibold text-muted-foreground uppercase tracking-wider">
                  Service
                </p>
                <p className="text-xs text-foreground mt-0.5">
                  {task.service?.name ?? "—"}
                </p>
              </div>
              <div>
                <p className="text-[10px] font-semibold text-muted-foreground uppercase tracking-wider">
                  Status
                </p>
                <Badge
                  variant={getStatusVariant(task.status)}
                  className="text-[10px] whitespace-nowrap mt-1"
                >
                  {task.status.replace(/_/g, " ")}
                </Badge>
              </div>
              <div>
                <p className="text-[10px] font-semibold text-muted-foreground uppercase tracking-wider">
                  Priority
                </p>
                {task.priority ? (
                  <Badge variant={getStatusVariant(task.priority)} className="text-[10px] mt-1">
                    <Flag className="h-3 w-3 mr-1" />
                    {task.priority}
                  </Badge>
                ) : (
                  <p className="text-xs text-muted-foreground mt-0.5">—</p>
                )}
              </div>
              <div>
                <p className="text-[10px] font-semibold text-muted-foreground uppercase tracking-wider">
                  Created At
                </p>
                <p className="text-xs text-foreground mt-0.5">
                  {task.createdAt
                    ? new Date(task.createdAt).toLocaleDateString("en-IN", {
                        day: "2-digit",
                        month: "short",
                        year: "numeric",
                      })
                    : "—"}
                </p>
              </div>
            </div>

            {/* Documents */}
            <div>
              <p className="text-[11px] font-semibold text-muted-foreground uppercase tracking-wider mb-2">
                Attached Documents
              </p>
              {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-card 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>
              )}
            </div>
          </div>

          <DialogFooter className="gap-2 sm:gap-2">
            {docs.length > 0 && (
              <Button size="sm" variant="outline" onClick={() => setVerifyOpen(true)}>
                Verify Documents
              </Button>
            )}
            {canApprove && (
              <Button size="sm" onClick={() => setApproveOpen(true)} className="gap-1">
                <CheckCircle2 className="h-3.5 w-3.5" />
                Approve
              </Button>
            )}
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {verifyOpen && (
        <DocumentVerifyDialog
          taskId={task.id}
          documents={docs}
          open={verifyOpen}
          onClose={() => setVerifyOpen(false)}
        />
      )}

      {approveOpen && (
        <ApproveTaskDialog
          taskId={task.id}
          open={approveOpen}
          onClose={() => setApproveOpen(false)}
        />
      )}
    </>
  );
}