'use client';

import { useState, useEffect } from 'react';
import { useRouter } from 'next/navigation';
import { fetchJson } from '../../../lib/api';
import type { Product } from '../../../features/inventory/types';

export default function CreateRecipePage() {
  const router = useRouter();
  const [recipe, setRecipe] = useState({
    name: '',
    description: '',
    instructions: '',
    ingredients: [{ productId: 0, quantity: '', unit: '', note: '' }],
  });
  const [products, setProducts] = useState<Product[]>([]);
  const [isLoading, setIsLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    fetchJson('/api/products')
      .then(setProducts)
      .catch(console.error);
  }, []);

  const handleIngredientChange = (index: number, field: string, value: string | number) => {
    const newIngredients = [...recipe.ingredients];
    newIngredients[index] = { ...newIngredients[index], [field]: value };
    setRecipe({ ...recipe, ingredients: newIngredients });
  };

  const addIngredient = () => {
    setRecipe({
      ...recipe,
      ingredients: [...recipe.ingredients, { productId: 0, quantity: '', unit: '', note: '' }],
    });
  };

  const removeIngredient = (index: number) => {
    const newIngredients = [...recipe.ingredients];
    newIngredients.splice(index, 1);
    setRecipe({ ...recipe, ingredients: newIngredients });
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setIsLoading(true);
    setError(null);

    // Konvertera quantity till number för varje ingrediens
    const recipeToSend = {
      ...recipe,
      ingredients: recipe.ingredients.map((ing) => ({
        ...ing,
        quantity: Number(ing.quantity),
      })),
    };

    try {
      const response = await fetch('/api/recipes', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(recipeToSend),
      });

      if (!response.ok) {
        throw new Error('Kunde inte spara receptet');
      }

      router.push('/recipes');
    } catch (err) {
      setError((err as Error).message);
    } finally {
      setIsLoading(false);
    }
  };

  return (
    <main style={{ padding: '1.5rem', maxWidth: '800px', margin: '0 auto' }}>
      <h1>Lägg till nytt recept</h1>

      {error && <p style={{ color: 'red' }}>{error}</p>}

      <form onSubmit={handleSubmit} style={{ display: 'grid', gap: '1rem' }}>
        <div style={{ display: 'grid', gap: '0.5rem' }}>
          <label>
            Receptnamn:
            <input
              type="text"
              value={recipe.name}
              onChange={(e) => setRecipe({ ...recipe, name: e.target.value })}
              required
              style={{ width: '100%', padding: '0.5rem' }}
            />
          </label>

          <label>
            Beskrivning:
            <textarea
              value={recipe.description}
              onChange={(e) => setRecipe({ ...recipe, description: e.target.value })}
              style={{ width: '100%', padding: '0.5rem', minHeight: '100px' }}
            />
          </label>

          <label>
            Instruktioner:
            <textarea
              value={recipe.instructions}
              onChange={(e) => setRecipe({ ...recipe, instructions: e.target.value })}
              style={{ width: '100%', padding: '0.5rem', minHeight: '100px' }}
            />
          </label>
        </div>

        <h2>Ingredienser</h2>
        {recipe.ingredients.map((ingredient, index) => (
          <div key={index} style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr 1fr auto', gap: '0.5rem', alignItems: 'center' }}>
            <select
              value={ingredient.productId}
              onChange={(e) => handleIngredientChange(index, 'productId', Number(e.target.value))}
              required
              style={{ padding: '0.5rem' }}
            >
              <option value={0}>Välj produkt</option>
              {products.map((product) => (
                <option key={product.id} value={product.id}>
                  {product.name}
                </option>
              ))}
            </select>

            <input
              type="text"
              placeholder="Mängd"
              value={ingredient.quantity}
              onChange={(e) => handleIngredientChange(index, 'quantity', e.target.value)}
              required
              style={{ padding: '0.5rem' }}
            />

            <input
              type="text"
              placeholder="Enhet (t.ex. g, st, dl)"
              value={ingredient.unit}
              onChange={(e) => handleIngredientChange(index, 'unit', e.target.value)}
              required
              style={{ padding: '0.5rem' }}
            />

            <input
              type="text"
              placeholder="Notering (valfritt)"
              value={ingredient.note || ''}
              onChange={(e) => handleIngredientChange(index, 'note', e.target.value)}
              style={{ padding: '0.5rem' }}
            />

            <button type="button" onClick={() => removeIngredient(index)} style={{ padding: '0.5rem' }}>
              Ta bort
            </button>
          </div>
        ))}

        {products.length === 0 && (
          <div style={{ color: 'red' }}>
            Kunde inte ladda produkter. Kontrollera API:et.
          </div>
        )}

        <div style={{ display: 'flex', gap: '1rem' }}>
          <button type="button" onClick={addIngredient} style={{ padding: '0.5rem' }}>
            Lägg till ingrediens
          </button>
          <button type="submit" disabled={isLoading} style={{ padding: '0.5rem' }}>
            {isLoading ? 'Sparar...' : 'Spara recept'}
          </button>
        </div>
      </form>
    </main>
  );
}