'use client';

import { useState } from 'react';
import Link from 'next/link';

interface OlderOrdersProps {
  orders: any[];
  formatPrice: (cents: number) => string;
  statusLabel: (status: string, trackingNumber?: string | null, collectedByCustomer?: boolean) => string;
  statusClasses: (status: string, trackingNumber?: string | null) => string;
}

export default function OlderOrders({ orders, formatPrice, statusLabel, statusClasses }: OlderOrdersProps) {
  const [isOpen, setIsOpen] = useState(false);

  if (orders.length === 0) return null;

  return (
    <div className="mt-6">
      <button
        onClick={() => setIsOpen(!isOpen)}
        className="text-sm font-medium text-clay hover:text-clay-dark"
      >
        {isOpen ? '✕' : '▼'} Older orders ({orders.length})
      </button>

      {isOpen && (
        <div className="mt-4 divide-y divide-line border-t border-line">
          {orders.map((order) => (
            <div key={order.id} className="border-b border-line py-4 last:border-b-0">
              <Link
                href={`/account/orders/${order.id}`}
                className="flex flex-wrap items-center justify-between gap-2 hover:opacity-80"
              >
                <div>
                  <p className="text-sm">
                    {new Date(order.createdAt).toLocaleDateString(undefined, { dateStyle: 'medium' })} ·{' '}
                    {order.items.length} item{order.items.length === 1 ? '' : 's'}
                  </p>
                  <span className={`tag-label mt-1 inline-block rounded-full px-3 py-1 ${statusClasses(order.status, order.trackingNumber)}`}>
                    {statusLabel(order.status, order.trackingNumber, order.collectedByCustomer)}
                  </span>
                </div>
                <span className="font-mono text-sm">{formatPrice(order.total)}</span>
              </Link>

              {order.carrier && order.trackingNumber && (
                <div className="mt-3 border-t border-line pt-3 text-sm">
                  <p>
                    <strong>Tracking:</strong> {order.carrier} · {order.trackingNumber}
                  </p>
                  {order.estimatedDeliveryDate && (
                    <p className="text-muted">
                      Est. delivery: {new Date(order.estimatedDeliveryDate).toLocaleDateString(undefined, { dateStyle: 'medium' })}
                    </p>
                  )}
                </div>
              )}
            </div>
          ))}
        </div>
      )}
    </div>
  );
}
