"use client"

import * as React from "react"
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog"
import { Badge } from "@/components/ui/badge"
import {
  Circle,
  Clock,
  CheckCircle2,
  XCircle,
  Calendar,
  User,
  Briefcase,
  Type,
  FileText,
  CalendarDays,
  Layers,
} from "lucide-react"
import { useGetTaskStatusesQuery } from "@/api/rtk"
import {
  TASK_MODULE_TYPE_LABELS,
  TASK_STATUS_FALLBACK_LABELS,
  taskStatusCatalogLabel,
  type Task,
  type TaskStatus,
} from "@/api/rtk/tasks-api"
import { format } from "date-fns"
import { cn } from "@/lib/utils"

interface TaskViewModalProps {
  task: Task | null
  open: boolean
  onClose: () => void
}

const STATUS_VISUAL: Record<
  TaskStatus,
  { icon: React.ElementType; className: string }
> = {
  RECEIVED: { icon: Clock, className: "bg-slate-100 text-slate-700 border-slate-200" },
  IN_PROGRESS: { icon: Clock, className: "bg-blue-50 text-blue-700 border-blue-100" },
  TECHNICAL_REVIEW: { icon: Clock, className: "bg-orange-50 text-orange-700 border-orange-100" },
  APPROVED: { icon: CheckCircle2, className: "bg-emerald-50 text-emerald-700 border-emerald-100" },
  HANDED_TO_AE: { icon: CheckCircle2, className: "bg-emerald-50 text-emerald-700 border-emerald-100" },
  TODO: { icon: Circle, className: "bg-slate-100 text-slate-700 border-slate-200" },
  DONE: { icon: CheckCircle2, className: "bg-emerald-50 text-emerald-700 border-emerald-100" },
  CANCELLED: { icon: XCircle, className: "bg-red-50 text-red-700 border-red-100" },
}

const PRIORITY_CONFIG = {
  LOW: { label: "Low", className: "bg-slate-50 text-slate-600 border-slate-200" },
  MEDIUM: { label: "Medium", className: "bg-amber-50 text-amber-700 border-amber-100" },
  HIGH: { label: "High", className: "bg-orange-50 text-orange-700 border-orange-100" },
  URGENT: { label: "Urgent", className: "bg-red-50 text-red-700 border-red-100" },
}

export function TaskViewModal({ task, open, onClose }: TaskViewModalProps) {
  const { data: taskStatuses = [] } = useGetTaskStatusesQuery()

  if (!task) return null

  const statusVis = STATUS_VISUAL[task.status]
  const statusText = taskStatusCatalogLabel(
    task.status,
    taskStatuses,
    TASK_STATUS_FALLBACK_LABELS,
  )
  const priorityCfg = PRIORITY_CONFIG[task.priority]
  const StatusIcon = statusVis.icon

  return (
    <Dialog open={open} onOpenChange={(v) => !v && onClose()}>
      <DialogContent className="max-w-xl p-0 overflow-hidden border-none shadow-2xl rounded-2xl">
        <div className="bg-slate-50/50 px-6 py-4 border-b border-slate-100">
          <DialogHeader>
            <div className="flex items-center gap-2 mb-1">
              <Badge variant="outline" className={cn("gap-1.5 px-2.5 py-0.5 font-semibold text-[11px] uppercase tracking-wider", statusVis.className)}>
                <StatusIcon className="size-3" />
                {statusText}
              </Badge>
              <Badge variant="outline" className={cn("px-2.5 py-0.5 font-semibold text-[11px] uppercase tracking-wider", priorityCfg.className)}>
                {priorityCfg.label} Priority
              </Badge>
            </div>
            <DialogTitle className="text-xl font-bold font-['Lexend'] text-slate-900 leading-tight">
              {task.title}
            </DialogTitle>
          </DialogHeader>
        </div>

        <div className="p-6 space-y-8">
          {/* Description Section */}
          {task.description && (
            <div className="space-y-2">
              <div className="flex items-center gap-2 text-slate-400">
                <FileText className="size-4" />
                <h4 className="text-[11px] font-bold uppercase tracking-widest">Description</h4>
              </div>
              <p className="text-[14px] text-slate-600 leading-relaxed font-medium bg-slate-50/50 p-4 rounded-xl border border-slate-100">
                {task.description}
              </p>
            </div>
          )}

          {/* Details Grid */}
          <div className="grid grid-cols-2 gap-x-8 gap-y-6">
            <div className="space-y-2">
              <div className="flex items-center gap-2 text-slate-400">
                <User className="size-4" />
                <h4 className="text-[11px] font-bold uppercase tracking-widest">Assigned To</h4>
              </div>
              <div className="flex items-center gap-3">
                <div className="size-8 rounded-full bg-slate-100 flex items-center justify-center border border-slate-200">
                   <span className="text-[10px] font-bold text-slate-500 uppercase">
                     {task.assignedTo?.name?.slice(0, 2) || "??"}
                   </span>
                </div>
                <span className="text-[14px] font-semibold text-slate-700">
                  {task.assignedTo?.name || "Unassigned"}
                </span>
              </div>
            </div>

            <div className="space-y-2">
              <div className="flex items-center gap-2 text-slate-400">
                <CalendarDays className="size-4" />
                <h4 className="text-[11px] font-bold uppercase tracking-widest">Due Date</h4>
              </div>
              <div className="flex items-center gap-3">
                <div className="size-8 rounded-full bg-orange-50 flex items-center justify-center border border-orange-100 text-orange-600">
                   <Calendar className="size-4" />
                </div>
                <span className={cn(
                  "text-[14px] font-semibold",
                  task.dueDate ? "text-slate-700" : "text-slate-400 italic"
                )}>
                  {task.dueDate ? format(new Date(task.dueDate), "MMMM d, yyyy") : "No due date set"}
                </span>
              </div>
            </div>

            <div className="space-y-2">
              <div className="flex items-center gap-2 text-slate-400">
                <Layers className="size-4" />
                <h4 className="text-[11px] font-bold uppercase tracking-widest">Module</h4>
              </div>
              <span className="text-[14px] font-semibold text-slate-700">
                {task.moduleType ? TASK_MODULE_TYPE_LABELS[task.moduleType] : "—"}
              </span>
            </div>

            <div className="space-y-2">
              <div className="flex items-center gap-2 text-slate-400">
                <Briefcase className="size-4" />
                <h4 className="text-[11px] font-bold uppercase tracking-widest">Linked Deal</h4>
              </div>
              <div className="flex items-center gap-3">
                <div className="size-8 rounded-full bg-blue-50 flex items-center justify-center border border-blue-100 text-blue-600">
                   <Briefcase className="size-4" />
                </div>
                <span className={cn(
                  "text-[14px] font-semibold",
                  task.deal ? "text-blue-600" : "text-slate-400 italic"
                )}>
                  {task.deal?.customerName || task.deal?.leadId || "Personal Task"}
                </span>
              </div>
            </div>

            <div className="space-y-2">
              <div className="flex items-center gap-2 text-slate-400">
                <Type className="size-4" />
                <h4 className="text-[11px] font-bold uppercase tracking-widest">Created By</h4>
              </div>
              <div className="flex items-center gap-3">
                <div className="size-8 rounded-full bg-slate-100 flex items-center justify-center border border-slate-200">
                   <span className="text-[10px] font-bold text-slate-500 uppercase">
                     {task.createdBy?.name?.slice(0, 2) || "??"}
                   </span>
                </div>
                <span className="text-[14px] font-semibold text-slate-700">
                  {task.createdBy?.name || "System"}
                </span>
              </div>
            </div>
          </div>
        </div>

        <div className="bg-slate-50 px-6 py-4 border-t border-slate-100 flex justify-end gap-3">
           <span className="text-[10px] text-slate-400 font-medium">
             Created on {format(new Date(task.createdAt), "PPP")}
           </span>
        </div>
      </DialogContent>
    </Dialog>
  )
}
