"use client";

import { useState, useEffect } from "react";
import { createPortal } from "react-dom";
import Image from "next/image";
import Link from "next/link";
import {
  CaretDown,
  Package,
  MapPin,
  Phone,
  CreditCard,
  Receipt,
  Clock,
  CheckCircle,
  Truck,
  ShoppingBag,
  X,
  MagnifyingGlassPlus,
} from "@phosphor-icons/react";
import { useLanguage } from "@/lib/i18n/context";

export interface OrderItem {
  name:          string;
  quantity:      number;
  price:         number;
  price_gros?:   number;
  min_qty_gros?: number;
  size?:         string;
  image_url?:    string;
}

export interface Order {
  id:                 number;
  items:              OrderItem[];
  total:              number | string;
  status:             string;
  phone:              string;
  address:            string;
  notes?:             string;
  payment_method?:    string;
  payment_screenshot?: string;
  created_at:         string;
  review_rating?:     number | null;
  review_comment?:    string | null;
}

/* ── Status style config (no text — text comes from translations) ── */
const STATUS_STYLE: Record<string, {
  dot:   string;
  badge: string;
  bar:   string;
  Icon:  React.ElementType;
}> = {
  payment_review: {
    dot:   "bg-orange-400",
    badge: "bg-orange-400/10 text-orange-500 border-orange-300/40",
    bar:   "bg-orange-400",
    Icon:  Clock,
  },
  pending: {
    dot:   "bg-yellow-400",
    badge: "bg-yellow-400/10 text-yellow-600 border-yellow-300/40",
    bar:   "bg-yellow-400",
    Icon:  Clock,
  },
  confirmed: {
    dot:   "bg-blue-400",
    badge: "bg-blue-400/10 text-blue-600 border-blue-300/40",
    bar:   "bg-blue-500",
    Icon:  CheckCircle,
  },
  delivered: {
    dot:   "bg-green-400",
    badge: "bg-green-400/10 text-green-600 border-green-300/40",
    bar:   "bg-green-400",
    Icon:  Truck,
  },
};

/* ── Progress bar for active orders ── */
const STEPS = ["payment_review", "pending", "confirmed", "delivered"];
function ProgressBar({ status }: { status: string }) {
  if (status === "delivered") return null;
  const idx  = STEPS.indexOf(status);
  const pct  = idx < 0 ? 0 : Math.round(((idx + 1) / STEPS.length) * 100);
  return (
    <div className="w-full h-1 bg-brand-dark/8 rounded-full overflow-hidden">
      <div
        className="h-full rounded-full bg-brand-dark transition-all duration-700"
        style={{ width: `${pct}%` }}
      />
    </div>
  );
}

/* ── Review widget ── */
function ReviewWidget({ orderId, initialRating, initialComment }: {
  orderId: number;
  initialRating?: number | null;
  initialComment?: string | null;
}) {
  const { t } = useLanguage();
  const [rating,    setRating]    = useState<number>(initialRating ?? 0);
  const [hover,     setHover]     = useState<number>(0);
  const [comment,   setComment]   = useState(initialComment ?? "");
  const [submitted, setSubmitted] = useState(!!initialRating);
  const [loading,   setLoading]   = useState(false);

  const submit = async () => {
    if (!rating) return;
    setLoading(true);
    const res = await fetch("/api/orders/review", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ order_id: orderId, rating, comment }),
    });
    if (res.ok) setSubmitted(true);
    setLoading(false);
  };

  if (submitted) {
    return (
      <div className="flex items-start gap-3 bg-green-50 border border-green-200/60 rounded-2xl px-5 py-4">
        <span className="text-green-500 text-lg mt-0.5">✓</span>
        <div>
          <p className="text-green-700 text-sm font-semibold">{t.suivi.reviewThanks}</p>
          <div className="flex gap-0.5 mt-1">
            {[1,2,3,4,5].map(s => (
              <span key={s} className={`text-base ${s <= rating ? "text-brand-yellow" : "text-brand-dark/15"}`}>★</span>
            ))}
          </div>
          {comment && <p className="text-green-600/70 text-xs mt-1 italic">&quot;{comment}&quot;</p>}
        </div>
      </div>
    );
  }

  return (
    <div className="bg-brand-yellow/8 border border-brand-yellow/30 rounded-2xl px-5 py-4 space-y-3">
      <p className="text-brand-dark text-sm font-bold">{t.suivi.reviewQuestion}</p>

      {/* Stars */}
      <div className="flex gap-1">
        {[1,2,3,4,5].map(s => (
          <button
            key={s}
            onClick={() => setRating(s)}
            onMouseEnter={() => setHover(s)}
            onMouseLeave={() => setHover(0)}
            className="text-2xl transition-transform duration-100 hover:scale-110"
          >
            <span className={s <= (hover || rating) ? "text-brand-yellow" : "text-brand-dark/15"}>★</span>
          </button>
        ))}
      </div>

      {/* Optional comment */}
      {rating > 0 && (
        <textarea
          value={comment}
          onChange={e => setComment(e.target.value)}
          placeholder={t.suivi.reviewPlaceholder}
          rows={2}
          className="w-full text-sm bg-white border border-brand-dark/10 rounded-xl px-3 py-2 text-brand-dark placeholder:text-brand-dark/30 resize-none focus:outline-none focus:border-brand-yellow transition-colors"
        />
      )}

      {rating > 0 && (
        <button
          onClick={submit}
          disabled={loading}
          className="text-xs font-bold bg-brand-dark text-brand-yellow px-5 py-2 rounded-full hover:bg-brand-dark/80 transition-colors disabled:opacity-50"
        >
          {loading ? t.suivi.reviewSending : t.suivi.reviewSubmit}
        </button>
      )}
    </div>
  );
}

/* ── Single order card ── */
function OrderCard({ order, defaultOpen, onOpenLightbox }: {
  order: Order;
  defaultOpen: boolean;
  onOpenLightbox: (src: string) => void;
}) {
  const { t, locale } = useLanguage();
  const [open, setOpen] = useState(defaultOpen);
  const style  = STATUS_STYLE[order.status] ?? STATUS_STYLE.pending;
  const statusText = t.suivi.status[order.status as keyof typeof t.suivi.status] ?? t.suivi.status.pending;
  const { Icon } = style;
  const items  = order.items;
  const total  = Number(order.total);
  const date   = new Date(order.created_at).toLocaleDateString(locale === "fr" ? "fr-FR" : "en-GB", {
    day: "numeric", month: "long", year: "numeric",
  });
  const itemCount = items.reduce((s, i) => s + i.quantity, 0);

  return (
    <div className={`bg-white border rounded-2xl overflow-hidden shadow-sm transition-all duration-200 ${
      order.status === "delivered"
        ? "border-brand-dark/8 opacity-70"
        : "border-brand-dark/12 shadow-[0_2px_16px_rgba(0,0,0,0.06)]"
    }`}>

      {/* Colored top bar */}
      <div className={`h-1 w-full ${style.bar}`} />

      {/* Collapsed header — always visible */}
      <button
        onClick={() => setOpen(o => !o)}
        className="w-full text-left px-6 py-5 group"
      >
        <div className="flex items-start justify-between gap-4">

          {/* Left: status + order info */}
          <div className="flex-1 min-w-0 space-y-3">

            {/* Status row */}
            <div className="flex items-center gap-2.5">
              <span className={`inline-flex items-center gap-1.5 px-3 py-1 rounded-full border text-xs font-bold ${style.badge}`}>
                <Icon size={11} weight="bold" />
                {statusText.label}
              </span>
            </div>

            {/* Order # + total */}
            <div className="flex items-baseline justify-between gap-4 flex-wrap">
              <div>
                <p className="text-brand-dark font-bold text-xl" style={{ fontFamily: "var(--font-space,sans-serif)" }}>
                  #{String(order.id).padStart(4, "0")}
                </p>
                <p className="text-brand-dark/40 text-xs mt-0.5">{date} · {itemCount} {t.suivi.articles.toLowerCase()}</p>
              </div>
              <p className="text-brand-dark font-bold text-xl" style={{ fontFamily: "var(--font-space,sans-serif)" }}>
                {total.toLocaleString("fr-MR")} <span className="text-sm font-semibold text-brand-dark/50">MRU</span>
              </p>
            </div>

            {/* Progress bar (active orders only) */}
            {order.status !== "delivered" && (
              <ProgressBar status={order.status} />
            )}
          </div>

          {/* Chevron */}
          <div className={`flex-shrink-0 mt-1 text-brand-dark/30 group-hover:text-brand-dark transition-all duration-300 ${open ? "rotate-180" : ""}`}>
            <CaretDown size={18} weight="bold" />
          </div>
        </div>
      </button>

      {/* Review widget — always visible for delivered orders, outside the toggle */}
      {order.status === "delivered" && (
        <div className="px-6 pb-5 -mt-1">
          <ReviewWidget
            orderId={order.id}
            initialRating={order.review_rating}
            initialComment={order.review_comment}
          />
        </div>
      )}

      {/* Expanded content */}
      {open && (
        <div className="border-t border-brand-dark/8">

          {/* Items */}
          <div className="px-6 py-5 space-y-4">
            <p className="text-brand-dark/40 text-xs font-bold uppercase tracking-wider flex items-center gap-1.5">
              <Package size={11} weight="bold" /> {t.suivi.articles}
            </p>
            <div className="space-y-3">
              {items.map((item, i) => {
                const isGros    = !!(item.price_gros && item.price_gros > 0 && item.min_qty_gros && item.min_qty_gros > 1 && item.quantity >= item.min_qty_gros);
                const unitPrice = isGros ? item.price_gros! : item.price;
                return (
                <div key={i} className="flex items-center gap-3">
                  {item.image_url ? (
                    <div className="w-14 h-14 rounded-xl overflow-hidden bg-brand-sand-light relative flex-shrink-0">
                      <Image src={item.image_url} alt={item.name} fill className="object-cover" />
                    </div>
                  ) : (
                    <div className="w-14 h-14 rounded-xl bg-brand-sand-light flex items-center justify-center flex-shrink-0">
                      <ShoppingBag size={20} className="text-brand-dark/20" />
                    </div>
                  )}
                  <div className="flex-1 min-w-0">
                    <p className="text-brand-dark font-semibold text-sm">{item.name}</p>
                    {item.size && <p className="text-brand-dark/40 text-xs">{item.size}</p>}
                    <div className="flex items-center gap-1.5 mt-0.5">
                      <p className="text-brand-dark/50 text-xs">{unitPrice.toLocaleString("fr-MR")} MRU {t.suivi.perUnit}</p>
                      {isGros && (
                        <span className="bg-brand-yellow text-brand-dark text-[9px] font-bold px-1.5 py-0.5 rounded-full">
                          Prix gros ✓
                        </span>
                      )}
                    </div>
                  </div>
                  <div className="flex-shrink-0 text-right">
                    <p className="text-brand-dark font-bold text-sm">× {item.quantity}</p>
                    <p className="text-brand-dark/50 text-xs">{(unitPrice * item.quantity).toLocaleString("fr-MR")} MRU</p>
                    {isGros && (
                      <p className="text-brand-dark/30 text-[10px] line-through">{(item.price * item.quantity).toLocaleString("fr-MR")} MRU</p>
                    )}
                  </div>
                </div>
                );
              })}
            </div>
          </div>

          {/* Delivery + payment info */}
          <div className="border-t border-brand-dark/8 px-6 py-5 space-y-4 bg-brand-sand-light/30">
            <p className="text-brand-dark/40 text-xs font-bold uppercase tracking-wider">{t.suivi.deliveryPayment}</p>

            <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">

              {/* Phone */}
              <div className="flex items-start gap-2.5">
                <div className="w-8 h-8 rounded-lg bg-brand-dark/5 flex items-center justify-center flex-shrink-0">
                  <Phone size={14} className="text-brand-dark/50" />
                </div>
                <div>
                  <p className="text-brand-dark/40 text-xs">{t.suivi.phone}</p>
                  <p className="text-brand-dark font-semibold text-sm">{order.phone}</p>
                </div>
              </div>

              {/* Address */}
              <div className="flex items-start gap-2.5">
                <div className="w-8 h-8 rounded-lg bg-brand-dark/5 flex items-center justify-center flex-shrink-0">
                  <MapPin size={14} className="text-brand-dark/50" />
                </div>
                <div className="min-w-0">
                  <p className="text-brand-dark/40 text-xs">{t.suivi.deliveryLocation}</p>
                  <p className="text-brand-dark font-semibold text-sm leading-snug">{order.address || "—"}</p>
                </div>
              </div>

              {/* Payment method */}
              {order.payment_method && (
                <div className="flex items-start gap-2.5">
                  <div className="w-8 h-8 rounded-lg bg-brand-dark/5 flex items-center justify-center flex-shrink-0">
                    <CreditCard size={14} className="text-brand-dark/50" />
                  </div>
                  <div>
                    <p className="text-brand-dark/40 text-xs">{t.suivi.payment}</p>
                    <p className="text-brand-dark font-semibold text-sm capitalize">{order.payment_method}</p>
                  </div>
                </div>
              )}

              {/* Notes */}
              {order.notes && (
                <div className="flex items-start gap-2.5">
                  <div className="w-8 h-8 rounded-lg bg-brand-dark/5 flex items-center justify-center flex-shrink-0">
                    <Receipt size={14} className="text-brand-dark/50" />
                  </div>
                  <div className="min-w-0">
                    <p className="text-brand-dark/40 text-xs">{t.suivi.notes}</p>
                    <p className="text-brand-dark font-semibold text-sm">{order.notes}</p>
                  </div>
                </div>
              )}
            </div>

            {/* Payment screenshot */}
            {order.payment_screenshot && (
              <div>
                <p className="text-brand-dark/40 text-xs mb-2">{t.suivi.paymentScreenshot}</p>
                <button
                  type="button"
                  onClick={() => onOpenLightbox(order.payment_screenshot!)}
                  className="relative w-24 h-24 rounded-xl overflow-hidden border border-brand-dark/10 hover:border-brand-dark/30 transition-colors group block"
                >
                  <Image src={order.payment_screenshot} alt="Capture paiement" fill className="object-cover" />
                  <div className="absolute inset-0 bg-black/0 group-hover:bg-black/20 transition-colors flex items-center justify-center">
                    <MagnifyingGlassPlus size={20} className="text-white opacity-0 group-hover:opacity-100 transition-opacity" weight="bold" />
                  </div>
                </button>
              </div>
            )}
          </div>

          {/* Total footer */}
          <div className="border-t border-brand-dark/8 px-6 py-4 flex items-center justify-between">
            <p className="text-brand-dark/40 text-sm">{t.suivi.orderTotal}</p>
            <p className="text-brand-dark font-bold text-2xl" style={{ fontFamily: "var(--font-space,sans-serif)" }}>
              {total.toLocaleString("fr-MR")} <span className="text-base font-semibold text-brand-dark/50">MRU</span>
            </p>
          </div>

        </div>
      )}
    </div>
  );
}

/* ── Lightbox ── */
function Lightbox({ src, onClose, closeLabel }: { src: string; onClose: () => void; closeLabel: string }) {
  // Lock scroll + hide navbar
  useEffect(() => {
    const scrollY = window.scrollY;
    document.body.style.position = "fixed";
    document.body.style.top      = `-${scrollY}px`;
    document.body.style.width    = "100%";

    const navbar = document.querySelector("nav") as HTMLElement | null;
    if (navbar) navbar.style.display = "none";

    return () => {
      document.body.style.position = "";
      document.body.style.top      = "";
      document.body.style.width    = "";
      window.scrollTo(0, scrollY);
      if (navbar) navbar.style.display = "";
    };
  }, []);

  const content = (
    <div
      className="fixed inset-0 z-[9999] flex items-center justify-center p-6 backdrop-blur-md bg-black/70"
      style={{ position: "fixed", top: 0, left: 0, right: 0, bottom: 0, WebkitBackdropFilter: "blur(12px)" }}
      onClick={onClose}
    >
      {/* Close button — solid, clearly visible */}
      <button
        onClick={onClose}
        className="absolute top-4 right-4 flex items-center gap-2 bg-white text-brand-dark font-bold text-xs px-4 py-2 rounded-full shadow-lg hover:bg-white/90 transition-colors z-10"
      >
        <X size={14} weight="bold" /> {closeLabel}
      </button>

      <div onClick={e => e.stopPropagation()}>
        <Image
          src={src}
          alt="Capture de paiement"
          width={600}
          height={900}
          className="max-w-[88vw] max-h-[88vh] w-auto h-auto rounded-2xl object-contain shadow-2xl"
        />
      </div>
    </div>
  );

  return createPortal(content, document.body);
}

/* ── Toast notification ── */
interface Toast { id: number; text: string; color: string; }

function ToastBanner({ toasts, onDismiss }: { toasts: Toast[]; onDismiss: (id: number) => void }) {
  if (!toasts.length) return null;
  return createPortal(
    <div className="fixed top-4 left-1/2 -translate-x-1/2 z-[9998] flex flex-col gap-2 w-[calc(100%-2rem)] max-w-sm">
      {toasts.map(t => (
        <div key={t.id} className={`flex items-center justify-between gap-3 px-4 py-3 rounded-2xl shadow-xl text-white text-sm font-semibold ${t.color}`}>
          <span>{t.text}</span>
          <button onClick={() => onDismiss(t.id)} className="flex-shrink-0 opacity-70 hover:opacity-100">
            <X size={14} weight="bold" />
          </button>
        </div>
      ))}
    </div>,
    document.body
  );
}


/* ── Main list ── */
export default function OrderList({ orders: initialOrders }: { orders: Order[]; name: string }) {
  const { t } = useLanguage();
  const [orders,       setOrders]       = useState<Order[]>(initialOrders);
  const [showHistory,  setShowHistory]  = useState(false);
  const [lightboxSrc,  setLightboxSrc]  = useState<string | null>(null);
  const [toasts,       setToasts]       = useState<Toast[]>([]);

  const addToast = (text: string, color: string) => {
    const id = Date.now();
    setToasts(t => [...t, { id, text, color }]);
    setTimeout(() => setToasts(t => t.filter(x => x.id !== id)), 6000);
  };

  // Listen for status changes fired by the global OrderStatusPoller
  useEffect(() => {
    const handler = (e: Event) => {
      const { orderId, newStatus, msg, color } = (e as CustomEvent).detail;
      setOrders(prev => prev.map(o => o.id === orderId ? { ...o, status: newStatus } : o));
      addToast(msg, color);
    };
    window.addEventListener("order-status-change", handler);
    return () => window.removeEventListener("order-status-change", handler);
  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  if (orders.length === 0) {
    return (
      <div className="text-center py-24 bg-white border border-brand-dark/8 rounded-3xl">
        <div className="w-16 h-16 bg-brand-sand-light rounded-full flex items-center justify-center mx-auto mb-4">
          <ShoppingBag size={28} className="text-brand-dark/20" />
        </div>
        <p className="text-brand-dark/40 text-sm mb-6">{t.suivi.empty}</p>
        <Link href="/produits" className="bg-brand-dark text-brand-off-white font-bold px-6 py-3 rounded-full text-sm hover:bg-brand-dark/90 transition-colors">
          {t.suivi.viewProducts}
        </Link>
      </div>
    );
  }

  const [latest, ...history] = orders;

  return (
    <>
      <ToastBanner toasts={toasts} onDismiss={id => setToasts(prev => prev.filter(x => x.id !== id))} />
      {lightboxSrc && <Lightbox src={lightboxSrc} onClose={() => setLightboxSrc(null)} closeLabel={t.suivi.close} />}

      <div className="space-y-6">

        {/* Latest order — hero */}
        <div className="space-y-2">
          <p className="text-brand-dark/40 text-xs font-bold uppercase tracking-wider">
            {t.suivi.latestOrder}
          </p>
          <OrderCard order={latest} defaultOpen={true} onOpenLightbox={setLightboxSrc} />
        </div>

        {/* History */}
        {history.length > 0 && (
          <div className="space-y-3">
            <button
              onClick={() => setShowHistory(v => !v)}
              className="w-full py-3 border border-brand-dark/12 rounded-2xl text-brand-dark/50 text-sm font-semibold hover:bg-white hover:text-brand-dark transition-all flex items-center justify-center gap-2"
            >
              {showHistory
                ? t.suivi.hideHistory
                : `${t.suivi.showHistory} (${history.length} ${history.length > 1 ? t.suivi.orders : t.suivi.order})`
              }
              <CaretDown size={14} className={`transition-transform duration-200 ${showHistory ? "rotate-180" : ""}`} />
            </button>

            {showHistory && (
              <div className="space-y-3">
                {history.map(order => (
                  <OrderCard key={order.id} order={order} defaultOpen={false} onOpenLightbox={setLightboxSrc} />
                ))}
              </div>
            )}
          </div>
        )}
      </div>
    </>
  );
}
