'use client';

/**
 * ============================================
 * ORDER DETAIL PAGE
 * ============================================
 * Equivalent to: account/order/detail.html.twig in Shopware
 */

import { useState, useEffect, useCallback } from 'react';
import { useParams, useRouter } from 'next/navigation';
import Link from 'next/link';
import Image from 'next/image';
import { useAuth } from '@/lib/auth-context';
import AccountNav from '@/components/layout/AccountNav';
import OrderActions from '@/components/account/OrderActions';
import { getOrder, formatPrice, getActiveTransaction, Order } from '@/lib/shopware-api';

const STATE_COLORS: Record<string, string> = {
  open: 'bg-yellow-100 text-yellow-700',
  in_progress: 'bg-blue-100 text-blue-700',
  completed: 'bg-green-100 text-green-700',
  cancelled: 'bg-red-100 text-red-700',
  paid: 'bg-green-100 text-green-700',
  paid_partially: 'bg-yellow-100 text-yellow-700',
  shipped: 'bg-blue-100 text-blue-700',
  returned: 'bg-surface-100 text-surface-600',
};

function stateClass(name: string) {
  const key = name.toLowerCase().replace(/[\s-]/g, '_');
  return STATE_COLORS[key] || 'bg-surface-100 text-surface-600';
}

export default function OrderDetailPage() {
  const params = useParams();
  const orderId = params.id as string;
  const { isLoggedIn, isLoading } = useAuth();
  const router = useRouter();

  const [order, setOrder] = useState<Order | null>(null);
  const [pageLoading, setPageLoading] = useState(true);
  const [error, setError] = useState('');

  useEffect(() => {
    if (!isLoading && !isLoggedIn) router.push('/account/login');
  }, [isLoading, isLoggedIn, router]);

  const loadOrder = useCallback(async () => {
    try {
      const o = await getOrder(orderId);
      setOrder(o);
      if (!o) setError('Order not found.');
    } catch (e: any) {
      setError(e.message || 'Failed to load order.');
    } finally {
      setPageLoading(false);
    }
  }, [orderId]);

  useEffect(() => {
    if (!isLoggedIn) return;
    loadOrder();
  }, [isLoggedIn, loadOrder]);

  // The current payment method/state lives on the most recent transaction
  // (changing payment appends a new one), not necessarily transactions[0].
  const activeTxn = order ? getActiveTransaction(order) : undefined;

  if (isLoading || pageLoading) {
    return (
      <div className="min-h-[60vh] flex items-center justify-center">
        <svg className="w-6 h-6 animate-spin text-surface-400" viewBox="0 0 24 24" fill="none">
          <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4" />
          <path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z" />
        </svg>
      </div>
    );
  }

  return (
    <div className="max-w-5xl mx-auto px-6 py-10">
      <div className="grid md:grid-cols-[220px_1fr] gap-8">
        <AccountNav />

        <div>
          {/* Back + breadcrumb */}
          <nav className="text-sm text-surface-400 mb-4 flex items-center gap-1.5">
            <Link href="/account" className="hover:text-surface-600">Account</Link>
            <svg className="w-3 h-3" fill="none" viewBox="0 0 24 24" stroke="currentColor">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 5l7 7-7 7" />
            </svg>
            <Link href="/account/orders" className="hover:text-surface-600">Orders</Link>
            <svg className="w-3 h-3" fill="none" viewBox="0 0 24 24" stroke="currentColor">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 5l7 7-7 7" />
            </svg>
            <span className="text-surface-700">Order {order ? `#${order.orderNumber}` : ''}</span>
          </nav>

          {error && (
            <div className="p-4 bg-red-50 border border-red-200 rounded-xl text-sm text-red-700 mb-6">{error}</div>
          )}

          {order && (
            <div className="space-y-6">
              {/* Order Header */}
              <div className="bg-white border border-surface-200 rounded-2xl p-6">
                <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-4 mb-6">
                  <div>
                    <h1 className="text-2xl font-bold text-surface-900">Order #{order.orderNumber}</h1>
                    <p className="text-surface-500 mt-1 text-sm">
                      Placed on {new Date(order.orderDateTime).toLocaleDateString('en-GB', {
                        day: 'numeric', month: 'long', year: 'numeric',
                      })}
                    </p>
                  </div>
                  <div className="flex flex-wrap gap-2">
                    {/* Order state */}
                    {order.stateMachineState && (
                      <span className={`text-xs font-semibold px-3 py-1.5 rounded-full ${stateClass(order.stateMachineState.translated?.name || order.stateMachineState.name)}`}>
                        Order: {order.stateMachineState.translated?.name || order.stateMachineState.name}
                      </span>
                    )}
                    {/* Payment state */}
                    {activeTxn?.stateMachineState && (
                      <span className={`text-xs font-semibold px-3 py-1.5 rounded-full ${stateClass(activeTxn.stateMachineState.translated?.name || activeTxn.stateMachineState.name || '')}`}>
                        Payment: {activeTxn.stateMachineState.translated?.name || activeTxn.stateMachineState.name}
                      </span>
                    )}
                    {/* Delivery state */}
                    {order.deliveries?.[0]?.stateMachineState && (
                      <span className={`text-xs font-semibold px-3 py-1.5 rounded-full ${stateClass(order.deliveries[0].stateMachineState.translated?.name || order.deliveries[0].stateMachineState.name || '')}`}>
                        Delivery: {order.deliveries[0].stateMachineState.translated?.name || order.deliveries[0].stateMachineState.name}
                      </span>
                    )}
                  </div>
                </div>

                {/* Actions: repeat order / change payment method */}
                <div className="pt-4 border-t border-surface-100">
                  <OrderActions order={order} variant="buttons" onChanged={loadOrder} />
                </div>
              </div>

              {/* Order Items */}
              <div className="bg-white border border-surface-200 rounded-2xl overflow-hidden">
                <div className="px-6 py-4 border-b border-surface-100">
                  <h2 className="font-semibold text-surface-900">Items Ordered</h2>
                </div>
                <div className="divide-y divide-surface-100">
                  {order.lineItems?.map((item) => {
                    const productHref = item.productId ? `/products/${item.productId}` : null;
                    const imageBlock = (
                      <div className="w-14 h-14 bg-surface-50 rounded-xl overflow-hidden flex-shrink-0 flex items-center justify-center relative">
                        {item.cover?.url ? (
                          <Image
                            src={item.cover.url}
                            alt={item.cover.alt || item.label}
                            fill
                            sizes="56px"
                            className="object-contain p-1"
                          />
                        ) : (
                          <span className="text-xl" role="img" aria-label="product">📦</span>
                        )}
                      </div>
                    );
                    return (
                      <div key={item.id} className="flex items-center gap-4 px-6 py-4">
                        {productHref ? (
                          <Link href={productHref} className="flex-shrink-0 hover:opacity-80 transition-opacity">
                            {imageBlock}
                          </Link>
                        ) : (
                          imageBlock
                        )}
                        <div className="flex-1 min-w-0">
                          {productHref ? (
                            <Link
                              href={productHref}
                              className="font-medium text-surface-900 text-sm hover:text-brand-600 transition-colors"
                            >
                              {item.label}
                            </Link>
                          ) : (
                            <p className="font-medium text-surface-900 text-sm">{item.label}</p>
                          )}
                          {item.payload?.options && item.payload.options.length > 0 && (
                            <p className="text-xs text-surface-400 mt-0.5">
                              {item.payload.options.map((o) => `${o.group}: ${o.option}`).join(' | ')}
                            </p>
                          )}
                          <p className="text-xs text-surface-400 mt-0.5">{formatPrice(item.unitPrice)} each</p>
                        </div>
                        <div className="text-right shrink-0">
                          <p className="text-sm font-semibold">{formatPrice(item.totalPrice)}</p>
                          <p className="text-xs text-surface-400">Qty: {item.quantity}</p>
                        </div>
                      </div>
                    );
                  })}
                </div>

                {/* Price summary */}
                <div className="px-6 py-4 bg-surface-50 border-t border-surface-200 space-y-2">
                  <div className="flex justify-between text-sm">
                    <span className="text-surface-500">Subtotal</span>
                    <span>{formatPrice(order.price?.positionPrice || order.amountNet)}</span>
                  </div>
                  {order.shippingTotal !== undefined && order.shippingTotal > 0 && (
                    <div className="flex justify-between text-sm">
                      <span className="text-surface-500">Shipping</span>
                      <span>{formatPrice(order.shippingTotal)}</span>
                    </div>
                  )}
                  {order.deliveries?.[0]?.shippingCosts && (
                    <div className="flex justify-between text-sm">
                      <span className="text-surface-500">Shipping</span>
                      <span>{formatPrice(order.deliveries[0].shippingCosts.totalPrice)}</span>
                    </div>
                  )}
                  <div className="flex justify-between font-bold text-base pt-2 border-t border-surface-200">
                    <span>Total</span>
                    <span>{formatPrice(order.amountTotal)}</span>
                  </div>
                </div>
              </div>

              {/* Customer comment */}
              {order.customerComment && order.customerComment.trim() && (
                <div className="bg-white border border-surface-200 rounded-2xl p-6">
                  <h2 className="font-semibold text-surface-900 mb-2">Your Comment</h2>
                  <p className="text-sm text-surface-600 whitespace-pre-wrap">
                    {order.customerComment}
                  </p>
                </div>
              )}

              {/* Shipping + Payment info */}
              <div className="grid sm:grid-cols-2 gap-6">
                {/* Shipping address */}
                {order.deliveries?.[0]?.shippingOrderAddress && (
                  <div className="bg-white border border-surface-200 rounded-2xl p-6">
                    <h2 className="font-semibold text-surface-900 mb-3">Shipping Address</h2>
                    <div className="text-sm text-surface-600 space-y-0.5">
                      {(() => {
                        const a = order.deliveries![0].shippingOrderAddress!;
                        return (
                          <>
                            <p className="font-medium text-surface-900">{a.firstName} {a.lastName}</p>
                            <p>{a.street}</p>
                            <p>{a.zipcode} {a.city}</p>
                            {a.country && <p>{a.country.name}</p>}
                          </>
                        );
                      })()}
                    </div>
                  </div>
                )}

                {/* Payment & Shipping methods */}
                <div className="bg-white border border-surface-200 rounded-2xl p-6">
                  <h2 className="font-semibold text-surface-900 mb-3">Payment &amp; Shipping</h2>
                  <div className="space-y-3 text-sm">
                    {activeTxn?.paymentMethod && (
                      <div>
                        <p className="text-surface-400 text-xs uppercase tracking-wider mb-0.5">Payment</p>
                        <p className="text-surface-700 font-medium">
                          {activeTxn.paymentMethod.translated?.name || activeTxn.paymentMethod.name}
                        </p>
                      </div>
                    )}
                    {order.deliveries?.[0]?.shippingMethod && (
                      <div>
                        <p className="text-surface-400 text-xs uppercase tracking-wider mb-0.5">Shipping</p>
                        <p className="text-surface-700 font-medium">
                          {order.deliveries[0].shippingMethod.translated?.name || order.deliveries[0].shippingMethod.name}
                        </p>
                      </div>
                    )}
                  </div>
                </div>
              </div>

              {/* Back button */}
              <Link
                href="/account/orders"
                className="inline-flex items-center gap-2 text-sm text-surface-500 hover:text-surface-900 transition-colors"
              >
                <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15 19l-7-7 7-7" />
                </svg>
                Back to orders
              </Link>
            </div>
          )}
        </div>
      </div>
    </div>
  );
}
