"use client";
import { useParams, useRouter } from "next/navigation";
import { motion } from "framer-motion";
import {
  ArrowLeft,
  Truck,
  MapPin,
  CheckCircle,
  Package,
  Home,
  ClipboardList,
  Copy,
  Check,
  ExternalLink,
  Loader2,
  XCircle,
} from "lucide-react";
import { useState, useCallback, useEffect } from "react";
import { orderService, ORDER_STATUS, orderStatusMeta, type MarketplaceOrder } from "@/services/orderService";
import { getCarrierTrackingUrl } from "@/utils/carrierTracking";
import { useFormatPrice } from "@/hooks/useFormatPrice";

const PIPELINE = [
  { status: ORDER_STATUS.PLACED,    label: "Placed",    icon: ClipboardList },
  { status: ORDER_STATUS.CONFIRMED, label: "Confirmed", icon: CheckCircle },
  { status: ORDER_STATUS.SHIPPED,   label: "Shipped",   icon: Truck },
  { status: ORDER_STATUS.DELIVERED, label: "Delivered", icon: Home },
];

export function TrackingPage() {
  const params = useParams<{ id: string }>();
  const router = useRouter();
  const formatPrice = useFormatPrice();
  const [order, setOrder] = useState<MarketplaceOrder | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState("");
  const [copied, setCopied] = useState(false);

  useEffect(() => {
    if (!params?.id) return;
    setLoading(true);
    orderService
      .getOrderDetail(params.id)
      .then(setOrder)
      .catch(() => setError("Could not load order details."))
      .finally(() => setLoading(false));
  }, [params?.id]);

  const copyTracking = useCallback(() => {
    if (order?.trackingNumber) {
      navigator.clipboard.writeText(order.trackingNumber).catch(() => {});
      setCopied(true);
      setTimeout(() => setCopied(false), 2000);
    }
  }, [order]);

  /* ── Loading ── */
  if (loading) {
    return (
      <div className="flex flex-col items-center justify-center h-full gap-3 py-32" style={{ background: "var(--bg)" }}>
        <Loader2 size={28} className="animate-spin" color="var(--accent)" />
        <p className="text-xs text-[var(--text-muted)]">Loading tracking info…</p>
      </div>
    );
  }

  /* ── Error / not found ── */
  if (error || !order) {
    return (
      <div className="flex flex-col items-center justify-center h-full gap-4 px-4 py-20" style={{ background: "var(--bg)" }}>
        <Truck size={48} className="text-[var(--text-muted)] opacity-40" />
        <p className="font-bold text-[var(--text-primary)]">Order Not Found</p>
        <button onClick={() => router.push("/marketplace/orders")} className="text-sm text-[var(--accent)]">
          ← Back to Orders
        </button>
      </div>
    );
  }

  const isCancelled = order.status === ORDER_STATUS.CANCELLED;
  const currentStepIdx = PIPELINE.findIndex((p) => p.status === order.status);
  const activeIdx = currentStepIdx < 0 ? (isCancelled ? -1 : 0) : currentStepIdx;
  const pct = isCancelled
    ? 0
    : activeIdx < 0
    ? 0
    : Math.round((activeIdx / (PIPELINE.length - 1)) * 100);

  const statusMeta = orderStatusMeta(order.status);
  const trackingUrl = order.trackingNumber
    ? getCarrierTrackingUrl(order.trackingNumber)
    : null;

  return (
    <div className="min-h-full pb-20" style={{ background: "var(--bg)" }}>
      <div className="max-w-2xl mx-auto px-4 py-6">

        {/* Back */}
        <div className="flex items-center gap-3 mb-6">
          <button
            onClick={() => router.back()}
            className="p-2 rounded-full hover:bg-[var(--card)] transition-colors"
          >
            <ArrowLeft size={18} className="text-[var(--text-muted)]" />
          </button>
          <h1 className="text-base font-black text-[var(--text-primary)]">
            Order Tracking
          </h1>
          <span
            className="ml-auto text-[11px] px-2.5 py-1 rounded-full font-bold shrink-0"
            style={{ background: `${statusMeta.color}18`, color: statusMeta.color }}
          >
            {statusMeta.label}
          </span>
        </div>

        {/* Status hero */}
        <motion.div
          initial={{ opacity: 0, y: 16 }}
          animate={{ opacity: 1, y: 0 }}
          className="rounded-3xl overflow-hidden border border-[var(--border)] mb-5"
          style={{ background: "linear-gradient(135deg, var(--deep) 0%, var(--card) 100%)" }}
        >
          <div className="p-5">
            {isCancelled ? (
              <div className="flex items-center gap-3">
                <XCircle size={24} color="#ef4444" />
                <div>
                  <p className="text-sm font-black" style={{ color: "#ef4444" }}>Order Cancelled</p>
                  <p className="text-[11px] text-[var(--text-muted)]">This order has been cancelled.</p>
                </div>
              </div>
            ) : (
              <>
                {/* Progress bar */}
                <div className="mb-4">
                  <div className="flex items-center justify-between mb-1.5">
                    <span className="text-[10px] text-[var(--text-muted)]">Delivery Progress</span>
                    <span className="text-[10px] font-mono" style={{ color: "var(--accent)" }}>{pct}%</span>
                  </div>
                  <div className="h-2 rounded-full overflow-hidden" style={{ background: "rgba(255,255,255,0.08)" }}>
                    <motion.div
                      initial={{ width: 0 }}
                      animate={{ width: `${pct}%` }}
                      transition={{ duration: 1.2, ease: [0.16, 1, 0.3, 1], delay: 0.3 }}
                      className="h-full rounded-full"
                      style={{ background: "linear-gradient(90deg, var(--accent), #f0c040)" }}
                    />
                  </div>
                </div>

                {/* Pipeline steps */}
                <div className="flex items-center justify-between gap-1">
                  {PIPELINE.map((step, i) => {
                    const done = i <= activeIdx;
                    const active = i === activeIdx;
                    const Icon = step.icon;
                    return (
                      <div key={step.status} className="flex flex-col items-center gap-1 flex-1">
                        <motion.div
                          animate={{
                            background: done ? "var(--accent)" : "rgba(255,255,255,0.06)",
                            scale: active ? 1.15 : 1,
                          }}
                          transition={{ duration: 0.3 }}
                          className="w-8 h-8 rounded-full flex items-center justify-center border"
                          style={{ borderColor: done ? "var(--accent)" : "rgba(255,255,255,0.1)" }}
                        >
                          <Icon size={14} style={{ color: done ? "#fff" : "rgba(255,255,255,0.3)" }} />
                        </motion.div>
                        <span
                          className="text-[9px] font-medium text-center leading-tight"
                          style={{ color: done ? "var(--text-primary)" : "rgba(255,255,255,0.3)" }}
                        >
                          {step.label}
                        </span>
                      </div>
                    );
                  })}
                </div>
              </>
            )}
          </div>
        </motion.div>

        {/* Tracking number + Live tracking button */}
        {order.trackingNumber && (
          <motion.div
            initial={{ opacity: 0, y: 12 }}
            animate={{ opacity: 1, y: 0 }}
            transition={{ delay: 0.15 }}
            className="rounded-2xl overflow-hidden border border-[var(--border)] mb-5"
            style={{ background: "var(--card)" }}
          >
            <div className="px-5 pt-4 pb-3">
              <p className="text-[10px] text-[var(--text-muted)] mb-1.5">Tracking Number</p>
              <div className="flex items-center gap-2 mb-4">
                {/* Clickable → opens carrier page */}
                {trackingUrl ? (
                  <a
                    href={trackingUrl}
                    target="_blank"
                    rel="noopener noreferrer"
                    className="font-mono text-sm font-bold flex items-center gap-1.5 hover:underline"
                    style={{ color: "var(--accent)" }}
                  >
                    {order.trackingNumber}
                    <ExternalLink size={12} />
                  </a>
                ) : (
                  <span className="font-mono text-sm font-bold text-[var(--text-primary)]">
                    {order.trackingNumber}
                  </span>
                )}
                <button onClick={copyTracking} className="p-1.5 rounded-lg hover:bg-[var(--bg)] ml-auto">
                  {copied ? (
                    <Check size={13} className="text-green-400" />
                  ) : (
                    <Copy size={13} className="text-[var(--text-muted)]" />
                  )}
                </button>
              </div>

              {/* Live tracking CTA */}
              {trackingUrl && (
                <a
                  href={trackingUrl}
                  target="_blank"
                  rel="noopener noreferrer"
                  className="flex items-center justify-between w-full px-4 py-3.5 rounded-xl transition-all hover:brightness-110 active:scale-[0.98]"
                  style={{ background: "linear-gradient(135deg, var(--accent) 0%, #ff4040 100%)" }}
                >
                  <div className="flex items-center gap-3">
                    <div
                      className="w-9 h-9 rounded-lg flex items-center justify-center"
                      style={{ background: "rgba(255,255,255,0.15)" }}
                    >
                      <Truck size={16} className="text-white" />
                    </div>
                    <div>
                      <p className="text-xs font-black text-white">Track Live Shipment</p>
                      <p className="text-[10px] text-white/70">
                        Opens carrier tracking page in new tab
                      </p>
                    </div>
                  </div>
                  <ExternalLink size={16} className="text-white/80 shrink-0" />
                </a>
              )}
              <p className="text-[10px] text-[var(--text-muted)] text-center mt-2">
                View real-time status, location &amp; delivery history on the carrier&apos;s website
              </p>
            </div>
          </motion.div>
        )}

        {/* Product */}
        <motion.div
          initial={{ opacity: 0, y: 12 }}
          animate={{ opacity: 1, y: 0 }}
          transition={{ delay: 0.2 }}
          className="flex items-center gap-3 p-4 rounded-2xl border border-[var(--border)] mb-5"
          style={{ background: "var(--card)" }}
        >
          {order.listingImage ? (
            <img src={order.listingImage} alt={order.listingName} className="w-14 h-14 rounded-xl object-cover shrink-0" />
          ) : (
            <div className="w-14 h-14 rounded-xl flex items-center justify-center shrink-0" style={{ background: "var(--bg)" }}>
              <Package size={22} className="text-[var(--text-muted)]" />
            </div>
          )}
          <div className="flex-1 min-w-0">
            <p className="text-xs font-semibold text-[var(--text-primary)] line-clamp-2">
              {order.listingName || `Listing #${order.listingId}`}
            </p>
            <p className="text-[10px] text-[var(--text-muted)] mt-0.5">Order #{order.id}</p>
          </div>
          <p className="text-sm font-black shrink-0" style={{ color: "var(--accent)" }}>
            {formatPrice(order.price)}
          </p>
        </motion.div>

        {/* Delivery address */}
        <motion.div
          initial={{ opacity: 0, y: 12 }}
          animate={{ opacity: 1, y: 0 }}
          transition={{ delay: 0.25 }}
          className="rounded-2xl overflow-hidden border border-[var(--border)] mb-5"
          style={{ background: "var(--card)" }}
        >
          <div className="flex items-center gap-2 px-5 py-3 border-b border-[var(--border)]">
            <MapPin size={14} className="text-[var(--accent)]" />
            <span className="text-sm font-bold text-[var(--text-primary)]">Delivery Address</span>
          </div>
          <div className="p-5">
            <p className="text-sm leading-relaxed text-[var(--text-primary)]">
              {[order.address, order.city, order.state, order.country].filter(Boolean).join(", ")}
              {order.pincode ? ` — ${order.pincode}` : ""}
            </p>
          </div>
        </motion.div>

        {/* View full order */}
        <button
          onClick={() => router.push(`/marketplace/orders/${order.id}`)}
          className="w-full py-3 rounded-xl text-sm font-semibold border border-[var(--border)] text-[var(--text-muted)] hover:text-[var(--text-primary)] transition-colors"
          style={{ background: "var(--card)" }}
        >
          View Full Order Details
        </button>
      </div>
    </div>
  );
}
