import { prisma } from '@/lib/prisma';
import AdminNav from '@/components/AdminNav';
import AccountsNav from '@/components/AccountsNav';
import StockAdjustForm from '@/components/StockAdjustForm';

export default async function StockPage() {
  let levels = [];
  let productRows = [];

  try {
    [levels, productRows] = await Promise.all([
      prisma.stockLevel.findMany({
        include: { product: true },
      }),
      prisma.product.findMany(),
    ]);
  } catch (err) {
    console.error('Error fetching stock data:', err);
  }

  const products = productRows.map((p) => ({
    id: p.id,
    name: p.name,
    colors: JSON.parse(p.colors) as string[],
    sizes: p.sizes ? (JSON.parse(p.sizes) as string[]) : [],
  })).sort((a, b) => a.name.localeCompare(b.name));

  // Group rows under their product for a readable table.
  const grouped = new Map<string, typeof levels>();
  for (const level of levels.sort((a, b) => {
    if (a.product.name !== b.product.name) return a.product.name.localeCompare(b.product.name);
    if (a.color !== b.color) return a.color.localeCompare(b.color);
    return (a.size || '').localeCompare(b.size || '');
  })) {
    const list = grouped.get(level.productId) ?? [];
    list.push(level);
    grouped.set(level.productId, list);
  }

  return (
    <div className="mx-auto max-w-4xl px-6 py-12">
      <AdminNav />
      <h1 className="font-display text-3xl">Stock</h1>
      <AccountsNav active="/admin/accounts/stock" />
      <p className="mt-4 text-sm text-muted">
        Counts go up when you record a purchase and down when something sells (website or manual).
        A <span className="text-splash-pink">negative count</span> means a sale happened that your
        purchases don&apos;t cover — enter the missing invoice or set the real count below. Nothing
        here ever blocks an order.
      </p>

      <StockAdjustForm products={products} />

      {levels.length === 0 ? (
        <p className="mt-8 text-sm text-muted">
          No stock recorded yet — record a purchase, or set a count above to do an initial stock take.
        </p>
      ) : (
        <div className="mt-8 space-y-8">
          {[...grouped.entries()].map(([productId, rows]) => (
            <div key={productId}>
              <h2 className="font-display text-xl">{rows[0].product.name}</h2>
              <div className="mt-2 divide-y divide-line border-t border-line">
                {rows.map((row) => (
                  <div key={row.id} className="flex flex-wrap items-center gap-x-4 gap-y-1 py-2.5">
                    <span
                      className="h-5 w-5 shrink-0 rounded-full border border-line"
                      style={{ backgroundColor: row.color }}
                      title={row.color}
                    />
                    <span className="w-20 font-mono text-xs text-muted">{row.color}</span>
                    <span className="w-12 text-sm">{row.size || '—'}</span>
                    <span
                      className={`ml-auto font-mono text-sm ${row.quantity < 0 ? 'font-medium text-splash-pink' : ''}`}
                    >
                      {row.quantity} in stock
                    </span>
                  </div>
                ))}
              </div>
            </div>
          ))}
        </div>
      )}
    </div>
  );
}
