'use client';

/**
 * ============================================
 * ORDER HISTORY PAGE
 * ============================================
 * Equivalent to: account/order/index.html.twig in Shopware
 */

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

const LIMIT = 10;

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',
};

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

export default function OrdersPage() {
  const { isLoggedIn, isLoading } = useAuth();
  const router = useRouter();

  const [orders, setOrders] = useState<Order[]>([]);
  const [total, setTotal] = useState(0);
  const [page, setPage] = useState(1);
  const [pageLoading, setPageLoading] = useState(true);
  const [error, setError] = useState('');

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

  const loadOrders = useCallback(async () => {
    if (!isLoggedIn) return;
    setPageLoading(true);
    setError('');
    try {
      const data = await getOrders({ limit: LIMIT, page });
      const elements = data?.orders?.elements || (data as any)?.elements || [];
      const tot = data?.orders?.total || (data as any)?.total || 0;
      setOrders(elements);
      setTotal(tot);
    } catch (e: any) {
      setError(e.message || 'Failed to load orders.');
    } finally {
      setPageLoading(false);
    }
  }, [isLoggedIn, page]);

  useEffect(() => {
    loadOrders();
  }, [loadOrders]);

  const totalPages = Math.ceil(total / LIMIT);

  if (isLoading) {
    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>
          <h1 className="text-2xl font-bold text-surface-900 mb-6">Order History</h1>

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

          {pageLoading ? (
            <div className="space-y-4">
              {[1, 2, 3].map((i) => (
                <div key={i} className="p-5 bg-surface-50 rounded-2xl animate-pulse">
                  <div className="flex justify-between">
                    <div className="space-y-2">
                      <div className="h-5 w-36 bg-surface-200 rounded" />
                      <div className="h-4 w-24 bg-surface-100 rounded" />
                    </div>
                    <div className="space-y-2 text-right">
                      <div className="h-6 w-20 bg-surface-200 rounded" />
                      <div className="h-5 w-16 bg-surface-100 rounded ml-auto" />
                    </div>
                  </div>
                </div>
              ))}
            </div>
          ) : orders.length === 0 ? (
            <div className="text-center py-16 bg-surface-50 rounded-2xl">
              <span className="text-4xl mb-3 block">📦</span>
              <p className="text-surface-500 mb-4">You haven&apos;t placed any orders yet.</p>
              <Link href="/" className="inline-block px-6 py-2.5 bg-brand-500 hover:bg-brand-600 text-white font-semibold rounded-xl transition-colors">
                Start Shopping
              </Link>
            </div>
          ) : (
            <>
              <div className="space-y-4">
                {orders.map((order) => {
                  const stateName = order.stateMachineState?.translated?.name || order.stateMachineState?.name || 'Processing';
                  const shippingMethod = order.deliveries?.[0]?.shippingMethod?.translated?.name || order.deliveries?.[0]?.shippingMethod?.name;
                  const paymentMethod = getOrderPaymentMethodName(order);

                  return (
                    <div key={order.id} className="relative">
                    <Link
                      href={`/account/orders/${order.id}`}
                      className="block p-5 bg-white border border-surface-200 rounded-2xl hover:border-brand-300 hover:shadow-sm transition-all group"
                    >
                      <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-4 pr-10 sm:pr-12">
                        <div>
                          <p className="font-semibold text-surface-900 group-hover:text-brand-600 transition-colors">
                            Order #{order.orderNumber}
                          </p>
                          <p className="text-sm text-surface-500 mt-0.5">
                            {new Date(order.orderDateTime).toLocaleDateString('en-GB', {
                              day: 'numeric', month: 'long', year: 'numeric',
                            })}
                          </p>
                          <p className="text-xs text-surface-400 mt-1">
                            {order.lineItems?.filter(i => i.type === 'product' || !i.type).length || 0} item(s)
                          </p>
                        </div>
                        <div className="flex sm:flex-col items-center sm:items-end gap-3">
                          <p className="font-bold text-lg">{formatPrice(order.amountTotal)}</p>
                          <span className={`text-xs font-medium px-2.5 py-1 rounded-full ${getStateColor(stateName)}`}>
                            {stateName}
                          </span>
                        </div>
                      </div>

                      {/* Line items preview */}
                      {order.lineItems && order.lineItems.length > 0 && (
                        <div className="mt-4 pt-4 border-t border-surface-100 space-y-1.5">
                          {order.lineItems.slice(0, 3).map((item) => (
                            <div key={item.id} className="flex justify-between text-sm gap-2">
                              <span className="text-surface-600">
                                {item.quantity}× {item.label}
                                {item.payload?.options && item.payload.options.length > 0 && (
                                  <span className="text-surface-400 ml-1 text-xs">
                                    ({item.payload.options.map((o: any) => `${o.group}: ${o.option}`).join(', ')})
                                  </span>
                                )}
                              </span>
                              <span className="text-surface-500 font-medium whitespace-nowrap">{formatPrice(item.totalPrice)}</span>
                            </div>
                          ))}
                          {order.lineItems.length > 3 && (
                            <p className="text-xs text-surface-400">+{order.lineItems.length - 3} more</p>
                          )}
                        </div>
                      )}

                      {/* Methods */}
                      {(shippingMethod || paymentMethod) && (
                        <div className="mt-3 flex gap-4 flex-wrap text-xs text-surface-400">
                          {paymentMethod && <span>Payment: {paymentMethod}</span>}
                          {shippingMethod && <span>Shipping: {shippingMethod}</span>}
                        </div>
                      )}
                    </Link>
                    <OrderActions
                      order={order}
                      variant="menu"
                      className="absolute top-4 right-4"
                      onChanged={loadOrders}
                    />
                    </div>
                  );
                })}
              </div>

              {/* Pagination */}
              {totalPages > 1 && (
                <div className="flex items-center justify-center gap-2 mt-8">
                  <button
                    onClick={() => setPage((p) => Math.max(1, p - 1))}
                    disabled={page === 1}
                    className="px-4 py-2 text-sm font-medium border border-surface-200 rounded-lg hover:bg-surface-50 disabled:opacity-40 disabled:cursor-not-allowed transition-colors"
                  >
                    ← Previous
                  </button>
                  {Array.from({ length: totalPages }, (_, i) => i + 1).map((p) => (
                    <button
                      key={p}
                      onClick={() => setPage(p)}
                      className={`w-10 h-10 text-sm font-medium rounded-lg transition-colors ${
                        p === page ? 'bg-brand-500 text-white' : 'border border-surface-200 hover:bg-surface-50'
                      }`}
                    >
                      {p}
                    </button>
                  ))}
                  <button
                    onClick={() => setPage((p) => Math.min(totalPages, p + 1))}
                    disabled={page === totalPages}
                    className="px-4 py-2 text-sm font-medium border border-surface-200 rounded-lg hover:bg-surface-50 disabled:opacity-40 disabled:cursor-not-allowed transition-colors"
                  >
                    Next →
                  </button>
                </div>
              )}
            </>
          )}
        </div>
      </div>
    </div>
  );
}
