"use client";

import React, { useState, useEffect, use } from "react";
import { useRouter } from "next/navigation";
import Link from "next/link";
import { API_BASE_URL } from "@/utils/apiHelper";
import {
  FaChevronRight,
  FaBox,
  FaTruck,
  FaCheckCircle,
  FaClock,
  FaExternalLinkAlt,
  FaFileDownload,
  FaMapMarkerAlt,
  FaCalendarAlt,
  FaUser,
  FaWallet,
} from "react-icons/fa";

/* ─── Types ──────────────────────────────────────────────── */
type StatusHistory = {
  status: string;
  timestamp: string;
  note?: string;
};

type DispatchDetails = {
  courier?: string;
  awb?: string;
  dispatch_date?: string;
  expected_delivery?: string;
} | null;

type TrackOrder = {
  order_id: string;
  status: string;
  total_items: number;
  total_price: number;
  dispatch_details: DispatchDetails;
  status_history: StatusHistory[];
  created_at: string;
  updated_at: string;
  po_url: string | null;
  tracking_url: string | null;
};

/* ─── Status config ──────────────────────────────────────── */
const ALL_STATUSES = [
  { key: "Pending", label: "Order Placed", icon: FaClock },
  { key: "Confirmed", label: "Confirmed", icon: FaCheckCircle },
  { key: "Dispatched", label: "Dispatched", icon: FaTruck },
  { key: "Delivered", label: "Delivered", icon: FaMapMarkerAlt },
];

const statusColor: Record<string, string> = {
  Pending: "text-amber-500  bg-amber-50  border-amber-200",
  Confirmed: "text-blue-600   bg-blue-50   border-blue-200",
  Dispatched: "text-violet-600 bg-violet-50 border-violet-200",
  Delivered: "text-emerald-600 bg-emerald-50 border-emerald-200",
  Cancelled: "text-red-500    bg-red-50    border-red-200",
};

const statusDot: Record<string, string> = {
  Pending: "bg-amber-400",
  Confirmed: "bg-blue-500",
  Dispatched: "bg-violet-500",
  Delivered: "bg-emerald-500",
  Cancelled: "bg-red-400",
};

function formatDate(iso: string) {
  if (!iso) return "—";
  return new Date(iso).toLocaleString("en-IN", {
    day: "2-digit", month: "short", year: "numeric",
    hour: "2-digit", minute: "2-digit",
  });
}

function formatDateShort(iso: string) {
  if (!iso) return "—";
  return new Date(iso).toLocaleDateString("en-IN", {
    day: "2-digit", month: "short", year: "numeric",
  });
}

/* ─── Page ───────────────────────────────────────────────── */
export default function TrackOrderPage({
  params,
}: {
  params: Promise<{ order_id: string }>;
}) {
  const { order_id } = use(params);
  const router = useRouter();

  const [order, setOrder] = useState<TrackOrder | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    const token = localStorage.getItem("access_token");
    if (!token) {
      router.push("/login");
      return;
    }

    const fetchTrack = async () => {
      try {
        const res = await fetch(
          `${API_BASE_URL}/api/v1/b2b-orders/track/${order_id}`,
          { headers: { Authorization: `Bearer ${token}` } }
        );
        if (res.status === 401) {
          localStorage.removeItem("access_token");
          router.push("/login");
          return;
        }
        if (res.ok) {
          setOrder(await res.json());
        } else {
          setError(`Could not load tracking info (${res.status})`);
        }
      } catch {
        setError("Network error — please try again.");
      } finally {
        setLoading(false);
      }
    };

    fetchTrack();
  }, [order_id, router]);

  /* Determine active step index */
  const activeIdx = order
    ? ALL_STATUSES.findIndex((s) => s.key === order.status)
    : -1;

  /* ── Loading ── */
  if (loading) {
    return (
      <div className="min-h-screen bg-[#FAF9F6] flex items-center justify-center">
        <div className="flex flex-col items-center gap-4">
          <div className="w-12 h-12 rounded-full border-4 border-gray-200 border-t-slate-800 animate-spin" />
          <p className="text-xs font-bold text-gray-400 uppercase tracking-widest">
            Loading tracking info…
          </p>
        </div>
      </div>
    );
  }

  /* ── Error ── */
  if (error || !order) {
    return (
      <div className="min-h-screen bg-[#FAF9F6] flex items-center justify-center px-4">
        <div className="bg-white rounded-3xl border border-red-100 shadow-lg p-10 max-w-md w-full text-center">
          <div className="w-16 h-16 rounded-full bg-red-50 flex items-center justify-center mx-auto mb-4">
            <FaBox className="text-2xl text-red-400" />
          </div>
          <h2 className="text-lg font-extrabold text-gray-900 mb-2">Order Not Found</h2>
          <p className="text-xs text-gray-500 font-semibold mb-6">{error || "We couldn't find this order."}</p>
          <Link
            href="/profile/order"
            className="inline-flex items-center gap-2 px-5 py-2.5 bg-slate-900 text-white text-xs font-extrabold uppercase tracking-wider rounded-xl hover:bg-slate-800 transition-all"
          >
            Back to Orders
          </Link>
        </div>
      </div>
    );
  }

  const colorCls = statusColor[order.status] || "text-gray-500 bg-gray-50 border-gray-200";
  const dotCls = statusDot[order.status] || "bg-gray-400";

  return (
    <div className="bg-[#FAF9F6] min-h-screen py-10">
      <div className="max-w-5xl mx-auto px-4 sm:px-6">

        {/* Breadcrumb */}
        <div className="flex items-center gap-2 text-xs font-semibold text-gray-400 mb-8 select-none flex-wrap">
          <Link href="/" className="hover:text-primary transition-colors">Home</Link>
          <FaChevronRight className="text-[8px]" />
          <Link href="/profile" className="hover:text-primary transition-colors">My Account</Link>
          <FaChevronRight className="text-[8px]" />
          <Link href="/profile/order" className="hover:text-primary transition-colors">Orders</Link>
          <FaChevronRight className="text-[8px]" />
          <span className="text-gray-600">Track</span>
        </div>

        <div className="grid grid-cols-1 lg:grid-cols-4 gap-8 items-start">

          {/* ── Left Sidebar ── */}
          <div className="col-span-1 flex flex-col gap-6 lg:sticky lg:top-28">

            {/* Order ID Card */}
            <div className="bg-white rounded-[2rem] border border-gray-200/60 shadow-[0_4px_25px_rgba(0,0,0,0.02)] p-7 flex flex-col items-center text-center">
              <div className="w-16 h-16 rounded-full bg-slate-900 flex items-center justify-center mb-4 shadow-lg">
                <FaBox className="text-white text-xl" />
              </div>
              <div className="text-[10px] font-bold text-gray-400 uppercase tracking-widest mb-1">Order ID</div>
              <h2 className="text-sm font-extrabold text-gray-800 break-all">{order.order_id}</h2>

              <div className={`mt-4 inline-flex items-center gap-1.5 px-3 py-1.5 rounded-full border text-[10px] font-extrabold uppercase tracking-wider ${colorCls}`}>
                <span className={`w-1.5 h-1.5 rounded-full ${dotCls}`} />
                {order.status}
              </div>
            </div>

            {/* Sidebar Nav */}
            <div className="bg-white rounded-[2rem] border border-gray-200/60 shadow-[0_4px_25px_rgba(0,0,0,0.02)] p-6 flex flex-col gap-5">
              <div>
                <h3 className="text-[10px] font-black text-gray-400 uppercase tracking-widest mb-3 px-2">My Account</h3>
                <nav className="flex flex-col gap-1.5">
                  <Link href="/profile/order" className="flex items-center justify-between px-3 py-2.5 rounded-xl bg-primary-light text-primary text-xs font-bold">
                    <span className="flex items-center gap-2.5"><FaBox /> MY ORDERS</span>
                    <FaChevronRight className="text-[8px]" />
                  </Link>
                  <Link href="/profile" className="flex items-center justify-between px-3 py-2.5 rounded-xl hover:bg-gray-50 text-xs font-bold text-gray-600 hover:text-gray-900 transition-colors">
                    <span className="flex items-center gap-2.5"><FaUser className="text-gray-400" /> MY PROFILE</span>
                    <FaChevronRight className="text-[8px] text-gray-400" />
                  </Link>
                </nav>
              </div>
              <div className="border-t border-gray-100" />
              <div>
                <h3 className="text-[10px] font-black text-gray-400 uppercase tracking-widest mb-3 px-2">Wallet</h3>
                <nav className="flex flex-col gap-1.5">
                  <div className="flex items-center justify-between px-3 py-2.5 rounded-xl hover:bg-gray-50 text-xs font-bold text-gray-600 hover:text-gray-900 transition-colors cursor-pointer">
                    <span className="flex items-center gap-2.5"><FaWallet className="text-gray-400" /> B2B WALLET</span>
                    <FaChevronRight className="text-[8px] text-gray-400" />
                  </div>
                </nav>
              </div>
            </div>
          </div>

          {/* ── Main Content ── */}
          <div className="col-span-1 lg:col-span-3 flex flex-col gap-6">

            {/* Header Card */}
            <div className="bg-white rounded-[2rem] border border-gray-200/60 shadow-[0_4px_25px_rgba(0,0,0,0.02)] p-6 sm:p-8">
              <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4">
                <div>
                  <div className="text-[10px] font-bold text-gray-400 uppercase tracking-widest mb-1">Tracking Order</div>
                  <h1 className="text-xl font-black text-gray-900 tracking-tight">{order.order_id}</h1>
                  <p className="text-xs text-gray-500 font-semibold mt-1 flex items-center gap-1.5">
                    <FaCalendarAlt className="text-gray-300" />
                    Placed on {formatDateShort(order.created_at)}
                  </p>
                </div>

                {/* Actions */}
                <div className="flex flex-wrap gap-2">
                  {order.po_url && (
                    <a
                      href={`${API_BASE_URL}${order.po_url}`}
                      target="_blank"
                      rel="noopener noreferrer"
                      className="inline-flex items-center gap-1.5 px-4 py-2 bg-slate-900 text-white text-[11px] font-extrabold uppercase tracking-wider rounded-xl hover:bg-slate-800 transition-all shadow-md active:scale-95"
                    >
                      <FaFileDownload /> Download PO
                    </a>
                  )}
                  {order.tracking_url && (
                    <a
                      href={order.tracking_url}
                      target="_blank"
                      rel="noopener noreferrer"
                      className="inline-flex items-center gap-1.5 px-4 py-2 bg-blue-600 text-white text-[11px] font-extrabold uppercase tracking-wider rounded-xl hover:bg-blue-700 transition-all shadow-md active:scale-95"
                    >
                      <FaExternalLinkAlt /> Courier Tracking
                    </a>
                  )}
                </div>
              </div>

              {/* Order Meta Pills */}
              <div className="flex flex-wrap gap-3 mt-5 pt-5 border-t border-gray-100">
                <div className="flex items-center gap-2 bg-gray-50 border border-gray-200/80 rounded-xl px-4 py-2.5">
                  <FaBox className="text-gray-400 text-xs" />
                  <div>
                    <div className="text-[9px] font-bold text-gray-400 uppercase tracking-wider">Items</div>
                    <div className="text-xs font-extrabold text-gray-800">{order.total_items}</div>
                  </div>
                </div>
                <div className="flex items-center gap-2 bg-gray-50 border border-gray-200/80 rounded-xl px-4 py-2.5">
                  <span className="text-gray-400 text-xs font-extrabold">$</span>
                  <div>
                    <div className="text-[9px] font-bold text-gray-400 uppercase tracking-wider">Total</div>
                    <div className="text-xs font-extrabold text-gray-800">
                      ${order.total_price.toLocaleString("en-IN")}
                    </div>
                  </div>
                </div>
                <div className="flex items-center gap-2 bg-gray-50 border border-gray-200/80 rounded-xl px-4 py-2.5">
                  <FaClock className="text-gray-400 text-xs" />
                  <div>
                    <div className="text-[9px] font-bold text-gray-400 uppercase tracking-wider">Updated</div>
                    <div className="text-xs font-extrabold text-gray-800">{formatDateShort(order.updated_at)}</div>
                  </div>
                </div>
              </div>
            </div>

            {/* ── Status Timeline ── */}
            <div className="bg-white rounded-[2rem] border border-gray-200/60 shadow-[0_4px_25px_rgba(0,0,0,0.02)] p-6 sm:p-8">
              <h3 className="text-xs font-black text-gray-400 uppercase tracking-widest border-b border-gray-100 pb-4 mb-8">
                Shipment Progress
              </h3>

              {/* Step Tracker */}
              <div className="relative flex items-start justify-between mb-10">
                {/* Connector line */}
                <div className="absolute top-5 left-0 right-0 h-0.5 bg-gray-100 z-0" />
                {/* Filled portion */}
                {activeIdx >= 0 && (
                  <div
                    className="absolute top-5 left-0 h-0.5 bg-slate-800 z-0 transition-all duration-700"
                    style={{ width: `${(activeIdx / (ALL_STATUSES.length - 1)) * 100}%` }}
                  />
                )}

                {ALL_STATUSES.map((step, idx) => {
                  const StepIcon = step.icon;
                  const done = activeIdx >= 0 && idx <= activeIdx;
                  const current = idx === activeIdx;
                  return (
                    <div key={step.key} className="relative z-10 flex flex-col items-center gap-2 flex-1">
                      <div
                        className={`w-10 h-10 rounded-full flex items-center justify-center border-2 transition-all duration-500 ${current
                            ? "bg-slate-900 border-slate-900 text-white shadow-lg scale-110"
                            : done
                              ? "bg-slate-800 border-slate-800 text-white"
                              : "bg-white border-gray-200 text-gray-300"
                          }`}
                      >
                        <StepIcon className="text-sm" />
                      </div>
                      <span className={`text-[9px] font-extrabold uppercase tracking-wider text-center leading-tight ${done ? "text-slate-800" : "text-gray-300"}`}>
                        {step.label}
                      </span>
                    </div>
                  );
                })}
              </div>

              {/* Cancelled state override */}
              {order.status === "Cancelled" && (
                <div className="flex items-center gap-3 bg-red-50 border border-red-100 rounded-2xl px-5 py-4 mb-4">
                  <span className="w-8 h-8 rounded-full bg-red-100 flex items-center justify-center text-red-500 font-black text-sm">✕</span>
                  <div>
                    <div className="text-xs font-extrabold text-red-600">Order Cancelled</div>
                    <div className="text-[10px] text-red-400 font-semibold mt-0.5">This order has been cancelled. Contact support for more details.</div>
                  </div>
                </div>
              )}

              {/* Current status pill */}
              <div className={`inline-flex items-center gap-2 px-4 py-2 rounded-full border text-xs font-extrabold uppercase tracking-wider ${colorCls}`}>
                <span className={`w-2 h-2 rounded-full ${dotCls} animate-pulse`} />
                Current Status: {order.status}
              </div>
            </div>

            {/* ── Status History ── */}
            {order.status_history && order.status_history.length > 0 ? (
              <div className="bg-white rounded-[2rem] border border-gray-200/60 shadow-[0_4px_25px_rgba(0,0,0,0.02)] p-6 sm:p-8">
                <h3 className="text-xs font-black text-gray-400 uppercase tracking-widest border-b border-gray-100 pb-4 mb-6">
                  Activity Timeline
                </h3>
                <ol className="relative border-l border-gray-200 ml-4 flex flex-col gap-0">
                  {[...order.status_history].reverse().map((h, i) => (
                    <li key={i} className="mb-6 ml-6">
                      <span className={`absolute -left-2.5 w-5 h-5 rounded-full border-2 border-white flex items-center justify-center ${statusDot[h.status] || "bg-gray-300"}`} />
                      <div className="flex flex-col">
                        <span className={`text-[10px] font-extrabold uppercase tracking-wider ${statusColor[h.status]?.split(" ")[0] || "text-gray-600"}`}>
                          {h.status}
                        </span>
                        <time className="text-[9px] text-gray-400 font-semibold mt-0.5">{formatDate(h.timestamp)}</time>
                        {h.note && <p className="text-[10px] text-gray-500 font-semibold mt-1">{h.note}</p>}
                      </div>
                    </li>
                  ))}
                </ol>
              </div>
            ) : (
              <div className="bg-white rounded-[2rem] border border-gray-200/60 shadow-[0_4px_25px_rgba(0,0,0,0.02)] p-8 flex flex-col items-center text-center">
                <div className="w-12 h-12 bg-gray-50 rounded-full flex items-center justify-center text-gray-300 mb-3">
                  <FaClock className="text-xl" />
                </div>
                <p className="text-xs font-bold text-gray-400">No activity history yet</p>
                <p className="text-[10px] text-gray-300 mt-1 font-semibold">Updates will appear here as your order progresses</p>
              </div>
            )}

            {/* ── Dispatch Details ── */}
            {order.dispatch_details ? (
              <div className="bg-white rounded-[2rem] border border-gray-200/60 shadow-[0_4px_25px_rgba(0,0,0,0.02)] p-6 sm:p-8">
                <h3 className="text-xs font-black text-gray-400 uppercase tracking-widest border-b border-gray-100 pb-4 mb-6">
                  Dispatch Details
                </h3>
                <div className="grid grid-cols-1 sm:grid-cols-2 gap-5">
                  {order.dispatch_details.courier && (
                    <div>
                      <label className="block text-[10px] font-bold text-gray-400 uppercase tracking-widest mb-1.5">Courier</label>
                      <div className="px-4 py-3 bg-gray-50 border border-gray-200/80 rounded-xl text-xs font-bold text-gray-700">
                        {order.dispatch_details.courier}
                      </div>
                    </div>
                  )}
                  {order.dispatch_details.awb && (
                    <div>
                      <label className="block text-[10px] font-bold text-gray-400 uppercase tracking-widest mb-1.5">AWB / Tracking No.</label>
                      <div className="px-4 py-3 bg-gray-50 border border-gray-200/80 rounded-xl text-xs font-bold text-gray-700 flex items-center justify-between gap-2">
                        <span className="font-mono">{order.dispatch_details.awb}</span>
                        {order.tracking_url && (
                          <a href={order.tracking_url} target="_blank" rel="noopener noreferrer" className="text-blue-500 hover:text-blue-700 transition-colors">
                            <FaExternalLinkAlt className="text-[10px]" />
                          </a>
                        )}
                      </div>
                    </div>
                  )}
                  {order.dispatch_details.dispatch_date && (
                    <div>
                      <label className="block text-[10px] font-bold text-gray-400 uppercase tracking-widest mb-1.5">Dispatch Date</label>
                      <div className="px-4 py-3 bg-gray-50 border border-gray-200/80 rounded-xl text-xs font-bold text-gray-700">
                        {formatDateShort(order.dispatch_details.dispatch_date)}
                      </div>
                    </div>
                  )}
                  {order.dispatch_details.expected_delivery && (
                    <div>
                      <label className="block text-[10px] font-bold text-gray-400 uppercase tracking-widest mb-1.5">Expected Delivery</label>
                      <div className="px-4 py-3 bg-emerald-50 border border-emerald-200 rounded-xl text-xs font-extrabold text-emerald-700">
                        {formatDateShort(order.dispatch_details.expected_delivery)}
                      </div>
                    </div>
                  )}
                </div>
              </div>
            ) : (
              order.status !== "Delivered" && (
                <div className="bg-white rounded-[2rem] border border-gray-200/60 shadow-[0_4px_25px_rgba(0,0,0,0.02)] p-8 flex items-center gap-4">
                  <div className="w-12 h-12 bg-amber-50 rounded-full flex items-center justify-center text-amber-400 flex-shrink-0">
                    <FaTruck className="text-xl" />
                  </div>
                  <div>
                    <p className="text-xs font-extrabold text-gray-700">Not yet dispatched</p>
                    <p className="text-[10px] text-gray-400 font-semibold mt-0.5">
                      Dispatch and courier details will appear here once your order ships.
                    </p>
                  </div>
                </div>
              )
            )}

            {/* Back button */}
            <div className="flex">
              <Link
                href="/profile/order"
                className="inline-flex items-center gap-2 px-5 py-2.5 bg-white border border-gray-200 text-gray-700 text-[11px] font-extrabold uppercase tracking-wider rounded-xl hover:bg-gray-50 transition-all shadow-sm active:scale-95"
              >
                ← Back to My Orders
              </Link>
            </div>

          </div>{/* /main */}
        </div>
      </div>
    </div>
  );
}
