import Link from 'next/link';
import { prisma } from '@/lib/prisma';
import AdminNav from '@/components/AdminNav';
import AccountsNav from '@/components/AccountsNav';
import Price from '@/components/Price';
import { deleteManualSale } from './actions';

const PAYMENT_LABELS: Record<string, string> = {
  CASH: 'Cash',
  BANK_TRANSFER: 'Bank transfer',
};

// One row of the merged ledger — a website order and a manual sale flattened
// to the same shape so they can be sorted and totalled together.
type LedgerEntry = {
  id: string;
  kind: 'WEB' | 'MANUAL';
  date: Date;
  who: string;
  what: string;
  method: string;
  total: number;
  href: string | null; // detail link (web orders only for now)
};

export default async function AccountsPage({
  searchParams,
}: {
  searchParams: { type?: string; from?: string; to?: string };
}) {
  const type = searchParams.type === 'web' || searchParams.type === 'manual' ? searchParams.type : 'all';
  const from = searchParams.from ? new Date(searchParams.from) : null;
  // Include the whole "to" day, not just its midnight.
  const to = searchParams.to ? new Date(`${searchParams.to}T23:59:59`) : null;

  let orders = [];
  let manualSales = [];

  try {
    [orders, manualSales] = await Promise.all([
      type === 'manual'
        ? []
        : prisma.order.findMany({
            where: {
              status: 'PAID',
              ...(from || to ? { createdAt: { ...(from ? { gte: from } : {}), ...(to ? { lte: to } : {}) } } : {}),
            },
            include: { items: true, customer: true },
          }),
      type === 'web'
        ? []
        : prisma.manualSale.findMany({
            where: from || to ? { soldAt: { ...(from ? { gte: from } : {}), ...(to ? { lte: to } : {}) } } : {},
            include: { items: true },
          }),
    ]);
  } catch (err) {
    console.error('Error fetching ledger data:', err);
  }

  const entries: LedgerEntry[] = [
    ...orders.map((o) => ({
      id: o.id,
      kind: 'WEB' as const,
      date: o.createdAt,
      who: o.customer?.name ?? o.email ?? 'Guest',
      what: o.items.map((i) => `${i.quantity}× ${i.productName}`).join(', '),
      method: 'Card (website)',
      total: o.total,
      href: `/admin/orders`,
    })),
    ...manualSales.map((s) => ({
      id: s.id,
      kind: 'MANUAL' as const,
      date: s.soldAt,
      who: s.buyerName || s.buyerEmail || 'Unnamed buyer',
      what: s.items.map((i) => `${i.quantity}× ${i.description}`).join(', '),
      method: PAYMENT_LABELS[s.paymentMethod] ?? s.paymentMethod,
      total: s.total,
      href: null,
    })),
  ].sort((a, b) => b.date.getTime() - a.date.getTime());

  const totalAll = entries.reduce((sum, e) => sum + e.total, 0);
  const totalWeb = entries.filter((e) => e.kind === 'WEB').reduce((sum, e) => sum + e.total, 0);
  const totalManual = totalAll - totalWeb;

  const filterHref = (t: string) => {
    const params = new URLSearchParams();
    if (t !== 'all') params.set('type', t);
    if (searchParams.from) params.set('from', searchParams.from);
    if (searchParams.to) params.set('to', searchParams.to);
    const qs = params.toString();
    return `/admin/accounts${qs ? `?${qs}` : ''}`;
  };

  return (
    <div className="mx-auto max-w-4xl px-6 py-12">
      <AdminNav />
      <div className="flex flex-wrap items-baseline justify-between gap-3">
        <h1 className="font-display text-3xl">Accounts</h1>
        <Link
          href="/admin/accounts/new"
          className="border border-ink px-4 py-2 text-sm hover:border-clay hover:bg-clay hover:text-paper"
        >
          + Record a sale
        </Link>
      </div>
      <AccountsNav active="/admin/accounts" />
      <p className="mt-4 text-sm text-muted">
        Every sale in one place — paid website orders plus anything you record by hand (cash, bank
        transfer). Website orders appear here automatically once paid.
      </p>

      {/* Totals for whatever the current filter shows */}
      <div className="mt-6 grid gap-3 sm:grid-cols-3">
        <div className="border border-line bg-surface p-4">
          <p className="tag-label">Total</p>
          <p className="mt-1 font-mono text-xl">
            <Price cents={totalAll} />
          </p>
        </div>
        <div className="border border-line bg-surface p-4">
          <p className="tag-label">Website</p>
          <p className="mt-1 font-mono text-xl">
            <Price cents={totalWeb} />
          </p>
        </div>
        <div className="border border-line bg-surface p-4">
          <p className="tag-label">Manual</p>
          <p className="mt-1 font-mono text-xl">
            <Price cents={totalManual} />
          </p>
        </div>
      </div>

      {/* Filters */}
      <div className="mt-6 flex flex-wrap items-center gap-4">
        <div className="inline-flex border border-line">
          {(
            [
              ['all', 'All'],
              ['web', 'Website'],
              ['manual', 'Manual'],
            ] as const
          ).map(([value, label]) => (
            <Link
              key={value}
              href={filterHref(value)}
              className={`px-4 py-1.5 text-sm ${type === value ? 'bg-ink text-paper' : 'hover:text-clay'}`}
            >
              {label}
            </Link>
          ))}
        </div>
        <form method="get" className="flex flex-wrap items-center gap-2 text-sm">
          {type !== 'all' && <input type="hidden" name="type" value={type} />}
          <label className="flex items-center gap-1 text-muted">
            From
            <input
              type="date"
              name="from"
              defaultValue={searchParams.from ?? ''}
              className="border border-line bg-paper px-2 py-1.5"
            />
          </label>
          <label className="flex items-center gap-1 text-muted">
            To
            <input
              type="date"
              name="to"
              defaultValue={searchParams.to ?? ''}
              className="border border-line bg-paper px-2 py-1.5"
            />
          </label>
          <button type="submit" className="border border-line px-3 py-1.5 hover:border-clay hover:text-clay">
            Apply
          </button>
          {(searchParams.from || searchParams.to) && (
            <Link href={filterHref(type)} className="tag-label text-muted hover:text-ink">
              Clear dates
            </Link>
          )}
        </form>
      </div>

      {/* Ledger */}
      {entries.length === 0 ? (
        <p className="mt-8 text-sm text-muted">No sales in this range yet.</p>
      ) : (
        <div className="mt-8 divide-y divide-line border-t border-line">
          {entries.map((e) => (
            <div key={`${e.kind}-${e.id}`} className="flex flex-wrap items-center gap-x-4 gap-y-1 py-4">
              <span
                className={`tag-label shrink-0 rounded-full px-3 py-1 ${
                  e.kind === 'WEB' ? 'bg-splash-blue/10 text-splash-blue' : 'bg-splash-orange/10 text-splash-orange'
                }`}
              >
                {e.kind === 'WEB' ? 'Website' : 'Manual'}
              </span>
              <span className="w-24 shrink-0 font-mono text-xs text-muted">
                {e.date.toLocaleDateString('en-GB', { day: '2-digit', month: 'short', year: 'numeric' })}
              </span>
              <div className="min-w-0 flex-1">
                <p className="truncate text-sm font-medium">{e.who}</p>
                <p className="truncate text-xs text-muted">{e.what}</p>
              </div>
              <span className="tag-label hidden text-muted sm:inline">{e.method}</span>
              <span className="w-20 shrink-0 text-right font-mono text-sm">
                <Price cents={e.total} />
              </span>
              {e.kind === 'MANUAL' ? (
                <form action={deleteManualSale}>
                  <input type="hidden" name="id" value={e.id} />
                  <button type="submit" className="tag-label text-muted hover:text-splash-pink">
                    Delete
                  </button>
                </form>
              ) : (
                <Link href={e.href!} className="tag-label text-muted hover:text-ink">
                  View
                </Link>
              )}
            </div>
          ))}
        </div>
      )}
    </div>
  );
}
