import { fetchJson } from '../../../lib/api';
import type { Product } from '../../../features/inventory/types';
import CanonicalNameForm from './CanonicalNameForm';
import MergePreviewForm from './MergePreviewForm';
import Link from 'next/link';

export default async function AdminProductsPage() {
  const products = await fetchJson<Product[]>('/api/products');

  return (
    <main style={{ padding: '1.5rem', maxWidth: '1100px', margin: '0 auto' }}>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '1.5rem' }}>
        <h1 style={{ margin: 0 }}>Admin: Produkter</h1>
        <Link
          href="/recipes/create"
          style={{
            padding: '0.5rem 1rem',
            background: '#0070f3',
            color: 'white',
            borderRadius: '4px',
            textDecoration: 'none',
            fontWeight: 500,
            fontSize: '1rem',
            transition: 'background 0.2s',
          }}
        >
          Lägg till nytt recept
        </Link>
      </div>
      <p>Här kan du granska och standardisera produktnamn.</p>

      <MergePreviewForm products={products} />

      <div style={{ display: 'grid', gap: '1rem' }}>
        {products.map((product) => (
          <article
            key={product.id}
            style={{
              border: '1px solid #ddd',
              borderRadius: '8px',
              padding: '1rem',
              display: 'grid',
              gap: '0.5rem',
            }}
          >
            <div>
              <strong>ID:</strong> {product.id}
            </div>
            <div>
              <strong>Namn:</strong> {product.name}
            </div>
            <div>
              <strong>Canonical name:</strong> {product.canonicalName || 'Saknas'}
            </div>
            <div>
              <strong>Normalized:</strong> {product.normalizedName}
            </div>

            <CanonicalNameForm
              id={product.id}
              currentCanonicalName={product.canonicalName}
            />
          </article>
        ))}
      </div>
    </main>
  );
}