"use client";
import { useEffect, useState, useCallback } from "react";
import { use } from "react";
import Link from "next/link";
import {
  CheckCircle2,
  Loader2,
  RefreshCw,
  Search,
  XCircle,
  AlertCircle,
  UserCheck,
  Wrench,
  FileCheck,
  Download,
} from "lucide-react";
import { cn } from "@/lib/utils";
import { trackRequestByToken } from "@/services/requests";

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

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

interface StatusConfig {
  label: string;
  description: string;
  icon: React.ElementType;
  color: string;
  bg: string;
}

const STATUS_CONFIG: Record<RequestStatus, StatusConfig> = {
  submitted: {
    label: "Submitted",
    description: "Your request has been received and is in our queue.",
    icon: CheckCircle2,
    color: "text-blue-600",
    bg: "bg-blue-100",
  },
  reviewing: {
    label: "Under Review",
    description: "Our team is reviewing your requirements and identifying suitable inspectors.",
    icon: Search,
    color: "text-yellow-600",
    bg: "bg-yellow-100",
  },
  assigned: {
    label: "Inspector Assigned",
    description: "A qualified inspector has been assigned to your request.",
    icon: UserCheck,
    color: "text-purple-600",
    bg: "bg-purple-100",
  },
  in_progress: {
    label: "In Progress",
    description: "The inspection is currently underway at your site.",
    icon: Wrench,
    color: "text-orange-600",
    bg: "bg-orange-100",
  },
  completed: {
    label: "Completed",
    description: "The inspection has been completed. Reports are available below.",
    icon: FileCheck,
    color: "text-green-600",
    bg: "bg-green-100",
  },
  closed: {
    label: "Closed",
    description: "This request has been closed.",
    icon: CheckCircle2,
    color: "text-muted-foreground",
    bg: "bg-muted",
  },
  cancelled: {
    label: "Cancelled",
    description: "This request was cancelled.",
    icon: XCircle,
    color: "text-destructive",
    bg: "bg-destructive/10",
  },
};

const STATUS_ORDER: RequestStatus[] = [
  "submitted",
  "reviewing",
  "assigned",
  "in_progress",
  "completed",
];

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

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

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

interface TrackedRequest {
  id: number;
  reference: string;
  company_name: string;
  inspection_type: string;
  inspection_type_id: number;
  location: string;
  number_of_personnel: number | null;
  start_date: string | null;
  status: RequestStatus;
  assigned_inspector: { name: string; specialization: string } | null;
  inspectors?: { name: string; specialization: string }[];
  timeline: TimelineEvent[];
  documents: RequestDocument[];
  created_at: string;
  updated_at: string;
}

// ─── Sub-components ──────────────────────────────────────────────────────────

const StatusBadge = ({ status }: { status: RequestStatus }) => {
  const cfg = STATUS_CONFIG[status] ?? STATUS_CONFIG.submitted;
  const Icon = cfg.icon;
  return (
    <span className={cn("inline-flex items-center gap-1.5 px-3 py-1.5 rounded-full text-sm font-semibold", cfg.bg, cfg.color)}>
      <Icon className="w-4 h-4" />
      {cfg.label}
    </span>
  );
};

const Timeline = ({ 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="relative">
      <div className="flex flex-col gap-0">
        {steps.map((step, i) => {
          const cfg = STATUS_CONFIG[step];
          const Icon = cfg.icon;
          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">
              {/* Line */}
              {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")} />
              )}
              {/* Circle */}
              <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>
              {/* Content */}
              <div className="pb-8">
                <p className={cn("font-semibold text-sm", isActive ? "text-foreground" : isDone ? "text-foreground" : "text-muted-foreground")}>
                  {cfg.label}
                </p>
                <p className="text-xs text-muted-foreground mt-0.5">{cfg.description}</p>
                {event && (
                  <p className="text-xs text-muted-foreground mt-1">
                    {new Date(event.timestamp).toLocaleString()}
                    {event.notes && <> — <span className="italic">{event.notes}</span></>}
                  </p>
                )}
              </div>
            </div>
          );
        })}
      </div>
    </div>
  );
};

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

export default function TrackRequestPage({ params }: { params: Promise<{ token: string }> }) {
  const { token } = use(params);
  const [request, setRequest] = useState<TrackedRequest | null>(null);
  const [loading, setLoading] = useState(true);
  const [notFound, setNotFound] = useState(false);
  const [refreshing, setRefreshing] = useState(false);

  const fetchRequest = useCallback(async (isRefresh = false) => {
    if (isRefresh) setRefreshing(true);
    else setLoading(true);
    setNotFound(false);
    try {
      const res = await trackRequestByToken(token);
      setRequest(res.data as TrackedRequest);
    } catch (err: any) {
      if (err?.response?.status === 404 || err?.status === 404) {
        setNotFound(true);
      }
    } finally {
      setLoading(false);
      setRefreshing(false);
    }
  }, [token]);

  useEffect(() => {
    fetchRequest();
  }, [fetchRequest]);

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

  if (notFound || !request) {
    return (
      <div className="min-h-screen bg-primary flex flex-col items-center justify-center gap-4 text-center px-6">
        <AlertCircle className="w-14 h-14 text-primary-foreground/30" />
        <h2 className="text-xl font-bold text-primary-foreground">Request Not Found</h2>
        <p className="text-primary-foreground/60 max-w-sm">
          The tracking link may be invalid or expired. Please check the link in your confirmation email.
        </p>
        <Link href="/" className="mt-2 inline-flex items-center justify-center rounded-md border border-white/20 bg-white/10 px-4 py-2 text-sm font-medium text-primary-foreground hover:bg-white/20 transition-colors">
          Back to Home
        </Link>
      </div>
    );
  }

  return (
    <div className="bg-background min-h-screen">
      {/* Hero bar */}
      <div className="bg-primary pt-30 pb-10 px-6">
        <div className="max-w-3xl mx-auto">
          <p className="text-primary-foreground/60 text-sm mb-1">Inspection Request Tracking</p>
          <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-3">
            <div>
              <h1 className="text-2xl font-bold text-primary-foreground">Ref: {request.reference}</h1>
              <p className="text-primary-foreground/70 text-sm mt-1">{request.company_name} · {request.inspection_type}</p>
            </div>
            <StatusBadge status={request.status} />
          </div>
        </div>
      </div>

      <div className="max-w-3xl mx-auto px-6 py-10 space-y-10">
        {/* Details card */}
        <div className="bg-card border border-border rounded-xl p-6 shadow-sm">
          <h2 className="font-semibold text-base mb-4">Request Details</h2>
          <div className="grid grid-cols-1 sm:grid-cols-2 gap-4 text-sm">
            <div>
              <p className="text-muted-foreground text-xs uppercase tracking-wider">Location</p>
              <p className="font-medium mt-0.5">{request.location || "—"}</p>
            </div>
            <div>
              <p className="text-muted-foreground text-xs uppercase tracking-wider">Inspection Type</p>
              <p className="font-medium mt-0.5">{request.inspection_type}</p>
            </div>
            <div>
              <p className="text-muted-foreground text-xs uppercase tracking-wider">Personnel</p>
              <p className="font-medium mt-0.5">{request.number_of_personnel ?? "—"}</p>
            </div>
            <div>
              <p className="text-muted-foreground text-xs uppercase tracking-wider">Start Date</p>
              <p className="font-medium mt-0.5">{request.start_date ? new Date(request.start_date).toLocaleDateString() : "—"}</p>
            </div>
            <div>
              <p className="text-muted-foreground text-xs uppercase tracking-wider">Submitted</p>
              <p className="font-medium mt-0.5">{new Date(request.created_at).toLocaleDateString()}</p>
            </div>
            <div>
              <p className="text-muted-foreground text-xs uppercase tracking-wider">Last Updated</p>
              <p className="font-medium mt-0.5">{new Date(request.updated_at).toLocaleDateString()}</p>
            </div>
          </div>

          {/* Assigned inspector */}
          {request.assigned_inspector && (
            <div className="mt-5 pt-5 border-t border-border">
              <p className="text-muted-foreground text-xs uppercase tracking-wider mb-2">Assigned Inspector</p>
              <div className="flex items-center gap-3">
                <div className="w-10 h-10 rounded-full bg-accent/10 flex items-center justify-center">
                  <UserCheck className="w-5 h-5 text-accent" />
                </div>
                <div>
                  <p className="font-semibold text-sm">{request.assigned_inspector.name}</p>
                  <p className="text-xs text-muted-foreground">{request.assigned_inspector.specialization}</p>
                </div>
              </div>
            </div>
          )}

          {request.inspectors && request.inspectors.length > 0 && (
            <div className="mt-4 pt-4 border-t border-border">
              <p className="text-muted-foreground text-xs uppercase tracking-wider mb-2">Inspectors</p>
              <div className="flex gap-3">
                {request.inspectors.map((ins, idx) => (
                  <div key={idx} className="flex border p-2 rounded-lg items-center gap-3">
                    <div className="w-8 h-8 rounded-full bg-accent/10 flex items-center justify-center">
                      <UserCheck className="w-4 h-4 text-accent" />
                    </div>
                    <div>
                      <p className="font-medium text-sm">{ins.name}</p>
                      <p className="text-xs text-muted-foreground">{ins.specialization}</p>
                    </div>
                  </div>
                ))}
              </div>
            </div>
          )}
        </div>

        {/* Timeline */}
        <div className="bg-card border border-border rounded-xl p-6 shadow-sm">
          <div className="flex items-center justify-between mb-6">
            <h2 className="font-semibold text-base">Progress Timeline</h2>
            <button
              onClick={() => fetchRequest(true)}
              disabled={refreshing}
              className="flex items-center gap-1.5 text-xs text-muted-foreground hover:text-foreground transition-colors"
            >
              <RefreshCw className={cn("w-3.5 h-3.5", refreshing && "animate-spin")} />
              Refresh
            </button>
          </div>
          <Timeline current={request.status} events={request.timeline ?? []} />
        </div>

        {/* Documents — shown when completed and documents exist */}
        {request.status === "completed" && request.documents?.length > 0 && (
          <div className="bg-green-50 border border-green-200 rounded-xl p-6 shadow-sm">
            <div className="flex items-center gap-3 mb-4">
              <div className="w-11 h-11 rounded-lg bg-green-100 flex items-center justify-center shrink-0">
                <FileCheck className="w-5 h-5 text-green-700" />
              </div>
              <div>
                <p className="font-semibold text-green-900">Inspection Documents Ready</p>
                <p className="text-sm text-green-700 mt-0.5">
                  {request.documents.length} document{request.documents.length !== 1 ? "s" : ""} available for download.
                </p>
              </div>
            </div>
            <div className="flex flex-col gap-2">
              {request.documents.map((doc) => (
                <div key={doc.id} className="flex items-center justify-between gap-3 bg-white border border-green-100 rounded-lg px-4 py-3">
                  <div className="flex items-center gap-2 min-w-0">
                    <Download className="w-4 h-4 text-green-700 shrink-0" />
                    <span className="text-sm font-medium text-green-900 truncate">{doc.name}</span>
                  </div>
                  <a
                    href={doc.url}
                    target="_blank"
                    rel="noopener noreferrer"
                    download
                    className="inline-flex items-center gap-1.5 shrink-0 bg-green-700 hover:bg-green-800 text-white text-xs font-semibold px-3 py-1.5 rounded-lg transition-colors"
                  >
                    <Download className="w-3.5 h-3.5" />
                    Download
                  </a>
                </div>
              ))}
            </div>
          </div>
        )}

        {/* Footer */}
        <p className="text-xs text-center text-muted-foreground pb-6">
          Questions about your request?{" "}
          <a href="mailto:hello@petro-base.com" className="underline text-accent">Contact us</a>
        </p>
      </div>
    </div>
  );
}
