'use client';

import { useState } from 'react';
import { useRouter } from 'next/navigation';

export default function ProductForm() {
  const [isPending, setIsPending] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const router = useRouter();

  return (
    <form
      onSubmit={async (e) => {
        e.preventDefault();
        setError(null);

        const form = e.currentTarget;
        const name = String((new FormData(form)).get('name') || '').trim();

        setIsPending(true);
        try {
          const res = await fetch('/api/admin/create-product', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ name }),
          });
          if (!res.ok) {
            const data = await res.json().catch(() => ({}));
            throw new Error(data?.error || 'Kunde inte skapa produkt');
          }
          form.reset();
          router.refresh();
        } catch (err) {
          setError(err instanceof Error ? err.message : 'Okänt fel');
        } finally {
          setIsPending(false);
        }
      }}
      style={{
        display: 'grid',
        gap: '0.75rem',
        padding: '1rem',
        border: '1px solid #ddd',
        borderRadius: '8px',
        marginBottom: '1.5rem',
      }}
    >
      <h2 style={{ margin: 0 }}>Skapa produkt</h2>

      <label style={{ display: 'block', marginBottom: '0.5rem', fontWeight: 600 }}>
        Produktnamn
      </label>
      <input
        name="name"
        type="text"
        required
        placeholder="Till exempel Rödkål"
        style={{ 
          width: '100%', 
          padding: '0.75rem',
          border: '1px solid #ddd',
          borderRadius: '4px',
          fontSize: '1rem',
          boxSizing: 'border-box',
          minHeight: '44px',
        }}
      />

      <button 
        type="submit" 
        disabled={isPending} 
        style={{ 
          padding: '0.75rem 1.5rem',
          background: '#0070f3',
          color: 'white',
          border: 'none',
          borderRadius: '4px',
          cursor: 'pointer',
          fontSize: '1rem',
          minHeight: '44px',
          fontWeight: 600,
        }}
      >
        {isPending ? 'Sparar...' : 'Skapa produkt'}
      </button>

      {error ? <p style={{ color: 'crimson', margin: 0 }}>{error}</p> : null}
    </form>
  );
}
