import Link from 'next/link';
import { prisma } from '@/lib/prisma';
import AdminNav from '@/components/AdminNav';
import { autoArchiveOldOrders, archiveOrder, unarchiveOrder } from './actions';

function formatPrice(cents: number) {
  return `£${(cents / 100).toFixed(2)}`;
}

const STATUS_STYLES: Record<string, string> = {
  PAID: 'bg-splash-blue/10 text-splash-blue',
  PENDING: 'bg-splash-orange/10 text-splash-orange',
  FAILED: 'bg-splash-pink/10 text-splash-pink',
};

export default async function OrdersPage({ searchParams }: { searchParams: { archived?: string; personalised?: string } }) {
  await autoArchiveOldOrders();

  const showArchived = searchParams.archived === '1';
  const showOnlyPersonalised = searchParams.personalised === '1';

  let orders = [];
  try {
    orders = await prisma.order.findMany({
      where: {
        status: { in: ['PAID', 'PENDING', 'FAILED'] },
        archived: showArchived,
      },
      include: { items: true },
    });
    orders.sort((a, b) => b.createdAt.getTime() - a.createdAt.getTime());

    // Filter to personalised orders if requested
    if (showOnlyPersonalised) {
      orders = orders.filter((order) =>
        order.items.some((item) => {
          const design = JSON.parse(item.designJson) as { front: unknown[]; back: unknown[] };
          return design.front.length > 0 || design.back.length > 0;
        })
      );
    }
  } catch (err) {
    console.error('Error fetching orders:', err);
  }

  const filterHref = (personalised: boolean) => {
    const params = new URLSearchParams();
    if (showArchived) params.set('archived', '1');
    if (personalised) params.set('personalised', '1');
    const qs = params.toString();
    return `/admin/orders${qs ? `?${qs}` : ''}`;
  };

  return (
    <div className="mx-auto max-w-4xl px-6 py-12">
      <AdminNav />
      <div className="flex items-baseline justify-between">
        <h1 className="font-display text-3xl">{showArchived ? 'Archived orders' : 'Orders'}</h1>
        <Link href={showArchived ? '/admin/orders' : '/admin/orders?archived=1'} className="tag-label hover:text-ink">
          {showArchived ? '← Back to active orders' : 'View archived →'}
        </Link>
      </div>
      {!showArchived && (
        <p className="mt-2 text-xs text-muted">
          Paid or failed orders older than 30 days archive automatically. Use the button on any order
          to archive it sooner, or wait for it to happen on its own.
        </p>
      )}

      {!showArchived && (
        <div className="mt-6 flex flex-wrap items-center gap-2">
          <span className="text-sm text-muted">Filter:</span>
          <div className="inline-flex border border-line">
            <Link
              href={filterHref(false)}
              className={`px-4 py-1.5 text-sm ${!showOnlyPersonalised ? 'bg-ink text-paper' : 'hover:text-clay'}`}
            >
              All
            </Link>
            <Link
              href={filterHref(true)}
              className={`px-4 py-1.5 text-sm ${showOnlyPersonalised ? 'bg-ink text-paper' : 'hover:text-clay'}`}
            >
              Personalised only
            </Link>
          </div>
        </div>
      )}

      {orders.length === 0 ? (
        <p className="mt-10 text-sm text-muted">
          {showArchived ? 'Nothing archived yet.' : showOnlyPersonalised ? 'No personalised orders yet.' : 'No orders yet.'}
        </p>
      ) : (
        <div className="mt-8 divide-y divide-line border-t border-line">
          {orders.map((order) => {
            const hasPersonalised = order.items.some((item) => {
              const design = JSON.parse(item.designJson) as { front: unknown[]; back: unknown[] };
              return design.front.length > 0 || design.back.length > 0;
            });
            return (
              <div key={order.id} className="flex flex-wrap items-center gap-x-4 gap-y-2 py-4">
                <Link href={`/admin/orders/${order.id}`} className="flex flex-1 items-center gap-4 hover:opacity-80 min-w-0">
                  <div className="flex-1 min-w-0">
                    <p className="font-medium">{order.email ?? 'No email yet'}</p>
                    <p className="text-sm text-muted">
                      {order.items.length} item{order.items.length === 1 ? '' : 's'} ·{' '}
                      {new Date(order.createdAt).toLocaleString(undefined, {
                        dateStyle: 'medium',
                        timeStyle: 'short',
                      })}
                    </p>
                  </div>
                </Link>
                {hasPersonalised && (
                  <span className="tag-label rounded-full bg-splash-orange/10 px-3 py-1 text-splash-orange">Personalised</span>
                )}
                <span className="font-mono text-sm">{formatPrice(order.total)}</span>
                <span className={`tag-label rounded-full px-3 py-1 ${STATUS_STYLES[order.status] ?? ''}`}>
                  {order.status}
                </span>
                <form action={showArchived ? unarchiveOrder : archiveOrder}>
                  <input type="hidden" name="id" value={order.id} />
                  <button type="submit" className="tag-label text-muted hover:text-clay">
                    {showArchived ? 'Unarchive' : 'Archive'}
                  </button>
                </form>
              </div>
            );
          })}
        </div>
      )}
    </div>
  );
}
