"use client";

import { useCallback, useEffect, useState } from "react";
import Link from "next/link";
import { ExternalLink, Package } from "lucide-react";
import { AccountSection } from "@/components/account/AccountSection";
import { formatCop } from "@/data/products";
import {
  fetchMyOrders,
  type CustomerOrder,
} from "@/lib/customer-orders";

const STATUS_LABEL: Record<string, string> = {
  por_alistar: "Por alistar",
  alistado: "Alistado · preparando envío",
  despachado: "Despachado",
  cancelado: "Cancelado",
};

const STATUS_HINT: Record<string, string> = {
  por_alistar: "Recibimos tu pago. Estamos preparando tu pedido.",
  alistado: "Tu pedido está empacado y listo para generar guía.",
  despachado: "Tu pedido ya salió. Puedes seguir la guía abajo.",
  cancelado: "Este pedido fue cancelado.",
};

export default function OrdersPage() {
  return (
    <AccountSection title="Mis pedidos" wide>
      <OrdersList />
    </AccountSection>
  );
}

function OrdersList() {
  const [orders, setOrders] = useState<CustomerOrder[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  const load = useCallback(async () => {
    setLoading(true);
    setError(null);
    try {
      const list = await fetchMyOrders();
      setOrders(list);
    } catch (e) {
      setError(
        e instanceof Error
          ? e.message
          : "No se pudieron cargar tus pedidos."
      );
    } finally {
      setLoading(false);
    }
  }, []);

  useEffect(() => {
    void load();
  }, [load]);

  if (loading) {
    return <p>Cargando tus pedidos…</p>;
  }

  if (error) {
    return (
      <div className="space-y-3">
        <p className="text-red-700">{error}</p>
        <button type="button" className="ot-btn ot-btn-ghost" onClick={() => void load()}>
          Reintentar
        </button>
      </div>
    );
  }

  if (!orders.length) {
    return (
      <div className="space-y-4">
        <p>Aún no tienes pedidos en OLD TENNIS.</p>
        <Link href="/shop" className="ot-btn ot-btn-ghost inline-flex">
          Ir al catálogo
        </Link>
      </div>
    );
  }

  return (
    <div className="space-y-4">
      {orders.map((order) => {
        const label =
          STATUS_LABEL[order.fulfillment_status] || order.fulfillment_status;
        const hint =
          STATUS_HINT[order.fulfillment_status] ||
          "Te avisaremos cuando haya novedades.";
        const canTrack =
          order.fulfillment_status === "despachado" &&
          Boolean(order.shipping_guide);

        return (
          <article
            key={order.id}
            className="border border-black/10 bg-white p-4 sm:p-5 space-y-3"
          >
            <div className="flex flex-wrap items-start justify-between gap-2">
              <div>
                <h2 className="font-serif text-2xl text-ot-ink leading-tight">
                  Pedido #{order.display_id}
                </h2>
                <p className="text-xs text-ot-muted mt-1">
                  {order.created_at
                    ? new Date(order.created_at).toLocaleString("es-CO")
                    : ""}
                  {" · "}
                  {formatCop(order.total)}
                </p>
              </div>
              <span className="text-[10px] tracking-[0.14em] uppercase border border-ot-gold text-ot-green px-2.5 py-1">
                {label}
              </span>
            </div>

            <p className="text-sm text-ot-ink/75 leading-relaxed">{hint}</p>

            <ul className="space-y-2">
              {order.items.map((item) => (
                <li key={item.id} className="flex gap-3 text-sm">
                  <div className="w-12 h-14 shrink-0 bg-ot-cream overflow-hidden">
                    {item.thumbnail ? (
                      // eslint-disable-next-line @next/next/no-img-element
                      <img
                        src={item.thumbnail}
                        alt=""
                        className="h-full w-full object-cover object-top"
                      />
                    ) : (
                      <span className="grid place-items-center h-full text-ot-muted">
                        <Package size={16} />
                      </span>
                    )}
                  </div>
                  <div className="min-w-0">
                    <p className="text-ot-ink leading-snug">{item.title}</p>
                    <p className="text-xs text-ot-muted mt-0.5">
                      {item.quantity}×
                      {item.variant_title ? ` · ${item.variant_title}` : ""}
                    </p>
                  </div>
                </li>
              ))}
            </ul>

            {canTrack ? (
              <div className="border-t border-black/10 pt-3 space-y-2">
                <p className="text-sm text-ot-ink">
                  Guía: <strong className="font-mono">{order.shipping_guide}</strong>
                  {order.shipping_carrier
                    ? ` · ${order.shipping_carrier}`
                    : ""}
                </p>
                {order.shipping_tracking_url ? (
                  <a
                    href={order.shipping_tracking_url}
                    target="_blank"
                    rel="noreferrer"
                    className="ot-btn inline-flex items-center gap-2 !py-2.5"
                  >
                    Seguir tu pedido
                    <ExternalLink size={14} />
                  </a>
                ) : null}
              </div>
            ) : order.fulfillment_status === "despachado" ? (
              <p className="text-xs text-ot-muted border-t border-black/10 pt-3">
                Despachado. La guía aparecerá aquí en cuanto el equipo la
                registre.
              </p>
            ) : null}
          </article>
        );
      })}
    </div>
  );
}
