'use client';

import { useRef, useState, useEffect } from 'react';

type CategorySuggestion = {
  categoryId: number;
  categoryName: string;
  path: string;
  confidence: 'high' | 'medium' | 'low';
  usedFallback: boolean;
};

type ParsedItem = {
  rawName: string;
  quantity: number;
  unit: string;
  price?: number | null;
  brand?: string | null;
  origin?: string | null;
  matchedProductId?: number;
  matchedProductName?: string;
  suggestedProductId?: number;
  suggestedProductName?: string;
  categorySuggestion?: CategorySuggestion;
};

type Product = { id: number; name: string; canonicalName: string | null };
type Category = { id: number; name: string; parentId: number | null };

type RowState = {
  productSearch: string;
  selectedCategoryId: number | '';  // för manuellt val vid none utan AI
  rawName: string;
  quantity: number;
  unit: string;
  price?: number | null;
  selectedProductId: number | '';
  selectedProductName: string;
  checked: boolean;
  saveAlias: boolean;
  editQty: string;
  editUnit: string;
  editBrand: string;
  editOrigin: string;
  editComment: string;
  matchSource: 'alias' | 'suggestion' | 'manual' | 'none';
  categorySuggestion?: CategorySuggestion;
};

const UNITS = ['st', 'kg', 'g', 'l', 'dl', 'cl', 'ml', 'förp', 'pak', 'burk', 'flaska'];

export default function ReceiptImportClient({ isAdmin }: { isAdmin: boolean }) {
  const fileRef = useRef<HTMLInputElement>(null);
  // Debug: log role on mount
  useEffect(() => {
    // eslint-disable-next-line no-console
    console.log('ReceiptImportClient: isAdmin =', isAdmin);
  }, [isAdmin]);
  const [preview, setPreview] = useState<string | null>(null);
  const [parsing, setParsing] = useState(false);
  const [saving, setSaving] = useState(false);
  const [rows, setRows] = useState<RowState[]>([]);
  const [allProducts, setAllProducts] = useState<Product[]>([]);
  const [allCategories, setAllCategories] = useState<Category[]>([]);
  const [productsLoading, setProductsLoading] = useState(true);
  const [productsError, setProductsError] = useState<string | null>(null);
  const [error, setError] = useState<string | null>(null);
  const [savedCount, setSavedCount] = useState<number | null>(null);
  const [selectedFile, setSelectedFile] = useState<File | null>(null);
  const [showReceiptModal, setShowReceiptModal] = useState(false);
  const [creatingProduct, setCreatingProduct] = useState<number | null>(null);

  useEffect(() => {
    fetch('/api/products')
      .then(async (r) => {
        if (!r.ok) throw new Error(`HTTP ${r.status}`);
        return r.json();
      })
      .then((data) => {
        if (Array.isArray(data)) {
          setAllProducts(data);
        } else {
          setProductsError('Oväntat format från produktlistan');
        }
      })
      .catch((e) => setProductsError(`Kunde inte ladda produktlistan: ${e.message}`))
      .finally(() => setProductsLoading(false));

    fetch('/api/categories')
      .then((r) => r.json())
      .then((data) => { if (Array.isArray(data)) setAllCategories(data); })
      .catch(() => {});
  }, []);

  const handleFileChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (!file) return;
    setSelectedFile(file);
    setPreview(file.type === 'application/pdf' ? 'pdf' : URL.createObjectURL(file));
    setRows([]);
    setError(null);
    setSavedCount(null);
  };

  const handleParse = async () => {
    if (!selectedFile) return;
    setParsing(true);
    setError(null);
    try {
      const fd = new FormData();
      fd.append('file', selectedFile);
      const res = await fetch('/api/receipt-import-proxy', { method: 'POST', body: fd });
      if (!res.ok) {
        const e = await res.json().catch(() => ({ message: 'Okänt fel' }));
        throw new Error(e.message ?? 'Servern svarade med fel');
      }
      const items: ParsedItem[] = await res.json();
      setRows(
        items.map((item): RowState => {
          if (item.matchedProductId) {
            return {
              rawName: item.rawName,
              quantity: item.quantity,
              unit: item.unit,
              price: item.price,
              selectedProductId: item.matchedProductId,
              selectedProductName: item.matchedProductName ?? '',
              checked: true,
              saveAlias: false,
              editQty: String(item.quantity),
              editUnit: item.unit,
              editBrand: item.brand ?? '',
              editOrigin: item.origin ?? '',
              editComment: '',
              matchSource: 'alias',
              productSearch: item.matchedProductName ?? '',
              selectedCategoryId: '',
            };
          }
          if (item.suggestedProductId) {
            return {
              rawName: item.rawName,
              quantity: item.quantity,
              unit: item.unit,
              price: item.price,
              selectedProductId: item.suggestedProductId,
              selectedProductName: item.suggestedProductName ?? '',
              checked: false,
              saveAlias: false,
              editQty: String(item.quantity),
              editUnit: item.unit,
              editBrand: item.brand ?? '',
              editOrigin: item.origin ?? '',
              editComment: '',
              matchSource: 'suggestion',
              productSearch: item.suggestedProductName ?? '',
              selectedCategoryId: '',
            };
          }
          return {
            rawName: item.rawName,
            quantity: item.quantity,
            unit: item.unit,
            price: item.price,
            selectedProductId: '',
            selectedProductName: '',
            checked: false,
            saveAlias: false,
            editQty: String(item.quantity),
            editUnit: item.unit,
            editBrand: item.brand ?? '',
            editOrigin: item.origin ?? '',
            editComment: '',
            matchSource: 'none',
            categorySuggestion: item.categorySuggestion,
            productSearch: '',
            selectedCategoryId: item.categorySuggestion?.categoryId ?? '',
          };
        }),
      );
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Kunde inte tolka kvittot');
    } finally {
      setParsing(false);
    }
  };

  const updateRow = (i: number, patch: Partial<RowState>) => {
    setRows((prev) => prev.map((r, idx) => (idx === i ? { ...r, ...patch } : r)));
  };

  const handleCreateProduct = async (i: number) => {
    const row = rows[i];
    setCreatingProduct(i);
    setError(null);
    // eslint-disable-next-line no-console
    console.log('handleCreateProduct: isAdmin =', isAdmin, 'endpoint = /api/products-create');
    try {
      // Admin skapar aktiv produkt via API route
      const res = await fetch('/api/admin/create-product', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ name: row.rawName }),
      });

      if (!res.ok) {
        const e = await res.json().catch(() => ({}));
        throw new Error(e.error ?? `HTTP ${res.status}`);
      }

      const product = await res.json();

      // Sätt kategori: manuellt val har prioritet, annars AI-förslag
      const categoryId = row.selectedCategoryId !== '' ? row.selectedCategoryId : row.categorySuggestion?.categoryId ?? null;
      if (categoryId) {
        const patchRes = await fetch(`/api/admin/update-product/${product.id}`, {
          method: 'PATCH',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({ categoryId }),
        });
        if (!patchRes.ok) {
          const e = await patchRes.json().catch(() => ({}));
          throw new Error(e.error ?? `HTTP ${patchRes.status}`);
        }
      }

      // Uppdatera produktlistan lokalt
      const newProduct = { id: product.id, name: product.name, canonicalName: product.canonicalName };
      setAllProducts((prev) => [...prev, newProduct].sort((a, b) => (a.canonicalName ?? a.name).localeCompare(b.canonicalName ?? b.name, 'sv')));

      // Markera raden som matchad
      updateRow(i, {
        selectedProductId: product.id,
        selectedProductName: product.canonicalName ?? product.name,
        productSearch: product.canonicalName ?? product.name,
        checked: true,
        matchSource: 'manual',
        saveAlias: false,
      });
    } catch (err) {
      setError(`Kunde inte skapa produkt: ${err instanceof Error ? err.message : String(err)}`);
    } finally {
      setCreatingProduct(null);
    }
  };

  const handleSuggestProduct = async (i: number) => {
    const row = rows[i];
    setCreatingProduct(i);
    setError(null);
    // eslint-disable-next-line no-console
    console.log('handleSuggestProduct: isAdmin =', isAdmin, 'endpoint = /api/products/pending');
    try {
      // Användare skapar ett pending-förslag
      const createRes = await fetch('/api/products/pending', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ name: row.rawName }),
      });
      if (!createRes.ok) {
        const e = await createRes.json().catch(() => ({}));
        throw new Error(e.message ?? `HTTP ${createRes.status}`);
      }
      const product = await createRes.json() as { id: number; name: string; canonicalName: string | null };

      // Sätt kategori om vald/föreslagen
      const categoryId = row.selectedCategoryId !== '' ? row.selectedCategoryId : row.categorySuggestion?.categoryId ?? null;
      if (categoryId) {
        await fetch(`/api/products/${product.id}`, {
          method: 'PATCH',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({ categoryId }),
        });
      }

      // Lägg till i lokal lista (men markera som pending)
      const newProduct = { id: product.id, name: product.name, canonicalName: product.canonicalName };
      setAllProducts((prev) => [...prev, newProduct].sort((a, b) => (a.canonicalName ?? a.name).localeCompare(b.canonicalName ?? b.name, 'sv')));

      // Markera raden — pending = kan läggas till i inventariet men väntar på admin-godkännande
      updateRow(i, {
        selectedProductId: product.id,
        selectedProductName: product.canonicalName ?? product.name,
        productSearch: product.canonicalName ?? product.name,
        checked: true,
        matchSource: 'manual',
        saveAlias: false,
      });
    } catch (err) {
      setError(`Kunde inte föreslå produkt: ${err instanceof Error ? err.message : String(err)}`);
    } finally {
      setCreatingProduct(null);
    }
  };

  const handleSave = async () => {
    const toSave = rows.filter((r) => r.checked && r.selectedProductId !== '');
    if (toSave.length === 0) return;
    setSaving(true);
    setError(null);
    try {
      const inventoryResults = await Promise.all(
        toSave.map((r) =>
          fetch('/api/inventory', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({
              productId: r.selectedProductId,
              quantity: parseFloat(r.editQty) || r.quantity,
              unit: r.editUnit,
              receiptName: r.rawName,
              brand: r.editBrand.trim() || undefined,
              origin: r.editOrigin.trim() || undefined,
              comment: r.editComment.trim() || undefined,
            }),
          }),
        ),
      );
      const failedInventory = inventoryResults.find((r) => !r.ok);
      if (failedInventory) {
        const e = await failedInventory.json().catch(() => ({}));
        throw new Error(e.message ?? `Inventory HTTP ${failedInventory.status}`);
      }

      await Promise.all(
        toSave
          .filter((r) => r.saveAlias && r.selectedProductId !== '')
          .map((r) =>
            fetch('/api/receipt-alias-proxy', {
              method: 'POST',
              headers: { 'Content-Type': 'application/json' },
              body: JSON.stringify({
                receiptName: r.rawName,
                productId: r.selectedProductId,
              }),
            }),
          ),
      );

      setSavedCount(toSave.length);
      setRows([]);
      setPreview(null);
      setSelectedFile(null);
      if (fileRef.current) fileRef.current.value = '';
    } catch (err) {
      setError(`Sparning misslyckades: ${err instanceof Error ? err.message : 'Okänt fel'}. Försök igen.`);
    } finally {
      setSaving(false);
    }
  };

  const checkedCount = rows.filter((r) => r.checked && r.selectedProductId !== '').length;

  // Bygg flat lista av alla kategorier med hierarki: förälder → indragna barn
  const flatCategoryOptions = (() => {
    const roots = allCategories.filter((c) => c.parentId === null).sort((a, b) => a.name.localeCompare(b.name, 'sv'));
    const result: { id: number; label: string }[] = [];
    for (const root of roots) {
      result.push({ id: root.id, label: root.name });
      const children = allCategories.filter((c) => c.parentId === root.id).sort((a, b) => a.name.localeCompare(b.name, 'sv'));
      for (const child of children) {
        result.push({ id: child.id, label: `\u00a0\u00a0↳ ${child.name}` });
      }
    }
    return result;
  })();

  const sourceLabel = (src: RowState['matchSource']) => {
    if (src === 'alias') return { text: 'Känd vara', color: '#27ae60' };
    if (src === 'suggestion') return { text: 'Förslag', color: '#e67e22' };
    if (src === 'manual') return { text: 'Manuellt vald', color: '#0070f3' };
    return null;
  };

  return (
    <div>
      {showReceiptModal && preview && preview !== 'pdf' && (
        <div
          onClick={() => setShowReceiptModal(false)}
          style={{ position: 'fixed', inset: 0, background: 'rgba(0,0,0,0.75)', zIndex: 1000, display: 'flex', alignItems: 'center', justifyContent: 'center', padding: '1rem' }}
        >
          {/* eslint-disable-next-line @next/next/no-img-element */}
          <img
            src={preview}
            alt="Kvitto"
            onClick={(e) => e.stopPropagation()}
            style={{ maxWidth: '100%', maxHeight: '90vh', borderRadius: '8px', boxShadow: '0 4px 32px rgba(0,0,0,0.5)', objectFit: 'contain' }}
          />
          <button
            onClick={() => setShowReceiptModal(false)}
            style={{ position: 'absolute', top: '1rem', right: '1rem', background: 'rgba(255,255,255,0.9)', border: 'none', borderRadius: '50%', width: '2.5rem', height: '2.5rem', fontSize: '1.25rem', cursor: 'pointer', lineHeight: 1 }}
          >✕</button>
        </div>
      )}
      <div
        style={{ border: '2px dashed #ced4da', borderRadius: '10px', padding: '1.5rem', textAlign: 'center', background: '#fafafa', marginBottom: '1rem', cursor: preview ? 'default' : 'pointer' }}
        onClick={() => { if (!preview) fileRef.current?.click(); }}
      >
        <input ref={fileRef} type="file" accept="image/*,application/pdf" capture="environment" onChange={handleFileChange} style={{ display: 'none' }} />
        {preview === 'pdf' ? (
          <div style={{ padding: '1rem' }}>
            <div style={{ fontSize: '2.5rem', marginBottom: '0.5rem' }}>📄</div>
            <div style={{ fontWeight: 600 }}>{selectedFile?.name}</div>
            <div style={{ fontSize: '0.85rem', color: '#888', marginTop: '0.25rem' }}>PDF-kvitto valt</div>
          </div>
        ) : preview ? (
          <div style={{ padding: '1rem' }}>
            {/* eslint-disable-next-line @next/next/no-img-element */}
            <img
              src={preview}
              alt="Kvittoförhandsgranskning"
              onClick={(e) => { e.stopPropagation(); setShowReceiptModal(true); }}
              style={{ maxHeight: '200px', maxWidth: '100%', borderRadius: '6px', marginBottom: '0.75rem', cursor: 'zoom-in', boxShadow: '0 1px 4px rgba(0,0,0,0.15)' }}
            />
            <div style={{ fontWeight: 600, fontSize: '0.95rem' }}>{selectedFile?.name}</div>
            <div style={{ fontSize: '0.85rem', color: '#888', marginTop: '0.25rem' }}>Klicka på bilden för att förstora • <span style={{ color: '#2563eb', cursor: 'pointer', textDecoration: 'underline' }} onClick={(e) => { e.stopPropagation(); fileRef.current?.click(); }}>Byt fil</span></div>
          </div>
        ) : (
          <div style={{ color: '#888' }}>
            <div style={{ fontSize: '2.5rem', marginBottom: '0.5rem' }}>📷</div>
            <div style={{ fontWeight: 600 }}>Fotografera eller välj kvitto</div>
            <div style={{ fontSize: '0.85rem', marginTop: '0.25rem' }}>Klicka för att välja bild (JPEG, PNG, WebP) eller PDF</div>
          </div>
        )}
      </div>

      {productsError && (
        <p style={{ color: '#c0392b', background: '#fdf0ef', padding: '0.75rem 1rem', borderRadius: '6px', marginTop: '0.75rem', fontSize: '0.9rem' }}>
          ⚠️ {productsError}
        </p>
      )}

      {preview && rows.length === 0 && (
        <button onClick={handleParse} disabled={parsing} style={primaryBtn(parsing)}>
          {parsing ? '⏳ Läser kvitto...' : '🔍 Läs kvitto'}
        </button>
      )}

      {error && (
        <p style={{ color: '#c0392b', background: '#fdf0ef', padding: '0.75rem 1rem', borderRadius: '6px', marginTop: '0.75rem' }}>{error}</p>
      )}

      {savedCount !== null && (
        <p style={{ color: '#27ae60', background: '#edfdf4', padding: '0.75rem 1rem', borderRadius: '6px', marginTop: '0.75rem', fontWeight: 600 }}>
          ✓ {savedCount} {savedCount === 1 ? 'vara lades till' : 'varor lades till'} i inventariet.
        </p>
      )}

      {rows.length > 0 && (
        <div style={{ marginTop: '1.25rem' }}>
          {!isAdmin && (
            <div style={{ fontSize: '0.82rem', color: '#92400e', background: '#fffbeb', border: '1px solid #fde68a', borderRadius: '6px', padding: '0.6rem 0.9rem', marginBottom: '0.75rem' }}>
              <strong>Tips:</strong> Om en vara saknas kan du klicka <em>Föreslå ny vara</em> — varan läggs till i inventariet och skickas för granskning av en administratör.
            </div>
          )}
          <div style={{ marginBottom: '0.75rem', display: 'flex', gap: '1rem', alignItems: 'baseline', flexWrap: 'wrap' }}>
            <h2 style={{ margin: 0, fontSize: '1.05rem' }}>Identifierade varor ({rows.length})</h2>
            <span style={{ fontSize: '0.8rem', color: '#888' }}>
              🟢 Känd = automatiskt markerad · 🟠 Förslag = markera för att inkludera · {isAdmin ? 'Sök eller skapa ny produkt' : 'Sök eller föreslå ny vara'}
            </span>
          </div>

          <div style={{ display: 'grid', gap: '0.5rem', marginBottom: '1rem' }}>
            {rows.map((row, i) => {
              const label = sourceLabel(row.matchSource);
              return (
                <div key={i} style={{ padding: '0.75rem 1rem', border: `1px solid ${row.matchSource === 'alias' ? '#a8d5b5' : row.matchSource === 'suggestion' ? '#f5cba7' : '#dee2e6'}`, borderRadius: '8px', background: row.matchSource === 'alias' ? '#f0faf4' : row.matchSource === 'suggestion' ? '#fef9f5' : '#fff' }}>
                  <div style={{ display: 'flex', alignItems: 'center', gap: '0.6rem', marginBottom: '0.5rem', flexWrap: 'wrap' }}>
                    <input type="checkbox" checked={row.checked} disabled={row.selectedProductId === ''} onChange={(e) => updateRow(i, { checked: e.target.checked })} style={{ width: '18px', height: '18px', cursor: row.selectedProductId !== '' ? 'pointer' : 'not-allowed' }} />
                    <span style={{ fontWeight: 500 }}>{row.rawName}</span>
                    {label && (
                      <span style={{ fontSize: '0.75rem', color: label.color, border: `1px solid ${label.color}`, borderRadius: '4px', padding: '1px 6px' }}>{label.text}</span>
                    )}
                  </div>
                  <div style={{ display: 'grid', gridTemplateColumns: '1fr 120px 80px 90px', gap: '0.5rem', alignItems: 'center' }}>
                    <div style={{ position: 'relative' }}>
                      <input
                        list={`products-${i}`}
                        value={row.productSearch}
                        onChange={(e) => {
                          const val = e.target.value;
                          updateRow(i, { productSearch: val });
                          // Hitta exakt match
                          const match = allProducts.find(
                            (p) => (p.canonicalName ?? p.name) === val
                          );
                          if (match) {
                            updateRow(i, {
                              productSearch: val,
                              selectedProductId: match.id,
                              selectedProductName: match.canonicalName ?? match.name,
                              checked: true,
                              matchSource: row.matchSource === 'alias' ? 'alias' : 'manual',
                              saveAlias: row.matchSource !== 'alias',
                            });
                          } else {
                            updateRow(i, {
                              productSearch: val,
                              selectedProductId: '',
                              selectedProductName: '',
                              checked: false,
                            });
                          }
                        }}
                        placeholder={productsLoading ? 'Laddar produkter...' : 'Sök produkt...'}
                        disabled={productsLoading}
                        style={{ width: '100%', padding: '0.35rem 0.5rem', border: `1px solid ${row.selectedProductId !== '' ? '#22c55e' : '#ced4da'}`, borderRadius: '6px', fontSize: '0.9rem', boxSizing: 'border-box' }}
                      />
                      <datalist id={`products-${i}`}>
                        {allProducts.map((p) => (
                          <option key={p.id} value={p.canonicalName ?? p.name} />
                        ))}
                      </datalist>
                    </div>
                    <input type="number" min="0" step="0.01" value={row.editQty} onChange={(e) => updateRow(i, { editQty: e.target.value })} style={{ padding: '0.35rem 0.5rem', border: '1px solid #ced4da', borderRadius: '6px', fontSize: '0.9rem' }} />
                    <select value={row.editUnit} onChange={(e) => updateRow(i, { editUnit: e.target.value })} style={{ padding: '0.35rem 0.5rem', border: '1px solid #ced4da', borderRadius: '6px', fontSize: '0.9rem' }}>
                      {UNITS.map((u) => <option key={u} value={u}>{u}</option>)}
                    </select>
                  </div>
                  <div style={{ marginTop: '0.4rem', display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '0.4rem' }}>
                    <input
                      type="text"
                      value={row.editBrand}
                      onChange={(e) => updateRow(i, { editBrand: e.target.value })}
                      placeholder="Märke / leverantör (valfritt)"
                      style={{ padding: '0.3rem 0.5rem', border: '1px solid #ced4da', borderRadius: '6px', fontSize: '0.82rem', color: '#555' }}
                    />
                    <input
                      type="text"
                      value={row.editOrigin}
                      onChange={(e) => updateRow(i, { editOrigin: e.target.value })}
                      placeholder="Ursprungsland (valfritt)"
                      style={{ padding: '0.3rem 0.5rem', border: '1px solid #ced4da', borderRadius: '6px', fontSize: '0.82rem', color: '#555' }}
                    />
                  </div>
                  <div style={{ marginTop: '0.4rem' }}>
                    <input
                      type="text"
                      value={row.editComment}
                      onChange={(e) => updateRow(i, { editComment: e.target.value })}
                      placeholder="Kommentar, t.ex. styckning, kvalitet... (valfritt)"
                      style={{ width: '100%', padding: '0.3rem 0.5rem', border: '1px solid #ced4da', borderRadius: '6px', fontSize: '0.82rem', color: '#555', boxSizing: 'border-box' }}
                    />
                  </div>
                  {row.matchSource === 'none' && (
                    <div style={{ marginTop: '0.5rem', display: 'flex', alignItems: 'center', gap: '0.5rem', flexWrap: 'wrap' }}>
                      <select
                        value={row.selectedCategoryId}
                        onChange={(e) => updateRow(i, { selectedCategoryId: e.target.value === '' ? '' : Number(e.target.value) })}
                        style={{ fontSize: '0.8rem', padding: '3px 6px', border: '1px solid #d1d5db', borderRadius: '5px', color: '#374151', maxWidth: '260px' }}
                      >
                        <option value="">— Välj kategori —</option>
                        {flatCategoryOptions.map((c) => (
                          <option key={c.id} value={c.id}>{c.label}</option>
                        ))}
                      </select>
                      {row.categorySuggestion && (
                        <span style={{ fontSize: '0.75rem', color: '#7c3aed', background: '#f5f3ff', border: '1px solid #ddd6fe', borderRadius: '5px', padding: '2px 7px', display: 'inline-flex', alignItems: 'center', gap: '0.3rem' }}>
                          ✨ AI: {row.categorySuggestion.path}{row.categorySuggestion.usedFallback && <span style={{ color: '#b45309' }}> (osäker)</span>}
                        </span>
                      )}
                      {isAdmin ? (
                        <button
                          onClick={() => handleCreateProduct(i)}
                          disabled={creatingProduct === i}
                          style={{ fontSize: '0.8rem', padding: '3px 10px', background: creatingProduct === i ? '#e5e7eb' : '#f0fdf4', color: creatingProduct === i ? '#9ca3af' : '#166534', border: '1px solid #bbf7d0', borderRadius: '5px', cursor: creatingProduct === i ? 'not-allowed' : 'pointer', fontWeight: 500 }}
                        >
                          {creatingProduct === i ? '⏳ Skapar...' : '+ Skapa ny produkt'}
                        </button>
                      ) : (
                        <button
                          onClick={() => handleSuggestProduct(i)}
                          disabled={creatingProduct === i}
                          style={{ fontSize: '0.8rem', padding: '3px 10px', background: creatingProduct === i ? '#e5e7eb' : '#fefce8', color: creatingProduct === i ? '#9ca3af' : '#854d0e', border: '1px solid #fde68a', borderRadius: '5px', cursor: creatingProduct === i ? 'not-allowed' : 'pointer', fontWeight: 500 }}
                        >
                          {creatingProduct === i ? '⏳ Skickar...' : '+ Föreslå ny vara'}
                        </button>
                      )}
                    </div>
                  )}
                  {row.selectedProductId !== '' && row.matchSource !== 'alias' && (
                    <label style={{ display: 'flex', alignItems: 'center', gap: '0.4rem', marginTop: '0.5rem', fontSize: '0.82rem', color: '#555', cursor: 'pointer' }}>
                      <input type="checkbox" checked={row.saveAlias} onChange={(e) => updateRow(i, { saveAlias: e.target.checked })} />
                      Kom ihåg kopplingen — nästa gång matchas &quot;{row.rawName}&quot; automatiskt
                    </label>
                  )}
                </div>
              );
            })}
          </div>

          <div style={{ display: 'flex', gap: '0.75rem', alignItems: 'center' }}>
            <button onClick={handleSave} disabled={saving || checkedCount === 0} style={primaryBtn(saving || checkedCount === 0)}>
              {saving ? 'Sparar...' : `Lägg till ${checkedCount} ${checkedCount === 1 ? 'vara' : 'varor'} i inventariet`}
            </button>
            <button onClick={() => { setRows([]); setPreview(null); setSelectedFile(null); if (fileRef.current) fileRef.current.value = ''; }} style={{ padding: '0.5rem 1rem', background: '#f0f0f0', border: '1px solid #ccc', borderRadius: '6px', cursor: 'pointer', fontSize: '0.9rem' }}>
              Börja om
            </button>
          </div>
        </div>
      )}
    </div>
  );
}

function primaryBtn(disabled: boolean): React.CSSProperties {
  return { padding: '0.6rem 1.25rem', background: disabled ? '#aaa' : '#0070f3', color: '#fff', border: 'none', borderRadius: '6px', cursor: disabled ? 'not-allowed' : 'pointer', fontWeight: 600, fontSize: '0.95rem' };
}
