'use client';

import { useState, useEffect } from 'react';
import { useRouter, useParams } from 'next/navigation';
import { fetchJson } from '../../../../lib/api';
import { parseErrorResponse } from '../../../../lib/error-handler';
import type { Product, Recipe } from '../../../../features/inventory/types';

export default function EditRecipePage() {
  const router = useRouter();
  const params = useParams();
  const recipeId = params && (Array.isArray(params.id) ? params.id[0] : params.id);

  const [recipe, setRecipe] = useState({
    name: '',
    description: '',
    instructions: '',
    ingredients: [{ productId: 0, quantity: '', unit: '', note: '', location: '' }],
  });
  const [products, setProducts] = useState<Product[]>([]);
  const [isLoading, setIsLoading] = useState(true);
  const [isSaving, setIsSaving] = useState(false);
  const [isDeleting, setIsDeleting] = useState(false);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    const loadData = async () => {
      if (!recipeId) {
        setError('Receptet hittades inte.');
        setIsLoading(false);
        return;
      }

      try {
        // Ladda produkter
        const productsData = await fetchJson<Product[]>('/api/products');
        setProducts(productsData);

        // Ladda receptet
        const recipeData = await fetchJson<Recipe>(`/api/recipes/${recipeId}`);
        setRecipe({
          name: recipeData.name,
          description: recipeData.description || '',
          instructions: recipeData.instructions || '',
          ingredients: recipeData.ingredients.map((ing: any) => ({
            productId: ing.productId,
            quantity: ing.quantity.toString(),
            unit: ing.unit,
            note: ing.note || '',
            location: ing.location || '',
          })),
        });
      } catch (err) {
        setError((err as Error).message);
      } finally {
        setIsLoading(false);
      }
    };

    loadData();
  }, [recipeId]);

  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: '', location: '' }],
    });
  };

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

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

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

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

      if (!response.ok) {
        const errorMessage = await parseErrorResponse(response);
        throw new Error(errorMessage);
      }

      router.push('/recipes');
    } catch (err) {
      const message = err instanceof Error ? err.message : 'Ett okänt fel inträffade. Försök igen.';
      setError(message);
    } finally {
      setIsSaving(false);
    }
  };

  const UNIT_OPTIONS = [
    { value: '', label: 'Välj enhet' },
    { value: 'g', label: 'g (gram)' },
    { value: 'kg', label: 'kg (kilogram)' },
    { value: 'hg', label: 'hg (hektogram)' },
    { value: 'ml', label: 'ml (milliliter)' },
    { value: 'dl', label: 'dl (deciliter)' },
    { value: 'l', label: 'l (liter)' },
    { value: 'st', label: 'st (styck)' },
    { value: 'tsk', label: 'tsk (tesked)' },
    { value: 'msk', label: 'msk (matsked)' },
  ];

  const LOCATION_OPTIONS = [
    { value: '', label: 'Välj plats' },
    { value: 'Kyl', label: 'Kyl' },
    { value: 'Frys', label: 'Frys' },
    { value: 'Skafferi', label: 'Skafferi' },
    { value: 'Annat', label: 'Annat' },
  ];

  if (isLoading) {
    return (
      <main style={{ padding: '1.5rem', maxWidth: '800px', margin: '0 auto' }}>
        <p>Laddar recept...</p>
      </main>
    );
  }

  return (
    <main style={{ padding: '1.5rem', maxWidth: '800px', margin: '0 auto' }}>
      <h1>Redigera 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.length > 0 ? products.map((product) => (
                <option key={product.id} value={product.id}>
                  {product.name}
                </option>
              )) : <option disabled>Kunde inte ladda produkter</option>}
            </select>

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

            <select
              value={ingredient.unit}
              onChange={(e) => handleIngredientChange(index, 'unit', e.target.value)}
              required
              style={{ padding: '0.5rem' }}
            >
              {UNIT_OPTIONS.map((opt) => (
                <option key={opt.value} value={opt.value}>
                  {opt.label}
                </option>
              ))}
            </select>

            <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', flexWrap: 'wrap', justifyContent: 'space-between' }}>
          <div style={{ display: 'flex', gap: '1rem' }}>
            <button type="button" onClick={addIngredient} style={{ padding: '0.5rem' }}>
              Lägg till ingrediens
            </button>
            <button type="submit" disabled={isSaving || isDeleting} style={{ padding: '0.5rem' }}>
              {isSaving ? 'Uppdaterar...' : 'Uppdatera recept'}
            </button>
            <button
              type="button"
              onClick={() => router.push('/recipes')}
              style={{ padding: '0.5rem', background: '#f0f0f0', color: '#333', border: '1px solid #ccc', borderRadius: '4px', cursor: 'pointer' }}
            >
              Avbryt
            </button>
          </div>
          <button
            type="button"
            disabled={isSaving || isDeleting}
            onClick={async () => {
              if (!confirm('Är du säker på att du vill radera detta recept? Detta kan inte ångras.')) return;
              setIsDeleting(true);
              setError(null);
              try {
                const res = await fetch(`/api/recipes/${recipeId}`, { method: 'DELETE' });
                if (!res.ok) {
                  const errorMessage = await parseErrorResponse(res);
                  throw new Error(errorMessage);
                }
                router.push('/recipes');
              } catch (err) {
                setError(err instanceof Error ? err.message : 'Kunde inte radera receptet.');
              } finally {
                setIsDeleting(false);
              }
            }}
            style={{ padding: '0.5rem 1rem', background: '#c0392b', color: 'white', border: 'none', borderRadius: '4px', cursor: 'pointer' }}
          >
            {isDeleting ? 'Raderar...' : 'Radera recept'}
          </button>
        </div>
      </form>
    </main>
  );
}
