'use client';
import { useState, useEffect, useCallback } from 'react';
import { useParams } from 'next/navigation';
import Link from 'next/link';
import type { Order, OrderState, Product, OrderHistoryEvent } from '@/types';
import { ordersApi, productsApi, settingsApi } from '@/lib/api-client';

const STATE_LABELS: Record<OrderState, string> = {
  PENDING: 'Pendiente',
  AWAITING_PAYMENT: 'Esperando pago',
  PAID: 'Pagado',
  PROCESSING: 'Procesando',
  SHIPPED: 'Enviado',
  DELIVERED: 'Entregado',
  CANCELLED: 'Cancelado',
  REFUNDED: 'Reembolsado',
  PARTIALLY_REFUNDED: 'Reembolso parcial',
};

const STATE_COLORS: Record<OrderState, string> = {
  PENDING: 'bg-amber-100 text-amber-800',
  AWAITING_PAYMENT: 'bg-orange-100 text-orange-800',
  PAID: 'bg-blue-100 text-blue-800',
  PROCESSING: 'bg-indigo-100 text-indigo-800',
  SHIPPED: 'bg-purple-100 text-purple-800',
  DELIVERED: 'bg-green-100 text-green-800',
  CANCELLED: 'bg-red-100 text-red-800',
  REFUNDED: 'bg-purple-100 text-purple-800',
  PARTIALLY_REFUNDED: 'bg-pink-100 text-pink-800',
};

const ALLOWED_TRANSITIONS: Record<OrderState, OrderState[]> = {
  PENDING: ['AWAITING_PAYMENT', 'CANCELLED'],
  AWAITING_PAYMENT: ['PAID', 'CANCELLED'],
  PAID: ['PROCESSING', 'CANCELLED', 'REFUNDED'],
  PROCESSING: ['PAID', 'SHIPPED', 'CANCELLED', 'REFUNDED'],
  SHIPPED: ['PROCESSING', 'DELIVERED', 'PARTIALLY_REFUNDED'],
  DELIVERED: ['SHIPPED', 'PARTIALLY_REFUNDED'],
  CANCELLED: [],
  REFUNDED: [],
  PARTIALLY_REFUNDED: [],
};

// F-125: labels por par (origen, destino) — mismo target puede tener label distinto
// según venga de un estado anterior (avance) o posterior (reversión).
const ACTION_LABELS_BY_TRANSITION: Record<string, string> = {
  'PENDING>AWAITING_PAYMENT': 'Pasar a Esperando pago',
  'PENDING>CANCELLED': 'Cancelar pedido',
  'AWAITING_PAYMENT>PAID': 'Marcar como Pagado',
  'AWAITING_PAYMENT>CANCELLED': 'Cancelar pedido',
  'PAID>PROCESSING': 'Procesar pedido',
  'PAID>CANCELLED': 'Cancelar pedido',
  'PAID>REFUNDED': 'Reembolsar',
  'PROCESSING>PAID': 'Revertir a Pagado',
  'PROCESSING>SHIPPED': 'Marcar como Enviado',
  'PROCESSING>CANCELLED': 'Cancelar pedido',
  'PROCESSING>REFUNDED': 'Reembolsar',
  'SHIPPED>PROCESSING': 'Revertir a En preparación',
  'SHIPPED>DELIVERED': 'Marcar como Entregado',
  'SHIPPED>PARTIALLY_REFUNDED': 'Reembolso parcial',
  'DELIVERED>SHIPPED': 'Revertir a Enviado',
  'DELIVERED>PARTIALLY_REFUNDED': 'Reembolso parcial',
};

function actionLabel(from: OrderState, to: OrderState): string {
  return ACTION_LABELS_BY_TRANSITION[`${from}>${to}`] ?? `Pasar a ${to}`;
}

interface DraftItem {
  variantId: string;
  productId: string;
  sku: string;
  name: string;
  quantity: number;
}

function formatPrice(cents: number) {
  return `€${(cents / 100).toFixed(2)}`;
}

export default function OrderDetailPage() {
  const { id } = useParams<{ id: string }>();
  const [order, setOrder] = useState<Order | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState('');
  const [transitioning, setTransitioning] = useState(false);
  const [showConfirm, setShowConfirm] = useState<OrderState | null>(null);
  const [confirmReason, setConfirmReason] = useState('');
  const [trackingInput, setTrackingInput] = useState('');
  const [courierInput, setCourierInput] = useState('');
  const [couriers, setCouriers] = useState<string[]>([]);
  const [notification, setNotification] = useState<{ ok: boolean; message: string } | null>(null);

  // Edición de artículos
  const [editing, setEditing] = useState(false);
  const [draftItems, setDraftItems] = useState<DraftItem[]>([]);
  const [savingItems, setSavingItems] = useState(false);
  const [itemsError, setItemsError] = useState('');
  const [productQuery, setProductQuery] = useState('');
  const [searchResults, setSearchResults] = useState<Product[]>([]);
  const [searching, setSearching] = useState(false);
  const [addingProductId, setAddingProductId] = useState<string | null>(null);
  const [addingVariants, setAddingVariants] = useState<{ id: string; sku: string }[]>([]);

  // Envío e historial (F-111)
  const [history, setHistory] = useState<OrderHistoryEvent[]>([]);
  const [shippingTracking, setShippingTracking] = useState('');
  const [shippingCourier, setShippingCourier] = useState('');
  const [shippingNote, setShippingNote] = useState('');
  const [savingShipping, setSavingShipping] = useState(false);
  const [shippingMsg, setShippingMsg] = useState<{ ok: boolean; text: string } | null>(null);

  const loadHistory = useCallback(async () => {
    try {
      const result = await ordersApi.history(id);
      setHistory(result.items ?? []);
    } catch {
      setHistory([]);
    }
  }, [id]);

  const load = useCallback(async () => {
    setLoading(true);
    setError('');
    try {
      const data = await ordersApi.get(id);
      setOrder(data);
      setShippingTracking(data.trackingNumber ?? '');
      setShippingCourier(data.courier ?? '');
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Error al cargar');
    } finally {
      setLoading(false);
    }
  }, [id]);

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

  useEffect(() => {
    settingsApi
      .get()
      .then((settings) => setCouriers(settings.couriers ?? []))
      .catch(() => setCouriers([]));
  }, []);

  const handleTransition = async (nextState: OrderState) => {
    if (nextState === 'SHIPPED' && (!trackingInput.trim() || !courierInput.trim())) return;
    setTransitioning(true);
    try {
      const updated = await ordersApi.transition(
        id,
        nextState,
        nextState === 'SHIPPED' ? trackingInput : undefined,
        nextState === 'SHIPPED' ? courierInput : undefined,
      );
      setOrder(updated);
      setShippingTracking(updated.trackingNumber ?? '');
      setShippingCourier(updated.courier ?? '');
      setShowConfirm(null);
      setConfirmReason('');
      setTrackingInput('');
      setCourierInput('');
      loadHistory();
      if (updated.notified) {
        setNotification({ ok: true, message: 'Cliente notificado por email.' });
      } else {
        setNotification({
          ok: false,
          message: updated.notificationError || 'No se pudo notificar al cliente por email.',
        });
      }
    } catch (err) {
      alert(err instanceof Error ? err.message : 'Error al cambiar estado');
    } finally {
      setTransitioning(false);
    }
  };

  const startEditing = () => {
    if (!order) return;
    setDraftItems(
      order.items.map((item) => ({
        variantId: item.variantId,
        productId: item.productId,
        sku: item.sku,
        name: item.name,
        quantity: item.quantity,
      })),
    );
    setItemsError('');
    setEditing(true);
  };

  const updateDraftQuantity = (variantId: string, quantity: number) => {
    setDraftItems((prev) =>
      prev.map((item) =>
        item.variantId === variantId
          ? { ...item, quantity: Math.max(1, Math.min(999, quantity || 1)) }
          : item,
      ),
    );
  };

  const removeDraftItem = (variantId: string) => {
    setDraftItems((prev) => prev.filter((item) => item.variantId !== variantId));
  };

  const searchProducts = useCallback(async (query: string) => {
    setProductQuery(query);
    if (query.trim().length < 2) {
      setSearchResults([]);
      return;
    }
    setSearching(true);
    try {
      const result = await productsApi.list({ q: query.trim(), limit: 8 });
      setSearchResults(result.items ?? []);
    } catch {
      setSearchResults([]);
    } finally {
      setSearching(false);
    }
  }, []);

  const pickProductForAdd = async (product: Product) => {
    setAddingProductId(product.id);
    setAddingVariants([]);
    try {
      const result = await productsApi.getVariants(product.id);
      const variants = (result.items ?? []).map((variant) => ({ id: variant.id, sku: variant.sku }));
      if (variants.length === 1) {
        addDraftItem(variants[0].id, product.id, variants[0].sku, product.name);
        setAddingProductId(null);
      } else {
        setAddingVariants(variants);
      }
    } catch (err) {
      setItemsError(err instanceof Error ? err.message : 'Error al cargar variantes');
      setAddingProductId(null);
    }
  };

  const addDraftItem = (variantId: string, productId: string, sku: string, name: string) => {
    setDraftItems((prev) => {
      const existing = prev.find((item) => item.variantId === variantId);
      if (existing) {
        return prev.map((item) =>
          item.variantId === variantId ? { ...item, quantity: Math.min(999, item.quantity + 1) } : item,
        );
      }
      return [...prev, { variantId, productId, sku, name, quantity: 1 }];
    });
    setSearchResults([]);
    setProductQuery('');
    setAddingProductId(null);
    setAddingVariants([]);
    setItemsError('');
  };

  const saveItems = async () => {
    if (draftItems.length === 0) {
      setItemsError('El pedido debe tener al menos un artículo');
      return;
    }
    setSavingItems(true);
    setItemsError('');
    try {
      const updated = await ordersApi.editItems(
        id,
        draftItems.map((item) => ({ variantId: item.variantId, quantity: item.quantity })),
      );
      setOrder(updated);
      setEditing(false);
    } catch (err) {
      setItemsError(err instanceof Error ? err.message : 'Error al guardar artículos');
    } finally {
      setSavingItems(false);
    }
  };

  const handleSaveShipping = async () => {
    const tracking = shippingTracking.trim();
    if (!tracking) {
      setShippingMsg({ ok: false, text: 'Indica un número de seguimiento' });
      return;
    }
    setSavingShipping(true);
    setShippingMsg(null);
    try {
      const updated = await ordersApi.updateShipping(id, tracking, shippingNote, shippingCourier);
      setOrder(updated);
      setShippingTracking(updated.trackingNumber ?? tracking);
      setShippingCourier(updated.courier ?? '');
      setShippingNote('');
      setShippingMsg({ ok: true, text: 'Envío actualizado y registrado en el historial' });
      loadHistory();
      setTimeout(() => setShippingMsg(null), 4000);
    } catch (err) {
      setShippingMsg({ ok: false, text: err instanceof Error ? err.message : 'Error al guardar envío' });
    } finally {
      setSavingShipping(false);
    }
  };

  if (loading) {
    return (
      <div className="flex items-center justify-center min-h-64">
        <div className="text-gray-400">Cargando...</div>
      </div>
    );
  }

  if (error || !order) {
    return (
      <div>
        <p className="text-red-600">{error || 'Pedido no encontrado'}</p>
        <button onClick={load} className="text-sm text-[#2D6A4F] hover:underline mt-2">
          Reintentar
        </button>
      </div>
    );
  }

  const currentState = order.state as OrderState;
  const allowed = ALLOWED_TRANSITIONS[currentState] ?? [];
  const itemsEditable = currentState !== 'CANCELLED' && currentState !== 'REFUNDED';

  return (
    <div className="space-y-6">
      {/* Back */}
      <Link href="/orders" className="inline-flex items-center gap-1 text-sm text-gray-500 hover:text-gray-700">
        ← Volver a pedidos
      </Link>

      {/* Header */}
      <div className="flex items-start justify-between">
        <div>
          <h1 className="text-2xl font-bold text-gray-900 font-mono">#{order.id.slice(0, 8)}</h1>
          <p className="text-sm text-gray-500 mt-1">
            {new Date(order.createdAt).toLocaleString('es-ES', {
              dateStyle: 'long',
              timeStyle: 'short',
            })}
          </p>
        </div>
        <span className={`inline-flex items-center gap-1.5 px-3 py-1.5 rounded-full text-sm font-medium ${STATE_COLORS[currentState]}`}>
          <span className="w-2 h-2 rounded-full bg-current" />
          {STATE_LABELS[currentState]}
        </span>
      </div>

      {/* Notification result */}
      {notification && (
        <div
          className={`flex items-center justify-between px-4 py-3 rounded-xl text-sm border ${
            notification.ok
              ? 'bg-green-50 border-green-200 text-green-800'
              : 'bg-amber-50 border-amber-200 text-amber-800'
          }`}
        >
          <span>{notification.message}</span>
          <button onClick={() => setNotification(null)} className="ml-4 font-bold opacity-60 hover:opacity-100">✕</button>
        </div>
      )}

      <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
        {/* Main content */}
        <div className="lg:col-span-2 space-y-6">
          {/* Actions */}
          {allowed.length > 0 && (
            <div className="bg-white border border-gray-200 rounded-xl p-6">
              <h2 className="font-bold text-gray-900 mb-4">Acciones</h2>
              <div className="flex flex-wrap gap-2">
                {allowed.map((next) => (
                  <button
                    key={next}
                    onClick={() => {
                      setShowConfirm(next);
                      setNotification(null);
                      if (next === 'SHIPPED') setCourierInput((prev) => prev || couriers[0] || '');
                    }}
                    disabled={transitioning}
                    className="px-4 py-2 bg-[#2D6A4F] hover:bg-[#1B4332] disabled:opacity-50 text-white text-sm font-semibold rounded-xl transition-colors"
                  >
                    {actionLabel(currentState, next)}
                  </button>
                ))}
              </div>
            </div>
          )}

          {/* Order items */}
          <div className="bg-white border border-gray-200 rounded-xl p-6">
            <div className="flex items-center justify-between mb-4">
              <h2 className="font-bold text-gray-900">Productos</h2>
              {itemsEditable && !editing && (
                <button
                  onClick={startEditing}
                  className="px-3 py-1.5 text-sm font-semibold text-[#2D6A4F] border border-[#2D6A4F] rounded-lg hover:bg-[#2D6A4F]/5 transition-colors"
                >
                  ✏️ Editar artículos
                </button>
              )}
            </div>

            {!editing ? (
              <div className="space-y-3">
                {order.items.map((item) => (
                  <div key={item.id} className="flex justify-between items-start py-2 border-b border-gray-50 last:border-0">
                    <div className="flex-1 min-w-0">
                      <p className="text-sm font-medium text-gray-900">{item.name}</p>
                      <p className="text-xs text-gray-400">
                        {item.quantity} × {formatPrice(item.unitPriceCents)}
                        {item.discountCents > 0 && ` (-${formatPrice(item.discountCents)})`}
                      </p>
                    </div>
                    <p className="text-sm font-bold text-gray-900 ml-4">
                      {formatPrice((item.unitPriceCents - item.discountCents) * item.quantity)}
                    </p>
                  </div>
                ))}
              </div>
            ) : (
              <div className="space-y-4">
                <div className="space-y-3">
                  {draftItems.map((item) => (
                    <div key={item.variantId} className="flex items-center gap-3 py-2 border-b border-gray-50 last:border-0">
                      <div className="flex-1 min-w-0">
                        <p className="text-sm font-medium text-gray-900 truncate">{item.name}</p>
                        <p className="text-xs text-gray-400 font-mono">{item.sku}</p>
                      </div>
                      <input
                        type="number"
                        min={1}
                        max={999}
                        value={item.quantity}
                        onChange={(e) => updateDraftQuantity(item.variantId, Number(e.target.value))}
                        className="w-20 px-2 py-1.5 border border-gray-300 rounded-lg text-sm text-right focus:ring-2 focus:ring-[#2D6A4F] outline-none"
                      />
                      <button
                        onClick={() => removeDraftItem(item.variantId)}
                        disabled={draftItems.length === 1}
                        title="Quitar artículo"
                        className="p-1.5 text-red-500 hover:bg-red-50 rounded-lg disabled:opacity-30 disabled:cursor-not-allowed"
                      >
                        🗑️
                      </button>
                    </div>
                  ))}
                  {draftItems.length === 0 && (
                    <p className="text-sm text-gray-400 py-2">Sin artículos. Añade al menos uno.</p>
                  )}
                </div>

                {/* Add product */}
                <div className="border-t border-gray-100 pt-4">
                  <label className="text-xs font-semibold text-gray-500 uppercase tracking-wide">Añadir producto</label>
                  <input
                    type="search"
                    value={productQuery}
                    onChange={(e) => { searchProducts(e.target.value); }}
                    placeholder="Buscar por nombre o SKU (mín. 2 caracteres)…"
                    className="mt-1 w-full px-3 py-2 border border-gray-300 rounded-xl text-sm focus:ring-2 focus:ring-[#2D6A4F] outline-none"
                  />
                  {searching && <p className="text-xs text-gray-400 mt-2">Buscando…</p>}
                  {!searching && searchResults.length > 0 && (
                    <ul className="mt-2 border border-gray-200 rounded-xl divide-y divide-gray-100 max-h-56 overflow-auto">
                      {searchResults.map((product) => (
                        <li key={product.id}>
                          {addingProductId === product.id && addingVariants.length > 0 ? (
                            <div className="px-3 py-2">
                              <p className="text-sm font-medium text-gray-900">{product.name}</p>
                              <div className="flex flex-wrap gap-2 mt-1">
                                {addingVariants.map((variant) => (
                                  <button
                                    key={variant.id}
                                    onClick={() => addDraftItem(variant.id, product.id, variant.sku, product.name)}
                                    className="px-2 py-1 text-xs font-mono bg-gray-100 hover:bg-[#2D6A4F] hover:text-white rounded-lg transition-colors"
                                  >
                                    {variant.sku}
                                  </button>
                                ))}
                              </div>
                            </div>
                          ) : (
                            <button
                              onClick={() => { pickProductForAdd(product); }}
                              disabled={addingProductId !== null}
                              className="w-full text-left px-3 py-2 text-sm text-gray-800 hover:bg-gray-50 disabled:opacity-50"
                            >
                              {product.name}
                            </button>
                          )}
                        </li>
                      ))}
                    </ul>
                  )}
                </div>

                {itemsError && <p className="text-sm text-red-600">{itemsError}</p>}

                <div className="flex gap-3 justify-end border-t border-gray-100 pt-4">
                  <button
                    onClick={() => { setEditing(false); setItemsError(''); }}
                    disabled={savingItems}
                    className="px-4 py-2 text-sm text-gray-600 hover:text-gray-900 transition-colors"
                  >
                    Cancelar
                  </button>
                  <button
                    onClick={saveItems}
                    disabled={savingItems || draftItems.length === 0}
                    className="px-4 py-2 bg-[#2D6A4F] hover:bg-[#1B4332] disabled:opacity-50 text-white text-sm font-semibold rounded-xl transition-colors"
                  >
                    {savingItems ? 'Guardando…' : 'Guardar artículos'}
                  </button>
                </div>
                <p className="text-xs text-gray-400">
                  Los precios e IVA se recalculan con las tarifas vigentes al guardar.
                </p>
              </div>
            )}
          </div>
        </div>

        {/* Sidebar */}
        <div className="space-y-6">
          {/* F-140: Customer + Addresses + Payment */}
          <div className="bg-white border border-gray-200 rounded-xl p-6">
            <h2 className="font-bold text-gray-900 mb-4">Cliente</h2>
            <dl className="space-y-2 text-sm">
              <div>
                <dt className="text-xs font-semibold uppercase tracking-wide text-gray-400">Nombre</dt>
                <dd className="font-medium text-gray-900">{order.customerName || order.shippingAddress?.recipientName || 'No registrado'}</dd>
              </div>
              <div>
                <dt className="text-xs font-semibold uppercase tracking-wide text-gray-400">Email</dt>
                <dd className={order.email ? 'text-gray-700' : 'text-amber-700'}>{order.email || 'No registrado'}</dd>
              </div>
              <div>
                <dt className="text-xs font-semibold uppercase tracking-wide text-gray-400">Teléfono</dt>
                <dd className="text-gray-700">{order.customerPhone || order.phone || 'No registrado'}</dd>
              </div>
            </dl>
          </div>

          <div className="bg-white border border-gray-200 rounded-xl p-6">
            <h2 className="font-bold text-gray-900 mb-4">Dirección de envío</h2>
            {order.shippingAddress ? (
              <div className="space-y-1 text-sm text-gray-700">
                <p className="font-medium">{order.shippingAddress.recipientName}</p>
                <p>{order.shippingAddress.street}</p>
                <p>{order.shippingAddress.postalCode} {order.shippingAddress.city}</p>
                <p>{order.shippingAddress.country}</p>
              </div>
            ) : (
              <p className="text-sm text-amber-700">No registrada para este pedido.</p>
            )}
          </div>

          <div className="bg-white border border-gray-200 rounded-xl p-6">
            <h2 className="font-bold text-gray-900 mb-4">Dirección de facturación</h2>
            {order.billingAddress ? (
              <div className="space-y-1 text-sm text-gray-700">
                <p className="font-medium">{order.billingAddress.recipientName}</p>
                <p>{order.billingAddress.street}</p>
                <p>{order.billingAddress.postalCode} {order.billingAddress.city}</p>
                <p>{order.billingAddress.country}</p>
              </div>
            ) : (
              <p className="text-sm text-gray-500">No registrada; consultar la dirección de envío.</p>
            )}
          </div>

          <div className="bg-white border border-gray-200 rounded-xl p-6">
            <h2 className="font-bold text-gray-900 mb-4">Pago</h2>
            {order.payment ? (
              <div className="space-y-1 text-sm">
                <div className="flex justify-between">
                  <span className="text-gray-600">Método</span>
                  <span className="font-medium text-gray-900 capitalize">{order.payment.provider.replace(/_/g, ' ')}</span>
                </div>
                {order.payment.last4 && (
                  <div className="flex justify-between">
                    <span className="text-gray-600">Últimos 4</span>
                    <span className="font-mono font-medium text-gray-900">····{order.payment.last4}</span>
                  </div>
                )}
                <div className="flex justify-between">
                  <span className="text-gray-600">Importe</span>
                  <span className="font-medium text-gray-900">{formatPrice(order.payment.amountCents)}</span>
                </div>
                <div className="flex justify-between items-center">
                  <span className="text-gray-600">Estado</span>
                  <span className={`inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium ${
                    order.payment.status === 'succeeded' ? 'bg-green-100 text-green-800' :
                    order.payment.status === 'failed' ? 'bg-red-100 text-red-800' :
                    order.payment.status === 'refunded' ? 'bg-amber-100 text-amber-800' :
                    'bg-gray-100 text-gray-800'
                  }`}>
                    {order.payment.status}
                  </span>
                </div>
              </div>
            ) : (
              <p className="text-sm text-gray-500">No hay una transacción de pago registrada para este pedido.</p>
            )}
          </div>
          {/* F-140 already shown above — keep existing Envío section */}
          {/* Envío */}
          <div className="bg-white border border-gray-200 rounded-xl p-6">
            <h2 className="font-bold text-gray-900 mb-4">Envío</h2>
            <label className="block text-xs font-semibold text-gray-500 uppercase tracking-wide mb-1">
              Transportista
            </label>
            <select
              value={shippingCourier}
              onChange={(e) => setShippingCourier(e.target.value)}
              className="mb-2 w-full px-3 py-2 border border-gray-300 rounded-xl text-sm focus:ring-2 focus:ring-[#2D6A4F] outline-none bg-white"
            >
              <option value="">Sin transportista</option>
              {couriers.map((courier) => (
                <option key={courier} value={courier}>{courier}</option>
              ))}
              {shippingCourier && !couriers.includes(shippingCourier) && (
                <option value={shippingCourier}>{shippingCourier}</option>
              )}
            </select>
            <label className="block text-xs font-semibold text-gray-500 uppercase tracking-wide mb-1">
              Número de seguimiento
            </label>
            <input
              type="text"
              value={shippingTracking}
              onChange={(e) => setShippingTracking(e.target.value)}
              placeholder="p. ej. PQ123456789ES"
              maxLength={120}
              className="w-full px-3 py-2 border border-gray-300 rounded-xl text-sm font-mono focus:ring-2 focus:ring-[#2D6A4F] outline-none"
            />
            <input
              type="text"
              value={shippingNote}
              onChange={(e) => setShippingNote(e.target.value)}
              placeholder="Nota interna (opcional)"
              maxLength={500}
              className="mt-2 w-full px-3 py-2 border border-gray-300 rounded-xl text-sm focus:ring-2 focus:ring-[#2D6A4F] outline-none"
            />
            <button
              onClick={handleSaveShipping}
              disabled={savingShipping || !shippingTracking.trim()}
              className="mt-3 w-full px-4 py-2 bg-[#2D6A4F] hover:bg-[#1B4332] disabled:opacity-50 text-white text-sm font-semibold rounded-xl transition-colors"
            >
              {savingShipping ? 'Guardando…' : 'Guardar envío'}
            </button>
            {shippingMsg && (
              <p className={`mt-2 text-xs ${shippingMsg.ok ? 'text-green-600' : 'text-red-600'}`}>{shippingMsg.text}</p>
            )}
            <p className="mt-2 text-xs text-gray-400">Cada cambio queda registrado en el historial del pedido.</p>
          </div>

          {/* Totals */}
          <div className="bg-white border border-gray-200 rounded-xl p-6">
            <h2 className="font-bold text-gray-900 mb-4">Resumen</h2>
            <div className="space-y-2 text-sm">
              <div className="flex justify-between">
                <span className="text-gray-600">Subtotal</span>
                <span className="font-medium">{formatPrice(order.subtotalCents)}</span>
              </div>
              {order.discountCents > 0 && (
                <div className="flex justify-between">
                  <span className="text-gray-600">Descuento</span>
                  <span className="font-medium text-green-600">-{formatPrice(order.discountCents)}</span>
                </div>
              )}
              <div className="flex justify-between">
                <span className="text-gray-600">IVA</span>
                <span className="font-medium">{formatPrice(order.taxCents)}</span>
              </div>
              <div className="border-t border-gray-200 pt-2 mt-2 flex justify-between items-center">
                <span className="font-bold text-gray-900">Total</span>
                <span className="text-xl font-bold text-[#2D6A4F]">{formatPrice(order.totalCents)}</span>
              </div>
            </div>
            {order.trackingNumber && (
              <div className="mt-4 border-t border-gray-100 pt-3">
                <p className="text-xs font-semibold text-gray-500 uppercase tracking-wide">Seguimiento</p>
                <p className="text-sm font-mono text-gray-900 mt-1">{order.trackingNumber}</p>
              </div>
            )}
          </div>

          {/* Timeline */}
          <div className="bg-white border border-gray-200 rounded-xl p-6">
            <h2 className="font-bold text-gray-900 mb-4">Historial</h2>
            <div className="space-y-3">
              <div className="flex gap-3">
                <div className="w-2 h-2 rounded-full bg-[#2D6A4F] mt-1.5 flex-shrink-0" />
                <div>
                  <p className="text-sm font-medium text-gray-900">{STATE_LABELS[currentState]}</p>
                  <p className="text-xs text-gray-400">
                    {new Date(order.createdAt).toLocaleString('es-ES')}
                  </p>
                </div>
              </div>
              {[...history].reverse().map((event) => (
                <div key={event.id} className="flex gap-3">
                  <div className={`w-2 h-2 rounded-full mt-1.5 flex-shrink-0 ${event.eventType === 'SHIPPING_UPDATE' ? 'bg-purple-400' : 'bg-blue-400'}`} />
                  <div className="min-w-0">
                    <p className="text-sm text-gray-800 break-words">{event.message}</p>
                    <p className="text-xs text-gray-400">
                      {new Date(event.createdAt).toLocaleString('es-ES')}
                      {event.actorEmail ? ` · ${event.actorEmail}` : ''}
                    </p>
                  </div>
                </div>
              ))}
              {history.length === 0 && (
                <p className="text-xs text-gray-400">Sin eventos registrados todavía.</p>
              )}
            </div>
          </div>
        </div>
      </div>

      {/* Confirmation Modal */}
      {showConfirm && (
        <div className="fixed inset-0 bg-black/40 flex items-center justify-center z-50 p-4">
          <div className="bg-white rounded-2xl p-6 max-w-md w-full shadow-xl">
            <h3 className="text-lg font-bold text-gray-900 mb-2">
              Confirmar cambio de estado
            </h3>
            <p className="text-sm text-gray-600 mb-4">
              ¿{actionLabel(currentState, showConfirm)}? Se notificará al cliente por email.
            </p>
            {showConfirm === 'SHIPPED' && (
              <div className="mb-4">
                <label className="block text-sm font-medium text-gray-700 mb-1">
                  Transportista <span className="text-red-500">*</span>
                </label>
                <select
                  value={courierInput}
                  onChange={(e) => setCourierInput(e.target.value)}
                  className="w-full px-3 py-2 border border-gray-300 rounded-xl text-sm focus:ring-2 focus:ring-[#2D6A4F] outline-none bg-white mb-3"
                >
                  <option value="">Selecciona transportista</option>
                  {couriers.map((courier) => (
                    <option key={courier} value={courier}>{courier}</option>
                  ))}
                </select>
                {couriers.length === 0 && (
                  <p className="text-xs text-amber-600 mb-2">
                    No hay transportistas configurados. Añádelos en Ajustes → Transportistas.
                  </p>
                )}
                <label className="block text-sm font-medium text-gray-700 mb-1">
                  Número de seguimiento <span className="text-red-500">*</span>
                </label>
                <input
                  type="text"
                  value={trackingInput}
                  onChange={(e) => setTrackingInput(e.target.value)}
                  placeholder="p. ej. PQ123456789ES"
                  maxLength={120}
                  className="w-full px-3 py-2 border border-gray-300 rounded-xl text-sm focus:ring-2 focus:ring-[#2D6A4F] outline-none"
                />
              </div>
            )}
            {(showConfirm === 'CANCELLED' || showConfirm === 'REFUNDED') && (
              <textarea
                value={confirmReason}
                onChange={(e) => setConfirmReason(e.target.value)}
                placeholder="Motivo (opcional)"
                rows={2}
                className="w-full px-3 py-2 border border-gray-300 rounded-xl text-sm focus:ring-2 focus:ring-[#2D6A4F] outline-none mb-4 resize-none"
              />
            )}
            <div className="flex gap-3 justify-end">
              <button
                onClick={() => { setShowConfirm(null); setConfirmReason(''); setTrackingInput(''); setCourierInput(''); }}
                className="px-4 py-2 text-sm text-gray-600 hover:text-gray-900 transition-colors"
              >
                Cancelar
              </button>
              <button
                onClick={() => handleTransition(showConfirm)}
                disabled={transitioning || (showConfirm === 'SHIPPED' && (!trackingInput.trim() || !courierInput.trim()))}
                className="px-4 py-2 bg-[#2D6A4F] hover:bg-[#1B4332] disabled:opacity-50 text-white text-sm font-semibold rounded-xl transition-colors"
              >
                {transitioning ? 'Guardando...' : 'Confirmar'}
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}
