"use client";

import Image from "next/image";
import Link from "next/link";
import { useParams } from "next/navigation";
import { useEffect, useState } from "react";
import { motion } from "framer-motion";
import {
  ArrowLeft, Package, Truck, CheckCircle2,
  Clock, XCircle, MapPin, CreditCard,
} from "lucide-react";

import {
  getOrderById,
  updateOrderStatus,
  subscribeOrders,
  STATUS_LABELS,
  STATUS_COLORS,
  STATUS_STEPS,
  PAYMENT_LABELS,
  type Order,
  type OrderStatus,
} from "@/lib/orders";

/* ─── Styles ─── */
const GLASS = {
  background: "linear-gradient(135deg, rgba(18,14,40,0.88) 0%, rgba(10,8,26,0.94) 100%)",
  backdropFilter: "blur(22px) saturate(170%)",
  border: "1px solid rgba(201,162,80,0.13)",
  boxShadow: "0 4px 24px rgba(0,0,0,0.40)",
};
const GOLD_TEXT = {
  background: "linear-gradient(90deg, #c9a250, #f0d080)",
  WebkitBackgroundClip: "text",
  backgroundClip: "text",
  WebkitTextFillColor: "transparent",
};

/* ─── Status icon ─── */
const STATUS_ICONS: Record<OrderStatus, React.ReactNode> = {
  pending:    <Clock         className="h-4 w-4" />,
  confirmed:  <CheckCircle2 className="h-4 w-4" />,
  processing: <Package      className="h-4 w-4" />,
  shipped:    <Truck        className="h-4 w-4" />,
  delivered:  <CheckCircle2 className="h-4 w-4" />,
  cancelled:  <XCircle      className="h-4 w-4" />,
};

/* ─── Progress tracker ─── */
function StatusTracker({ order }: { order: Order }) {
  if (order.status === "cancelled") {
    return (
      <div
        className="flex items-center gap-3 rounded-2xl px-4 py-3"
        style={{ background: "rgba(239,68,68,0.08)", border: "1px solid rgba(239,68,68,0.25)" }}
      >
        <XCircle className="h-5 w-5 shrink-0 text-red-400" />
        <p className="text-sm font-bold text-red-400">অর্ডারটি বাতিল করা হয়েছে।</p>
      </div>
    );
  }

  const currentIdx = STATUS_STEPS.indexOf(order.status);

  return (
    <div className="space-y-3">
      <div className="flex items-center gap-0">
        {STATUS_STEPS.map((s, i) => {
          const done    = i <= currentIdx;
          const active  = i === currentIdx;
          const color   = STATUS_COLORS[s];
          return (
            <div key={s} className="flex flex-1 items-center">
              <div className="flex flex-col items-center gap-1">
                <div
                  className="flex h-9 w-9 items-center justify-center rounded-full transition-all duration-500"
                  style={
                    active
                      ? { background: `${color}22`, border: `2px solid ${color}`, color }
                      : done
                      ? { background: color, color: "#07071a" }
                      : { background: "rgba(255,255,255,0.05)", border: "1px solid rgba(255,255,255,0.1)", color: "rgba(255,255,255,0.25)" }
                  }
                >
                  {STATUS_ICONS[s]}
                </div>
                <span className="text-[10px] font-semibold" style={{ color: done ? "#f0d080" : "rgba(255,255,255,0.28)" }}>
                  {STATUS_LABELS[s]}
                </span>
              </div>
              {i < STATUS_STEPS.length - 1 && (
                <div
                  className="mx-1 mb-5 h-0.5 flex-1 transition-all duration-500"
                  style={{ background: i < currentIdx ? "linear-gradient(90deg,#c9a250,#f0d080)" : "rgba(255,255,255,0.07)" }}
                />
              )}
            </div>
          );
        })}
      </div>
    </div>
  );
}

/* ─── MAIN PAGE ─── */
export default function OrderDetailPage() {
  const { id } = useParams<{ id: string }>();
  const [order, setOrder] = useState<Order | null>(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    const refresh = () => {
      const o = getOrderById(id);
      setOrder(o);
      setLoading(false);
    };

    // Load from localStorage immediately
    refresh();

    // Sync latest status from API in background
    const apiBase = process.env.NEXT_PUBLIC_API_URL ?? "http://127.0.0.1:8000/api/v1";
    fetch(`${apiBase}/orders/${id}`)
      .then((r) => (r.ok ? r.json() : null))
      .then((apiOrder) => {
        if (!apiOrder?.status) return;
        const local = getOrderById(id);
        if (local && apiOrder.status !== local.status) {
          updateOrderStatus(id, apiOrder.status as OrderStatus, "স্ট্যাটাস আপডেট হয়েছে।");
        }
      })
      .catch(() => { /* API offline — show cached data */ });

    return subscribeOrders(refresh);
  }, [id]);

  if (loading) {
    return (
      <div className="flex min-h-[50vh] items-center justify-center">
        <div className="h-8 w-8 animate-spin rounded-full" style={{ border: "2px solid rgba(201,162,80,0.2)", borderTopColor: "#c9a250" }} />
      </div>
    );
  }

  if (!order) {
    return (
      <div className="flex min-h-[50vh] flex-col items-center justify-center gap-4 text-center">
        <Package className="h-16 w-16 text-white/15" />
        <p className="text-xl font-bold text-white/60">অর্ডার পাওয়া যায়নি।</p>
        <Link href="/dashboard" className="text-sm text-amber-400 underline">ড্যাশবোর্ডে ফিরুন</Link>
      </div>
    );
  }

  return (
    <section className="mx-auto max-w-3xl space-y-5 px-4 py-8 sm:px-6">
      {/* Back link */}
      <Link
        href="/dashboard"
        className="inline-flex items-center gap-1.5 text-sm font-semibold text-white/50 transition-all hover:text-amber-400"
      >
        <ArrowLeft className="h-4 w-4" /> ড্যাশবোর্ড
      </Link>

      {/* Header */}
      <motion.div
        initial={{ opacity: 0, y: 10 }}
        animate={{ opacity: 1, y: 0 }}
        className="rounded-2xl p-5"
        style={GLASS}
      >
        <div className="flex flex-wrap items-start justify-between gap-3">
          <div>
            <p className="text-xs text-white/35 uppercase tracking-widest mb-1">অর্ডার নম্বর</p>
            <h1 className="text-3xl font-black font-mono" style={GOLD_TEXT}>{order.id}</h1>
            <p className="mt-1 text-xs text-white/40">
              {new Date(order.createdAt).toLocaleDateString("bn-BD", {
                day: "numeric", month: "long", year: "numeric", hour: "2-digit", minute: "2-digit",
              })}
            </p>
          </div>
          <div className="text-right">
            <span
              className="rounded-full px-3 py-1 text-xs font-black uppercase tracking-wider text-[#07071a]"
              style={{ background: STATUS_COLORS[order.status] }}
            >
              {STATUS_LABELS[order.status]}
            </span>
            <p className="mt-2 text-xs text-white/35">
              প্রত্যাশিত:{" "}
              {new Date(order.estimatedDelivery).toLocaleDateString("bn-BD", {
                day: "numeric", month: "short",
              })}
            </p>
          </div>
        </div>
      </motion.div>

      {/* Status track */}
      <motion.div
        initial={{ opacity: 0, y: 10 }}
        animate={{ opacity: 1, y: 0 }}
        transition={{ delay: 0.05 }}
        className="rounded-2xl p-5"
        style={GLASS}
      >
        <p className="mb-4 text-xs font-bold uppercase tracking-widest text-white/30">ডেলিভারি স্ট্যাটাস</p>
        <StatusTracker order={order} />
      </motion.div>

      {/* Items */}
      <motion.div
        initial={{ opacity: 0, y: 10 }}
        animate={{ opacity: 1, y: 0 }}
        transition={{ delay: 0.10 }}
        className="rounded-2xl p-5"
        style={GLASS}
      >
        <p className="mb-4 text-xs font-bold uppercase tracking-widest text-white/30">পণ্যসমূহ</p>
        <div className="space-y-3">
          {order.items.map((item, i) => (
            <div
              key={i}
              className="flex items-center gap-3 rounded-xl p-3"
              style={{ background: "rgba(255,255,255,0.03)", border: "1px solid rgba(255,255,255,0.06)" }}
            >
              <div className="relative h-14 w-11 shrink-0 overflow-hidden rounded-lg">
                <Image src={item.image} alt={item.name} fill className="object-cover" />
              </div>
              <div className="flex-1 min-w-0">
                <p className="truncate text-sm font-bold text-white/85">{item.name}</p>
                <p className="text-xs text-white/40">
                  {[item.color, item.size].filter(Boolean).join(" / ")} × {item.qty}
                </p>
              </div>
              <p className="shrink-0 text-sm font-bold text-amber-400">৳{(item.price * item.qty).toLocaleString()}</p>
            </div>
          ))}
        </div>

        {/* Totals */}
        <div className="mt-4 space-y-2 border-t border-white/[0.06] pt-4 text-sm">
          {[
            { label: "সাবটোটাল",   value: `৳${order.subtotal.toLocaleString()}` },
            { label: "শিপিং",       value: `৳${order.shippingCost.toLocaleString()}` },
            { label: "ডিসকাউন্ট",  value: order.discount > 0 ? `-৳${order.discount.toLocaleString()}` : "—" },
          ].map(({ label, value }) => (
            <div key={label} className="flex justify-between text-white/50">
              <span>{label}</span><span>{value}</span>
            </div>
          ))}
          <div className="flex justify-between border-t border-white/[0.06] pt-2 font-extrabold text-white">
            <span>মোট</span>
            <span style={GOLD_TEXT}>৳{order.total.toLocaleString()}</span>
          </div>
        </div>
      </motion.div>

      {/* Shipping + Payment */}
      <div className="grid gap-4 sm:grid-cols-2">
        <motion.div
          initial={{ opacity: 0, y: 10 }}
          animate={{ opacity: 1, y: 0 }}
          transition={{ delay: 0.15 }}
          className="rounded-2xl p-5 space-y-2"
          style={GLASS}
        >
          <div className="flex items-center gap-2 mb-3">
            <MapPin className="h-4 w-4 text-amber-400" />
            <p className="text-xs font-bold uppercase tracking-widest text-white/30">শিপিং ঠিকানা</p>
          </div>
          <p className="text-sm font-bold text-white/85">{order.shipping.fullName}</p>
          <p className="text-xs text-white/50">{order.shipping.phone}</p>
          {order.shipping.email && <p className="text-xs text-white/40">{order.shipping.email}</p>}
          <p className="text-xs text-white/50">{order.shipping.address}</p>
          <p className="text-xs text-white/50">{order.shipping.area}, {order.shipping.city}</p>
          {order.shipping.postalCode && <p className="text-xs text-white/40">{order.shipping.postalCode}</p>}
        </motion.div>

        <motion.div
          initial={{ opacity: 0, y: 10 }}
          animate={{ opacity: 1, y: 0 }}
          transition={{ delay: 0.20 }}
          className="rounded-2xl p-5 space-y-2"
          style={GLASS}
        >
          <div className="flex items-center gap-2 mb-3">
            <CreditCard className="h-4 w-4 text-amber-400" />
            <p className="text-xs font-bold uppercase tracking-widest text-white/30">পেমেন্ট তথ্য</p>
          </div>
          <p className="text-sm font-bold text-white/85">{PAYMENT_LABELS[order.payment.method]}</p>
          {order.payment.accountNumber && (
            <p className="text-xs text-white/50">নম্বর: {order.payment.accountNumber}</p>
          )}
          {order.payment.transactionId && (
            <p className="text-xs text-white/50">TrxID: {order.payment.transactionId}</p>
          )}
          <span
            className="inline-block rounded-full px-2 py-0.5 text-[10px] font-black text-[#07071a]"
            style={{
              background: order.payment.status === "paid" ? "#22c55e" : "#c9a250",
            }}
          >
            {order.payment.status === "paid" ? "পেইড" : "অপেক্ষমাণ"}
          </span>
        </motion.div>
      </div>

      {/* Status history */}
      <motion.div
        initial={{ opacity: 0, y: 10 }}
        animate={{ opacity: 1, y: 0 }}
        transition={{ delay: 0.25 }}
        className="rounded-2xl p-5"
        style={GLASS}
      >
        <p className="mb-4 text-xs font-bold uppercase tracking-widest text-white/30">আপডেট টাইমলাইন</p>
        <div className="relative space-y-4 pl-5">
          <div className="absolute left-1.5 top-0 h-full w-px" style={{ background: "rgba(255,255,255,0.07)" }} />
          {order.statusHistory.map((h, i) => (
            <div key={i} className="relative">
              <div
                className="absolute -left-4 top-1 h-2.5 w-2.5 rounded-full"
                style={{ background: STATUS_COLORS[h.status] }}
              />
              <p className="text-sm font-semibold" style={{ color: STATUS_COLORS[h.status] }}>
                {STATUS_LABELS[h.status]}
              </p>
              <p className="text-xs text-white/45">{h.note}</p>
              <p className="text-[11px] text-white/25">
                {new Date(h.timestamp).toLocaleDateString("bn-BD", {
                  day: "numeric", month: "short", year: "numeric",
                  hour: "2-digit", minute: "2-digit",
                })}
              </p>
            </div>
          ))}
        </div>
      </motion.div>
    </section>
  );
}
