/**
 * ============================================
 * ACCOUNT DASHBOARD PAGE
 * ============================================
 * Equivalent to: account/index.html.twig in Shopware
 * Shows customer info, recent orders, and quick actions
 * 
 * FIX: The Shopware Store API /order endpoint returns
 * { orders: { elements: [...], total: N } }
 * NOT { elements: [...] } directly.
 */

'use client';

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

export default function AccountPage() {
  const { customer, isLoggedIn, isLoading } = useAuth();
  const router = useRouter();
  const [orders, setOrders] = useState<Order[]>([]);
  const [ordersLoading, setOrdersLoading] = useState(true);
  const [ordersError, setOrdersError] = useState<string | null>(null);

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

  // Load recent orders
  useEffect(() => {
    async function loadOrders() {
      if (!isLoggedIn) return;
      setOrdersLoading(true);
      setOrdersError(null);
      try {
        const data = await getOrders({ limit: 5 });
        // Shopware Store API returns { orders: { elements: [...] } }
        // Handle both possible response structures
        const orderElements =
          data?.orders?.elements ||  // Standard Store API response
          (data as any)?.elements ||  // Fallback
          [];
        setOrders(orderElements);
      } catch (e: any) {
        console.error('Failed to load orders:', e);
        setOrdersError(e.message || 'Failed to load orders');
        setOrders([]);
      } finally {
        setOrdersLoading(false);
      }
    }
    loadOrders();
  }, [isLoggedIn]);

  if (isLoading) {
    return (
      <div className="min-h-[60vh] flex items-center justify-center">
        <div className="flex items-center gap-3 text-surface-500">
          <svg className="w-6 h-6 animate-spin" 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>
          Loading...
        </div>
      </div>
    );
  }

  if (!customer) return null;

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

        <div>
          {/* Welcome */}
          <div className="flex items-center justify-between mb-8">
            <div>
              <h1 className="text-2xl font-bold text-surface-900">
                Hello, {customer.firstName}!
              </h1>
              <p className="text-surface-500 mt-1 text-sm">{customer.email}</p>
            </div>
          </div>

          {/* Quick Info Cards */}
          <div className="grid sm:grid-cols-2 gap-4 mb-10">
            {/* Profile Card */}
            <Link href="/account/profile" 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 items-center gap-3 mb-3">
                <div className="w-9 h-9 bg-brand-100 text-brand-600 rounded-xl flex items-center justify-center">
                  <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M16 7a4 4 0 11-8 0 4 4 0 018 0zM12 14a7 7 0 00-7 7h14a7 7 0 00-7-7z" />
                  </svg>
                </div>
                <h2 className="text-sm font-semibold text-surface-900 group-hover:text-brand-600 transition-colors">Profile</h2>
              </div>
              <p className="text-sm text-surface-600">{customer.firstName} {customer.lastName}</p>
              <p className="text-xs text-surface-400 mt-0.5">Customer #{customer.customerNumber}</p>
              <p className="text-xs text-brand-500 mt-2">Edit profile →</p>
            </Link>

            {/* Address Card */}
            <Link href="/account/addresses" 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 items-center gap-3 mb-3">
                <div className="w-9 h-9 bg-brand-100 text-brand-600 rounded-xl flex items-center justify-center">
                  <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M17.657 16.657L13.414 20.9a1.998 1.998 0 01-2.827 0l-4.244-4.243a8 8 0 1111.314 0z" />
                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15 11a3 3 0 11-6 0 3 3 0 016 0z" />
                  </svg>
                </div>
                <h2 className="text-sm font-semibold text-surface-900 group-hover:text-brand-600 transition-colors">Addresses</h2>
              </div>
              {customer.defaultBillingAddress ? (
                <div className="text-sm text-surface-600 space-y-0.5">
                  <p>{customer.defaultBillingAddress.street}</p>
                  <p>{customer.defaultBillingAddress.zipcode} {customer.defaultBillingAddress.city}</p>
                </div>
              ) : (
                <p className="text-sm text-surface-400">No address set</p>
              )}
              <p className="text-xs text-brand-500 mt-2">Manage addresses →</p>
            </Link>
          </div>

          {/* Recent Orders */}
          <div>
            <div className="flex items-center justify-between mb-4">
              <h2 className="text-lg font-bold text-surface-900">Recent Orders</h2>
              <Link href="/account/orders" className="text-sm text-brand-600 hover:text-brand-700 font-medium">
                View all →
              </Link>
            </div>

            {ordersLoading ? (
              <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 items-center">
                      <div>
                        <div className="h-5 w-32 bg-surface-200 rounded mb-2" />
                        <div className="h-4 w-24 bg-surface-100 rounded" />
                      </div>
                      <div className="text-right">
                        <div className="h-6 w-20 bg-surface-200 rounded mb-2" />
                        <div className="h-5 w-16 bg-surface-100 rounded" />
                      </div>
                    </div>
                  </div>
                ))}
              </div>
            ) : ordersError ? (
              <div className="text-center py-10 bg-red-50 rounded-2xl">
                <p className="text-red-600 mb-2 text-sm">Failed to load orders</p>
                <p className="text-red-400 text-xs mb-4">{ordersError}</p>
                <button
                  onClick={() => window.location.reload()}
                  className="px-5 py-2 bg-red-500 hover:bg-red-600 text-white text-sm font-semibold rounded-xl transition-colors"
                >
                  Retry
                </button>
              </div>
            ) : orders.length === 0 ? (
              <div className="text-center py-10 bg-surface-50 rounded-2xl">
                <p className="text-surface-500 mb-4 text-sm">No orders yet</p>
                <Link
                  href="/"
                  className="inline-block px-5 py-2 bg-brand-500 hover:bg-brand-600 text-white text-sm font-semibold rounded-xl transition-colors"
                >
                  Start Shopping
                </Link>
              </div>
            ) : (
              <div className="space-y-3">
                {orders.map((order) => (
                  <Link
                    key={order.id}
                    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">
                      <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?.length || 0} item(s)
                        </p>
                      </div>
                      <div className="text-right shrink-0">
                        <p className="font-bold text-lg">{formatPrice(order.amountTotal)}</p>
                        <span className="inline-block mt-1 px-3 py-1 text-xs font-medium bg-brand-100 text-brand-700 rounded-full">
                          {order.stateMachineState?.translated?.name || order.stateMachineState?.name || 'Processing'}
                        </span>
                      </div>
                    </div>

                    {/* Order Line Items Preview */}
                    {order.lineItems && order.lineItems.length > 0 && (
                      <div className="mt-4 pt-4 border-t border-surface-100">
                        <div className="space-y-1.5">
                          {order.lineItems.slice(0, 2).map((item) => (
                            <div key={item.id} className="flex justify-between text-sm">
                              <span className="text-surface-600">
                                {item.quantity}× {item.label}
                              </span>
                              <span className="text-surface-500 font-medium">
                                {formatPrice(item.totalPrice)}
                              </span>
                            </div>
                          ))}
                          {order.lineItems.length > 2 && (
                            <p className="text-xs text-surface-400">
                              +{order.lineItems.length - 2} more item(s)
                            </p>
                          )}
                        </div>
                      </div>
                    )}
                  </Link>
                ))}
              </div>
            )}
          </div>
        </div>
      </div>
    </div>
  );
}
