'use client';

import { useState, useTransition } from 'react';
import type { Product } from '../../features/inventory/types';
import { addPantryItem } from './actions';

type Props = {
  products: Product[];
  pantryProductIds: Set<number>;
};

export default function AddToPantryForm({ products, pantryProductIds }: Props) {
  const [selectedId, setSelectedId] = useState('');
  const [isPending, startTransition] = useTransition();
  const [error, setError] = useState<string | null>(null);

  const available = products.filter((p) => !pantryProductIds.has(p.id));

  function handleSubmit(e: React.FormEvent) {
    e.preventDefault();
    if (!selectedId) return;
    setError(null);
    startTransition(async () => {
      try {
        await addPantryItem(Number(selectedId));
        setSelectedId('');
      } catch (err) {
        setError(err instanceof Error ? err.message : 'Okänt fel');
      }
    });
  }

  return (
    <form onSubmit={handleSubmit} style={{ display: 'flex', gap: '0.5rem', flexWrap: 'wrap', alignItems: 'center' }}>
      <select
        value={selectedId}
        onChange={(e) => setSelectedId(e.target.value)}
        required
        style={{
          flex: '1 1 220px',
          padding: '0.6rem 0.75rem',
          border: '1px solid #ddd',
          borderRadius: '6px',
          fontSize: '1rem',
        }}
      >
        <option value="">Välj produkt…</option>
        {available.map((p) => (
          <option key={p.id} value={p.id}>
            {p.canonicalName || p.name}
          </option>
        ))}
      </select>
      <button
        type="submit"
        disabled={isPending || !selectedId}
        style={{
          padding: '0.6rem 1.25rem',
          background: '#0070f3',
          color: '#fff',
          border: 'none',
          borderRadius: '6px',
          fontWeight: 600,
          cursor: isPending || !selectedId ? 'not-allowed' : 'pointer',
          opacity: isPending || !selectedId ? 0.6 : 1,
          fontSize: '1rem',
        }}
      >
        {isPending ? 'Lägger till…' : 'Lägg till'}
      </button>
      {error && <span style={{ color: 'crimson', fontSize: '0.9rem' }}>{error}</span>}
    </form>
  );
}
