"use client";

import { useEffect, useState, useCallback, useRef } from "react";
import { use } from "react";
import Link from "next/link";
import { useRouter } from "next/navigation";
import {
  ArrowLeft, CheckCircle2, Search, UserCheck, Wrench, FileCheck,
  XCircle, RefreshCw, Loader2, AlertCircle, Building2, Mail, Phone, Download,
  MapPin, Calendar, Clock, Users, Clipboard, Save, Trash2, FileUp, X, FileText,
} from "lucide-react";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Label } from "@/components/ui/label";
import { Textarea } from "@/components/ui/textarea";
import { Separator } from "@/components/ui/separator";
import {
  Select, SelectContent, SelectItem, SelectTrigger, SelectValue,
} from "@/components/ui/select";
import { cn } from "@/lib/utils";
import { toast } from "sonner";
import { getRequestById, updateRequest, deleteRequest } from "@/services/requests";
import { getInspectorsList, type InspectorListItem } from "@/services/inspectors";
import { uploadToCloudinary } from "@/lib/cloudinary";

// ─── Types ────────────────────────────────────────────────────────────────────

type RequestStatus =
  | "submitted" | "reviewing" | "assigned"
  | "in_progress" | "completed" | "closed" | "cancelled";

interface RequestDocument {
  id: number;
  name: string;
  url: string;
  public_id: string;
  created_at: string;
}

interface TimelineEvent {
  status: RequestStatus;
  notes: string | null;
  actor_type: string;
  timestamp: string;
}

interface InspectionRequest {
  id: number;
  reference: string;
  company_name: string;
  contact_person: string;
  email: string;
  phone?: string;
  location: string;
  inspection_type_id?: number;
  inspection_type: { id: number; heading: string };
  number_of_personnel?: number | null;
  start_date?: string | null;
  job_duration?: string | null;
  equipment_available?: boolean;
  equipment_details?: string | null;
  certification_required?: string[] | null;
  additional_notes?: string | null;
  assigned_inspector?: { id: number; name: string } | null;
  inspectors?: { id: number; name: string }[] | null;
  status: RequestStatus;
  tracking_token?: string;
  timeline: TimelineEvent[];
  documents: RequestDocument[];
  created_at: string;
  updated_at: string;
}

// ─── Status config ────────────────────────────────────────────────────────────

const STATUS_LABELS: Record<RequestStatus, string> = {
  submitted: "Submitted",
  reviewing: "Under Review",
  assigned: "Assigned",
  in_progress: "In Progress",
  completed: "Completed",
  closed: "Closed",
  cancelled: "Cancelled",
};

const STATUS_DESCRIPTIONS: Record<RequestStatus, string> = {
  submitted: "Request received and is in queue.",
  reviewing: "Team is reviewing requirements and sourcing inspectors.",
  assigned: "A qualified inspector has been assigned.",
  in_progress: "Inspection is currently underway at the site.",
  completed: "Inspection complete. Reports available.",
  closed: "This request has been closed.",
  cancelled: "This request was cancelled.",
};

const STATUS_COLORS: Record<RequestStatus, string> = {
  submitted: "bg-blue-100 text-blue-700",
  reviewing: "bg-yellow-100 text-yellow-700",
  assigned: "bg-purple-100 text-purple-700",
  in_progress: "bg-orange-100 text-orange-700",
  completed: "bg-green-100 text-green-700",
  closed: "bg-muted text-muted-foreground",
  cancelled: "bg-red-100 text-red-700",
};

const TIMELINE_ICONS: Record<RequestStatus, React.ElementType> = {
  submitted: CheckCircle2,
  reviewing: Search,
  assigned: UserCheck,
  in_progress: Wrench,
  completed: FileCheck,
  closed: CheckCircle2,
  cancelled: XCircle,
};

const STATUS_ORDER: RequestStatus[] = ["submitted", "reviewing", "assigned", "in_progress", "completed"];
const ALL_STATUSES: RequestStatus[] = [...STATUS_ORDER, "closed", "cancelled"];

// ─── Helpers ──────────────────────────────────────────────────────────────────

function formatDate(iso: string) {
  return new Date(iso).toLocaleDateString("en-GB", { day: "numeric", month: "short", year: "numeric" });
}

function formatDateTime(iso: string) {
  return new Date(iso).toLocaleString("en-GB", {
    day: "numeric", month: "short", year: "numeric",
    hour: "2-digit", minute: "2-digit",
  });
}

function InfoRow({ icon: Icon, label, value, href }: {
  icon: React.ElementType;
  label: string;
  value?: string | null;
  href?: string;
}) {
  if (!value) return null;
  return (
    <div className="flex gap-3 items-start">
      <div className="w-8 h-8 rounded-lg bg-muted flex items-center justify-center shrink-0">
        <Icon className="w-4 h-4 text-muted-foreground" />
      </div>
      <div>
        <p className="text-[11px] uppercase tracking-wider text-muted-foreground font-semibold">{label}</p>
        {href ? (
          <a href={href} className="text-sm text-accent hover:underline mt-0.5 block">{value}</a>
        ) : (
          <p className="text-sm mt-0.5">{value}</p>
        )}
      </div>
    </div>
  );
}

// ─── Timeline ─────────────────────────────────────────────────────────────────

function AdminTimeline({ current, events }: { current: RequestStatus; events: TimelineEvent[] }) {
  const isCancelled = current === "cancelled";
  const steps = isCancelled ? ([...STATUS_ORDER, "cancelled"] as RequestStatus[]) : STATUS_ORDER;
  const currentIdx = steps.indexOf(current);

  return (
    <div className="flex flex-col gap-0">
      {steps.map((step, i) => {
        const Icon = TIMELINE_ICONS[step] ?? CheckCircle2;
        const isDone = i < currentIdx;
        const isActive = i === currentIdx;
        const event = events.find((e) => e.status === step);

        return (
          <div key={step} className="flex gap-4 relative">
            {i < steps.length - 1 && (
              <div className={cn("absolute left-[15px] top-8 w-0.5 h-full -z-0",
                isDone || isActive ? "bg-accent" : "bg-border"
              )} />
            )}
            <div className={cn(
              "relative z-10 w-8 h-8 rounded-full flex items-center justify-center shrink-0 mt-0.5 transition-all",
              isDone ? "bg-accent text-accent-foreground" :
              isActive ? "bg-accent text-accent-foreground ring-4 ring-accent/20" :
              "bg-muted text-muted-foreground"
            )}>
              <Icon className="w-4 h-4" />
            </div>
            <div className="pb-8">
              <p className={cn("font-semibold text-sm",
                isActive || isDone ? "text-foreground" : "text-muted-foreground"
              )}>
                {STATUS_LABELS[step]}
              </p>
              <p className="text-xs text-muted-foreground mt-0.5">{STATUS_DESCRIPTIONS[step]}</p>
              {event ? (
                <div className="mt-1.5 bg-muted rounded-lg px-3 py-2 text-xs text-muted-foreground space-y-0.5">
                  <p className="font-medium text-foreground">{formatDateTime(event.timestamp)}</p>
                  {event.notes && <p className="italic">"{event.notes}"</p>}
                  <p className="uppercase tracking-wider text-[10px] opacity-60">by {event.actor_type}</p>
                </div>
              ) : (
                isActive && (
                  <p className="mt-1 text-xs text-accent font-medium">● Current status</p>
                )
              )}
            </div>
          </div>
        );
      })}
    </div>
  );
}

// ─── Page ─────────────────────────────────────────────────────────────────────

export default function AdminRequestDetailPage({ params }: { params: Promise<{ id: string }> }) {
  const { id } = use(params);
  const router = useRouter();
  const [request, setRequest] = useState<InspectionRequest | null>(null);
  const [loading, setLoading] = useState(true);
  const [notFound, setNotFound] = useState(false);
  const [saving, setSaving] = useState(false);
  const [deleting, setDeleting] = useState(false);
  const [inspectors, setInspectors] = useState<InspectorListItem[]>([]);
  const [downloadingPdf, setDownloadingPdf] = useState(false);

  // Edit state
  const [editStatus, setEditStatus] = useState<string>("");
  const [editInspector, setEditInspector] = useState(""); // stores inspector id as string
  const [editNotes, setEditNotes] = useState("");
  const [reportFiles, setReportFiles] = useState<File[]>([]);
  const [supportingInspectors, setSupportingInspectors] = useState<string[]>([]);
  const [uploadProgress, setUploadProgress] = useState(0);
  const fileInputRef = useRef<HTMLInputElement>(null);

  const fetchRequest = useCallback(async (silent = false) => {
    if (!silent) setLoading(true);
    setNotFound(false);
    try {
      const data = await getRequestById(Number(id));
      const req = (data as any)?.data ?? data as InspectionRequest;
      setRequest(req);
      setEditStatus(req.status);
      setEditInspector(req.assigned_inspector ? String(req.assigned_inspector.id) : "none");
      // initialize supporting inspectors (include primary if present)
      setSupportingInspectors(req.inspectors ? req.inspectors.map((i: any) => String(i.id)) : []);
      setEditNotes("");
      setReportFiles([]);
      setUploadProgress(0);
    } catch (err: any) {
      if (err?.response?.status === 404 || err?.status === 404) setNotFound(true);
      else toast.error("Failed to load request.");
    } finally {
      setLoading(false);
    }
  }, [id]);

  useEffect(() => {
    fetchRequest();
    getInspectorsList().then(setInspectors).catch(() => {});
  }, [fetchRequest]);

  const handleDownloadPDF = async () => {
    if (!request) return;
    setDownloadingPdf(true);
    try {
      const [{ pdf }, { RequestPDF }] = await Promise.all([
        import("@react-pdf/renderer"),
        import("@/components/admin/RequestPDF"),
      ]);
      const logoUrl = `${window.location.origin}/logo-white.png`;
      const blob = await pdf(<RequestPDF request={request} logoUrl={logoUrl} />).toBlob();
      const url = URL.createObjectURL(blob);
      const a = document.createElement("a");
      const name = request.reference ?? `REQ-${request.id}`;
      a.href = url;
      a.download = `${name}.pdf`;
      a.click();
      URL.revokeObjectURL(url);
    } catch (err) {
      toast.error("Failed to generate PDF.");
    } finally {
      setDownloadingPdf(false);
    }
  };

  const handleSave = async () => {
    if (!request) return;
    setSaving(true);
    try {
      const inspectorId = editInspector && editInspector !== "none" ? Number(editInspector) : null;

      let uploaded: { name: string; url: string; public_id: string }[] = [];
      if (editStatus === "completed" && reportFiles.length > 0) {
        uploaded = await Promise.all(
          reportFiles.map((file) =>
            uploadToCloudinary(
              file,
              "raw",
              (pct) => setUploadProgress(pct),
              `/api/requests/${request.id}/documents/upload-signature`,
            ).then((result) => ({ name: file.name, url: result.secure_url, public_id: result.public_id }))
          )
        );
      }

      await updateRequest(request.id, {
        status: editStatus,
        assigned_inspector_id: inspectorId,
        notes: editNotes.trim() || null,
        ...(uploaded.length > 0 ? { documents: uploaded } : {}),
        ...(supportingInspectors.length > 0 ? { inspectors: supportingInspectors.map((s) => Number(s)) } : {}),
      });
      await fetchRequest(true);
      setReportFiles([]);
      setEditNotes("");
      toast.success("Request updated successfully.");
    } catch (err: any) {
      const apiMessage = err?.response?.data?.message;
      toast.error(apiMessage ?? "Failed to update request.");
    } finally {
      setSaving(false);
      setUploadProgress(0);
    }
  };

  const handleDelete = async () => {
    if (!request) return;
    if (!confirm(`Delete request ${request.reference}? This cannot be undone.`)) return;
    setDeleting(true);
    try {
      await deleteRequest(request.id);
      toast.success("Request deleted.");
      router.push("/admin/requests");
    } catch {
      toast.error("Failed to delete request.");
      setDeleting(false);
    }
  };

  // ── Loading ──
  if (loading) {
    return (
      <div className="min-h-screen flex items-center justify-center">
        <Loader2 className="w-8 h-8 animate-spin text-accent" />
      </div>
    );
  }

  // ── Not found ──
  if (notFound || !request) {
    return (
      <div className="min-h-screen flex flex-col items-center justify-center gap-4 text-center px-6">
        <AlertCircle className="w-14 h-14 text-muted-foreground/40" />
        <h2 className="text-xl font-bold">Request Not Found</h2>
        <p className="text-muted-foreground">The request may have been deleted.</p>
        <Link href="/admin/inspection-quotes" className="mt-2 inline-flex items-center gap-2 text-sm text-accent hover:underline">
          <ArrowLeft className="w-4 h-4" /> Back to Requests
        </Link>
      </div>
    );
  }

  const isDirty =
    editStatus !== request.status ||
    editInspector !== (request.assigned_inspector ? String(request.assigned_inspector.id) : "") ||
    editNotes.trim() !== "" ||
    reportFiles.length > 0 ||
    (() => {
      const orig = (request.inspectors ?? []).map((i) => String((i as any).id)).sort().join(",");
      const curr = [...supportingInspectors].sort().join(",");
      return orig !== curr;
    })();

  return (
    <div className="min-h-screen bg-background">
      {/* ── Top bar ── */}
      <div className="bg-primary px-6 pt-8 pb-10">
        <div className="max-w-6xl mx-auto">
          <Link
            href="/admin/inspection-quotes"
            className="inline-flex items-center gap-1.5 text-primary-foreground/60 hover:text-primary-foreground text-sm mb-4 transition-colors"
          >
            <ArrowLeft className="w-4 h-4" /> Back to Requests
          </Link>
          <div className="flex flex-col sm:flex-row sm:items-start sm:justify-between gap-4">
            <div>
              <p className="text-primary-foreground/50 text-xs uppercase tracking-wider mb-1">Inspection Request</p>
              <h1 className="text-2xl font-bold text-primary-foreground">{request.reference}</h1>
              <p className="text-primary-foreground/70 text-sm mt-1">
                {request.company_name} · {request.contact_person}
              </p>
            </div>
            <div className="flex items-center gap-3">
              <span className={`inline-flex items-center px-3 py-1 rounded-full text-xs font-semibold ${STATUS_COLORS[request.status]}`}>
                {STATUS_LABELS[request.status]}
              </span>
              <Button
                variant="outline"
                size="sm"
                className="gap-1.5 bg-white/10 border-white/20 text-primary-foreground hover:bg-white/20 hover:text-primary-foreground"
                onClick={() => fetchRequest(true)}
              >
                <RefreshCw className="w-3.5 h-3.5" /> Refresh
              </Button>
              <Button
                variant="outline"
                size="sm"
                className="gap-1.5 bg-white/10 border-white/20 text-primary-foreground hover:bg-white/20 hover:text-primary-foreground"
                onClick={handleDownloadPDF}
                disabled={downloadingPdf}
              >
                {downloadingPdf ? (
                  <><Loader2 className="w-3.5 h-3.5 animate-spin" /> Generating…</>
                ) : (
                  <><Download className="w-3.5 h-3.5" /> PDF</>
                )}
              </Button>
            </div>
          </div>
        </div>
      </div>

      {/* ── Content ── */}
      <div className="max-w-6xl mx-auto px-6 -mt-4 pb-16">
        <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">

          {/* ── Left col: Details + Timeline ── */}
          <div className="lg:col-span-2 space-y-6">

            {/* Contact card */}
            <div className="bg-card border border-border rounded-xl p-6 shadow-sm">
              <h2 className="font-semibold text-sm mb-4 flex items-center gap-2">
                <Building2 className="w-4 h-4 text-muted-foreground" /> Client Contact
              </h2>
              <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
                <InfoRow icon={Building2} label="Company" value={request.company_name} />
                <InfoRow icon={UserCheck} label="Contact Person" value={request.contact_person} />
                <InfoRow icon={Mail} label="Email" value={request.email} href={`mailto:${request.email}`} />
                {request.phone && (
                  <InfoRow icon={Phone} label="Phone" value={request.phone} href={`tel:${request.phone}`} />
                )}
              </div>
            </div>

            {/* Project details card */}
            <div className="bg-card border border-border rounded-xl p-6 shadow-sm">
              <h2 className="font-semibold text-sm mb-4 flex items-center gap-2">
                <Clipboard className="w-4 h-4 text-muted-foreground" /> Project Details
              </h2>
              <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
                <InfoRow icon={Wrench} label="Inspection Type" value={request.inspection_type?.heading} />
                <InfoRow icon={MapPin} label="Location" value={request.location} />
                {request.start_date && (
                  <InfoRow icon={Calendar} label="Start Date" value={formatDate(request.start_date)} />
                )}
                {request.job_duration && (
                  <InfoRow icon={Clock} label="Job Duration" value={request.job_duration} />
                )}
                {request.number_of_personnel != null && (
                  <InfoRow icon={Users} label="Personnel Required" value={String(request.number_of_personnel)} />
                )}
                <InfoRow
                  icon={Wrench}
                  label="Equipment Available"
                  value={request.equipment_available != null ? (request.equipment_available ? "Yes" : "No") : null}
                />
              </div>
              {request.equipment_details && (
                <div className="mt-4 pt-4 border-t border-border">
                  <p className="text-[11px] uppercase tracking-wider text-muted-foreground font-semibold mb-1">Equipment Details</p>
                  <p className="text-sm">{request.equipment_details}</p>
                </div>
              )}
              {request.certification_required && request.certification_required.length > 0 && (
                <div className="mt-4 pt-4 border-t border-border">
                  <p className="text-[11px] uppercase tracking-wider text-muted-foreground font-semibold mb-2">Certifications Required</p>
                  <div className="flex flex-wrap gap-1.5">
                    {request.certification_required.map((c) => (
                      <Badge key={c} variant="secondary" className="text-xs">{c}</Badge>
                    ))}
                  </div>
                </div>
              )}
              {request.additional_notes && (
                <div className="mt-4 pt-4 border-t border-border">
                  <p className="text-[11px] uppercase tracking-wider text-muted-foreground font-semibold mb-1">Additional Notes</p>
                  <p className="text-sm text-muted-foreground">{request.additional_notes}</p>
                </div>
              )}
              {request.inspectors && request.inspectors.length > 0 && (
                <div className="mt-4 pt-4 border-t border-border">
                  <p className="text-[11px] uppercase tracking-wider text-muted-foreground font-semibold mb-2">Inspectors</p>
                  <div className="flex flex-wrap gap-1.5">
                    {request.inspectors.map((ins: any) => (
                      <Badge key={ins.id} variant="secondary" className="text-xs">{ins.name}</Badge>
                    ))}
                  </div>
                </div>
              )}
            </div>

            {/* Documents card */}
            <div className="bg-card border border-border rounded-xl p-6 shadow-sm">
              <h2 className="font-semibold text-sm mb-4 flex items-center gap-2">
                <FileText className="w-4 h-4 text-muted-foreground" /> Documents
              </h2>
              {request.documents && request.documents.length > 0 ? (
                <ul className="space-y-2">
                  {request.documents.map((doc) => (
                    <li key={doc.id} className="flex items-center gap-3 rounded-lg border border-border bg-muted/30 px-3 py-2.5">
                      <FileText className="w-4 h-4 text-accent shrink-0" />
                      <div className="flex-1 min-w-0">
                        <p className="text-sm font-medium truncate">{doc.name}</p>
                        <p className="text-[11px] text-muted-foreground mt-0.5">{formatDateTime(doc.created_at)}</p>
                      </div>
                      <a
                        href={doc.url}
                        target="_blank"
                        rel="noopener noreferrer"
                        className="shrink-0 text-xs text-accent hover:underline font-medium"
                      >
                        Download
                      </a>
                    </li>
                  ))}
                </ul>
              ) : (
                <div className="flex flex-col items-center justify-center py-8 text-center">
                  <FileText className="w-8 h-8 text-muted-foreground/30 mb-2" />
                  <p className="text-sm text-muted-foreground">No documents uploaded yet.</p>
                </div>
              )}
            </div>

            {/* Timeline card */}
            <div className="bg-card border border-border rounded-xl p-6 shadow-sm">
              <h2 className="font-semibold text-sm mb-6 flex items-center gap-2">
                <CheckCircle2 className="w-4 h-4 text-muted-foreground" /> Progress Timeline
              </h2>
              <AdminTimeline current={request.status} events={request.timeline ?? []} />
            </div>
          </div>

          {/* ── Right col: Manage ── */}
          <div className="space-y-6">

            {/* Manage card */}
            <div className="bg-card border border-border rounded-xl p-6 shadow-sm sticky top-6">
              <h2 className="font-semibold text-sm mb-4">Manage Request</h2>

              <div className="space-y-4">
                <div className="space-y-1.5">
                  <Label className="text-xs font-semibold uppercase tracking-wider text-muted-foreground">Status</Label>
                  <Select
                    value={editStatus}
                    onValueChange={(v) => setEditStatus(v ?? editStatus)}
                    disabled={request.status === "closed" || request.status === "cancelled"}
                  >
                    <SelectTrigger className="h-9 mt-1.5 w-full">
                      <SelectValue />
                    </SelectTrigger>
                    <SelectContent alignItemWithTrigger={false}>
                      {ALL_STATUSES.map((s) => {
                        const currentOrderIdx = STATUS_ORDER.indexOf(request.status);
                        const thisOrderIdx = STATUS_ORDER.indexOf(s);
                        const isPast = thisOrderIdx !== -1 && thisOrderIdx < currentOrderIdx;
                        return (
                          <SelectItem key={s} value={s} disabled={isPast}>
                            {STATUS_LABELS[s]}
                          </SelectItem>
                        );
                      })}
                    </SelectContent>
                  </Select>
                </div>

                <div className="space-y-1.5">
                  <Label className="text-xs font-semibold uppercase tracking-wider text-muted-foreground flex items-center gap-1.5">
                    <UserCheck className="h-3.5 w-3.5" /> Assigned Inspector
                  </Label>
                  <Select
                    value={editInspector}
                    onValueChange={(v) => setEditInspector(v ?? "")}
                  >
                    <SelectTrigger className="h-9 mt-1.5 w-full">
                      <SelectValue placeholder="Select an inspector…">
                        {editInspector === "none" || !editInspector
                          ? "— Unassigned —"
                          : inspectors.find((i) => String(i.id) === editInspector)?.inspector_full_name
                            ?? request.assigned_inspector?.name
                            ?? editInspector}
                      </SelectValue>
                    </SelectTrigger>
                    <SelectContent alignItemWithTrigger={false}>
                      <SelectItem value="none">— Unassigned —</SelectItem>
                      {request.assigned_inspector && !inspectors.some((i) => String(i.id) === String(request.assigned_inspector!.id)) && (
                        <SelectItem value={String(request.assigned_inspector.id)}>{request.assigned_inspector.name}</SelectItem>
                      )}
                      {inspectors.map((ins) => (
                        <SelectItem key={ins.id} value={String(ins.id)}>{ins.inspector_full_name}</SelectItem>
                      ))}
                    </SelectContent>
                  </Select>
                </div>

                <div className="space-y-1.5">
                  <Label className="text-xs font-semibold uppercase tracking-wider text-muted-foreground flex items-center gap-1.5">
                    Supporting Inspectors <span className="text-muted-foreground/50 normal-case tracking-normal font-normal ml-2">(optional)</span>
                  </Label>
                  <select
                    multiple
                    value={supportingInspectors}
                    onChange={(e) => setSupportingInspectors(Array.from(e.target.selectedOptions).map((o) => o.value))}
                    className="h-28 mt-1.5 w-full rounded-lg border border-border bg-muted/0 text-sm p-2"
                  >
                    {inspectors.map((ins) => (
                      <option key={ins.id} value={String(ins.id)}>
                        {ins.inspector_full_name}
                      </option>
                    ))}
                  </select>
                </div>

                <div className="space-y-1.5">
                  <Label className="text-xs font-semibold uppercase tracking-wider text-muted-foreground">
                    Admin Note <span className="text-muted-foreground/50 normal-case tracking-normal font-normal">(for this update)</span>
                  </Label>
                  <Textarea
                    value={editNotes}
                    onChange={(e) => setEditNotes(e.target.value)}
                    placeholder="Optional note for this status update — recorded in the timeline…"
                    rows={4}
                    className="resize-none text-sm"
                  />
                </div>

                {editStatus === "completed" && (
                  <div className="space-y-1.5">
                    <Label className="text-xs font-semibold uppercase tracking-wider text-muted-foreground flex items-center gap-1.5">
                      <FileUp className="h-3.5 w-3.5" /> Upload Documents
                    </Label>
                    <input
                      ref={fileInputRef}
                      type="file"
                      multiple
                      accept=".pdf,.doc,.docx,application/pdf,application/msword,application/vnd.openxmlformats-officedocument.wordprocessingml.document"
                      className="hidden"
                      onChange={(e) => {
                        const picked = Array.from(e.target.files ?? []);
                        setReportFiles((prev) => {
                          const existing = new Set(prev.map((f) => f.name));
                          return [...prev, ...picked.filter((f) => !existing.has(f.name))];
                        });
                        if (fileInputRef.current) fileInputRef.current.value = "";
                      }}
                    />
                    <button
                      type="button"
                      onClick={() => fileInputRef.current?.click()}
                      className="w-full rounded-lg border border-dashed border-border bg-muted/30 hover:bg-muted/60 hover:border-accent/50 transition-colors px-4 py-5 text-center"
                    >
                      <FileUp className="w-5 h-5 mx-auto mb-1.5 text-muted-foreground" />
                      <p className="text-xs text-muted-foreground">Click to add documents</p>
                      <p className="text-[10px] text-muted-foreground/50 mt-0.5">PDF, DOC, DOCX</p>
                    </button>
                    {reportFiles.length > 0 && (
                      <ul className="space-y-1.5">
                        {reportFiles.map((file, i) => (
                          <li key={file.name} className="flex items-center gap-2 rounded-lg border border-border bg-muted/50 px-3 py-2">
                            <FileUp className="w-4 h-4 text-accent shrink-0" />
                            <span className="flex-1 truncate text-xs">{file.name}</span>
                            <button
                              type="button"
                              onClick={() => setReportFiles((prev) => prev.filter((_, j) => j !== i))}
                              className="text-muted-foreground hover:text-destructive transition-colors"
                            >
                              <X className="w-3.5 h-3.5" />
                            </button>
                          </li>
                        ))}
                      </ul>
                    )}
                    {uploadProgress > 0 && uploadProgress < 100 && (
                      <div className="space-y-1">
                        <div className="h-1.5 rounded-full bg-muted overflow-hidden">
                          <div
                            className="h-full bg-accent rounded-full transition-all"
                            style={{ width: `${uploadProgress}%` }}
                          />
                        </div>
                        <p className="text-[10px] text-muted-foreground text-right">{uploadProgress}%</p>
                      </div>
                    )}
                  </div>
                )}

                <Button
                  className="w-full gap-2"
                  onClick={handleSave}
                  disabled={saving || !isDirty}
                >
                  {saving ? (
                    <><Loader2 className="w-4 h-4 animate-spin" /> Saving…</>
                  ) : (
                    <><Save className="w-4 h-4" /> Save Changes</>
                  )}
                </Button>
              </div>

              <Separator className="my-5" />

              {/* Meta info */}
              <div className="space-y-2 text-xs text-muted-foreground">
                <div className="flex justify-between">
                  <span>Reference</span>
                  <span className="font-mono font-semibold text-foreground">{request.reference}</span>
                </div>
                <div className="flex justify-between">
                  <span>Submitted</span>
                  <span>{formatDate(request.created_at)}</span>
                </div>
                <div className="flex justify-between">
                  <span>Last Updated</span>
                  <span>{formatDate(request.updated_at)}</span>
                </div>
                {request.assigned_inspector && (
                  <div className="flex justify-between">
                    <span>Inspector</span>
                    <span className="font-medium text-foreground">{request.assigned_inspector.name}</span>
                  </div>
                )}
              </div>

              <Separator className="my-5" />

              <Button
                variant="outline"
                size="sm"
                className="w-full gap-2 text-destructive border-destructive/30 hover:bg-destructive/5 hover:text-destructive"
                onClick={handleDelete}
                disabled={deleting}
              >
                {deleting ? (
                  <Loader2 className="w-3.5 h-3.5 animate-spin" />
                ) : (
                  <Trash2 className="w-3.5 h-3.5" />
                )}
                Delete Request
              </Button>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}
