import Link from 'next/link';
import { redirect } from 'next/navigation';
import type { Metadata } from 'next';
import { getAccountToken } from '@/lib/account-session';
import { backendApi, BackendApiError, type ApiOrder } from '@/lib/backend-api';
import { ROUTES, orderRoute } from '@/lib/routes';

export const metadata: Metadata = { title: 'Order History' };

export default async function OrderHistoryPage() {
  const token = getAccountToken();
  if (!token) {
    redirect(`${ROUTES.login}?redirect=${ROUTES.orders}`);
    return;
  }

  let orders: ApiOrder[] = [];
  try {
    const res = await backendApi.getMyOrders(token);
    orders = res.data;
  } catch (err) {
    if (err instanceof BackendApiError && err.status === 401) {
      redirect(`${ROUTES.login}?redirect=${ROUTES.orders}`);
    }
    // Any other failure (network hiccup, etc.) — fail soft with an empty
    // list rather than crashing the whole account section.
  }

  return (
    <section className="bg-beige py-14">
      <div className="container-page max-w-3xl">
        <Link href={ROUTES.account} className="text-sm font-semibold text-gold-600 hover:text-gold-700">
          &larr; My Account
        </Link>
        <h1 className="mt-2 font-serif text-2xl font-bold text-navy-800">Order History</h1>

        {orders.length === 0 ? (
          <p className="mt-6 text-sm text-navy-600">
            You haven&apos;t placed any orders yet.{' '}
            <Link href={ROUTES.shop} className="font-semibold text-gold-600 hover:text-gold-700">Browse the shop</Link>.
          </p>
        ) : (
          <div className="mt-6 space-y-3">
            {orders.map((order) => (
              <Link
                key={order.order_id}
                href={orderRoute(order.order_id)}
                className="card flex items-center justify-between p-4 hover:border-gold-300"
              >
                <div>
                  <p className="text-sm font-semibold text-navy-800">Order #{order.order_id}</p>
                  <p className="mt-0.5 text-xs capitalize text-navy-500">
                    {order.order_status} · Payment {order.payment_status}
                  </p>
                </div>
                <span className="text-sm font-semibold text-navy-800">
                  Rs. {Number(order.net_amount).toLocaleString()}
                </span>
              </Link>
            ))}
          </div>
        )}
      </div>
    </section>
  );
}
