'use client';

import { useState } from 'react';
import { useRouter } from 'next/navigation';
import type { Product } from '../../features/inventory/types';

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

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

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

  async function handleSubmit(e: React.FormEvent) {
    e.preventDefault();
    if (!selectedId) return;
    setError(null);
    setIsPending(true);
    try {
      const res = await fetch('/api/admin/pantry-item', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ productId: Number(selectedId) }),
      });
      if (!res.ok) {
        const data = await res.json().catch(() => ({}));
        throw new Error(data?.error || 'Kunde inte lägga till');
      }
      setSelectedId('');
      router.refresh();
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Okänt fel');
    } finally {
      setIsPending(false);
    }
  }

  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>
  );
}
