'use client';

import { useState, useEffect } from 'react';
import { useRouter } from 'next/navigation';
import { useAuthFetch } from '../../../lib/use-auth-fetch';
import { fetchJson } from '../../../lib/api';
import { parseErrorResponse } from '../../../lib/error-handler';
import type { Product } from '../../../features/inventory/types';
import { UNIT_OPTIONS } from '../../../lib/units';

type ProductSuggestion = {
  productId: number;
  productName: string;
  score: number;
};

type ParsedIngredientRow = {
  rawName: string;
  quantity: number;
  unit: string;
  note?: string;
  suggestions: ProductSuggestion[];
  // Valda värden (redigerbara i steg 2)
  selectedProductId: number;
  editedQuantity: string;
  editedUnit: string;
  editedNote: string;
};

type ParseResult = {
  name: string;
  description?: string;
  instructions?: string;
  ingredients: ParsedIngredientRow[];
};

type Step = 'input' | 'review' | 'saving';

export default function ImportRecipePage() {
  const router = useRouter();
  const authFetch = useAuthFetch();
  const [step, setStep] = useState<Step>('input');
  const [markdown, setMarkdown] = useState('');
  const [parsed, setParsed] = useState<ParseResult | null>(null);
  const [editedName, setEditedName] = useState('');
  const [editedDescription, setEditedDescription] = useState('');
  const [editedInstructions, setEditedInstructions] = useState('');
  const [ingredients, setIngredients] = useState<ParsedIngredientRow[]>([]);
  const [allProducts, setAllProducts] = useState<Product[]>([]);
  const [isParsing, setIsParsing] = useState(false);
  const [isSaving, setIsSaving] = useState(false);
  const [error, setError] = useState<string | null>(null);

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

  const handleParse = async () => {
    if (!markdown.trim()) return;
    setIsParsing(true);
    setError(null);

    try {
      const res = await fetch('/api/parse-markdown-proxy', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ markdown }),
      });

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

      const data = await res.json();

      const rows: ParsedIngredientRow[] = data.ingredients.map(
        (ing: Omit<ParsedIngredientRow, 'selectedProductId' | 'editedQuantity' | 'editedUnit' | 'editedNote'>) => ({
          ...ing,
          selectedProductId: ing.suggestions[0]?.productId ?? 0,
          editedQuantity: String(ing.quantity),
          editedUnit: ing.unit,
          editedNote: ing.note ?? '',
        }),
      );

      setParsed(data);
      setEditedName(data.name);
      setEditedDescription(data.description ?? '');
      setEditedInstructions(data.instructions ?? '');
      setIngredients(rows);
      setStep('review');
    } catch (err) {
      const message = err instanceof Error ? err.message : 'Något gick fel vid tolkning.';
      setError(message);
    } finally {
      setIsParsing(false);
    }
  };

  const updateIngredient = (index: number, field: keyof ParsedIngredientRow, value: string | number) => {
    setIngredients((prev) => {
      const updated = [...prev];
      updated[index] = { ...updated[index], [field]: value };
      return updated;
    });
  };

  const removeIngredient = (index: number) => {
    setIngredients((prev) => prev.filter((_, i) => i !== index));
  };

  const handleSave = async () => {
    setIsSaving(true);
    setError(null);

    const validIngredients = ingredients.filter((ing) => ing.selectedProductId > 0);
    if (validIngredients.length === 0) {
      setError('Minst en ingrediens med vald produkt krävs.');
      setIsSaving(false);
      return;
    }

    const body = {
      name: editedName,
      description: editedDescription || undefined,
      instructions: editedInstructions || undefined,
      ingredients: validIngredients.map((ing) => ({
        productId: ing.selectedProductId,
        quantity: Number(ing.editedQuantity),
        unit: ing.editedUnit,
        note: ing.editedNote || undefined,
      })),
    };

    try {
      const res = await authFetch('/api/recipes', {
        method: 'POST',
        body: JSON.stringify(body),
      });

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

      router.push('/recipes');
    } catch (err) {
      const message = err instanceof Error ? err.message : 'Något gick fel vid sparning.';
      setError(message);
    } finally {
      setIsSaving(false);
    }
  };

  return (
    <main style={{ padding: '1rem', maxWidth: '1000px', margin: '0 auto' }}>
      <h1 style={{ marginBottom: '0.5rem' }}>Importera recept från Markdown</h1>

      {/* Steg-indikator */}
      <div style={{ display: 'flex', gap: '0.5rem', marginBottom: '1.5rem', fontSize: '0.9rem', color: '#666' }}>
        <span style={{ fontWeight: step === 'input' ? 700 : 400, color: step === 'input' ? '#0070f3' : '#666' }}>
          1. Klistra in
        </span>
        <span>→</span>
        <span style={{ fontWeight: step === 'review' ? 700 : 400, color: step === 'review' ? '#0070f3' : '#666' }}>
          2. Granska
        </span>
        <span>→</span>
        <span style={{ color: '#999' }}>3. Spara</span>
      </div>

      {error && (
        <p style={{ color: 'crimson', backgroundColor: '#ffe5e5', padding: '0.75rem', borderRadius: '4px', marginBottom: '1rem' }}>
          {error}
        </p>
      )}

      {/* STEG 1: Markdown-inmatning */}
      {step === 'input' && (
        <section style={{ display: 'grid', gap: '1rem' }}>
          <div style={{ background: '#f9f9f9', border: '1px solid #ddd', borderRadius: '8px', padding: '1rem', fontSize: '0.875rem', color: '#555' }}>
            <strong>Förväntat format:</strong>
            <pre style={{ margin: '0.5rem 0 0', fontFamily: 'monospace', whiteSpace: 'pre-wrap', lineHeight: 1.6 }}>{`# Receptnamn

Valfri beskrivning av receptet.

## Ingredienser
- 500 g köttfärs
- 1 st lök
- 2 msk tomatpuré
- 1 dl grädde (vispgrädde)

## Tillvägagångssätt
Stek löken i lite smör. Tillsätt köttfärsen...`}</pre>
          </div>

          <div>
            <label style={{ display: 'block', marginBottom: '0.5rem', fontWeight: 600 }}>
              Klistra in ditt recept i Markdown-format
            </label>
            <textarea
              value={markdown}
              onChange={(e) => setMarkdown(e.target.value)}
              placeholder="# Mitt recept&#10;&#10;## Ingredienser&#10;- 500 g köttfärs"
              style={{
                width: '100%',
                padding: '0.75rem',
                border: '1px solid #ddd',
                borderRadius: '4px',
                fontSize: '1rem',
                minHeight: '300px',
                fontFamily: 'monospace',
                boxSizing: 'border-box',
              }}
            />
          </div>

          <div style={{ display: 'flex', gap: '1rem' }}>
            <button
              onClick={handleParse}
              disabled={isParsing || !markdown.trim()}
              style={{
                padding: '0.75rem 1.5rem',
                background: '#0070f3',
                color: 'white',
                border: 'none',
                borderRadius: '4px',
                cursor: isParsing || !markdown.trim() ? 'not-allowed' : 'pointer',
                opacity: isParsing || !markdown.trim() ? 0.6 : 1,
                fontSize: '1rem',
                fontWeight: 500,
              }}
            >
              {isParsing ? 'Tolkar...' : 'Tolka recept'}
            </button>
            <button
              onClick={() => router.push('/recipes')}
              style={{ padding: '0.75rem 1rem', background: 'transparent', border: '1px solid #ddd', borderRadius: '4px', cursor: 'pointer', fontSize: '1rem' }}
            >
              Avbryt
            </button>
          </div>
        </section>
      )}

      {/* STEG 2: Granskning */}
      {step === 'review' && parsed && (
        <section style={{ display: 'grid', gap: '1.5rem' }}>
          {/* Receptdetaljer */}
          <div style={{ display: 'grid', gap: '1rem', padding: '1rem', border: '1px solid #ddd', borderRadius: '8px' }}>
            <h2 style={{ margin: 0, fontSize: '1.1rem' }}>Receptdetaljer</h2>

            <div>
              <label style={{ display: 'block', marginBottom: '0.5rem', fontWeight: 600 }}>Receptnamn *</label>
              <input
                type="text"
                value={editedName}
                onChange={(e) => setEditedName(e.target.value)}
                required
                style={{ width: '100%', padding: '0.75rem', border: '1px solid #ddd', borderRadius: '4px', fontSize: '1rem', boxSizing: 'border-box' }}
              />
            </div>

            <div>
              <label style={{ display: 'block', marginBottom: '0.5rem', fontWeight: 600 }}>Beskrivning</label>
              <textarea
                value={editedDescription}
                onChange={(e) => setEditedDescription(e.target.value)}
                style={{ width: '100%', padding: '0.75rem', border: '1px solid #ddd', borderRadius: '4px', fontSize: '1rem', minHeight: '80px', fontFamily: 'inherit', boxSizing: 'border-box' }}
              />
            </div>

            <div>
              <label style={{ display: 'block', marginBottom: '0.5rem', fontWeight: 600 }}>Instruktioner</label>
              <textarea
                value={editedInstructions}
                onChange={(e) => setEditedInstructions(e.target.value)}
                style={{ width: '100%', padding: '0.75rem', border: '1px solid #ddd', borderRadius: '4px', fontSize: '1rem', minHeight: '150px', fontFamily: 'monospace', boxSizing: 'border-box' }}
              />
            </div>
          </div>

          {/* Ingredienser */}
          <div style={{ display: 'grid', gap: '0.75rem', padding: '1rem', border: '1px solid #ddd', borderRadius: '8px' }}>
            <h2 style={{ margin: 0, fontSize: '1.1rem' }}>
              Ingredienser{' '}
              <span style={{ fontWeight: 400, fontSize: '0.875rem', color: '#666' }}>
                — välj produkt från databasen för varje rad
              </span>
            </h2>

            {ingredients.map((ing, index) => (
              <div
                key={index}
                style={{ display: 'grid', gap: '0.5rem', padding: '0.75rem', background: '#f9f9f9', borderRadius: '6px', border: '1px solid #eee' }}
              >
                {/* Rå text från Markdown */}
                <div style={{ fontSize: '0.85rem', color: '#888', fontStyle: 'italic' }}>
                  Tolkad som: <strong style={{ color: '#555' }}>{ing.rawName}</strong>
                  {ing.suggestions.length > 0 && (
                    <span style={{ marginLeft: '0.5rem', color: '#0070f3' }}>
                      (bästa match: {ing.suggestions[0].productName}, {ing.suggestions[0].score}%)
                    </span>
                  )}
                </div>

                <div style={{ display: 'grid', gridTemplateColumns: '2fr 1fr 1fr auto', gap: '0.5rem', alignItems: 'end' }}>
                  {/* Produktval */}
                  <div>
                    <label style={{ display: 'block', marginBottom: '0.25rem', fontSize: '0.85rem', fontWeight: 600 }}>Produkt *</label>
                    <select
                      value={ing.selectedProductId}
                      onChange={(e) => updateIngredient(index, 'selectedProductId', Number(e.target.value))}
                      style={{ width: '100%', padding: '0.5rem', border: ing.selectedProductId === 0 ? '1px solid #f59e0b' : '1px solid #ddd', borderRadius: '4px', fontSize: '0.9rem', background: ing.selectedProductId === 0 ? '#fffbeb' : 'white' }}
                    >
                      <option value={0}>— Välj produkt —</option>
                      {/* Förslag från backend (sorterade efter matchningspoäng) */}
                      {ing.suggestions.length > 0 && (
                        <optgroup label="Föreslagna matchningar">
                          {ing.suggestions.map((s) => (
                            <option key={s.productId} value={s.productId}>
                              {s.productName} ({s.score}%)
                            </option>
                          ))}
                        </optgroup>
                      )}
                      <optgroup label="Alla produkter">
                        {allProducts.map((p) => (
                          <option key={p.id} value={p.id}>
                            {p.canonicalName || p.name}
                          </option>
                        ))}
                      </optgroup>
                    </select>
                  </div>

                  {/* Mängd */}
                  <div>
                    <label style={{ display: 'block', marginBottom: '0.25rem', fontSize: '0.85rem', fontWeight: 600 }}>Mängd</label>
                    <input
                      type="number"
                      value={ing.editedQuantity}
                      onChange={(e) => updateIngredient(index, 'editedQuantity', e.target.value)}
                      min="0.01"
                      step="0.01"
                      style={{ width: '100%', padding: '0.5rem', border: '1px solid #ddd', borderRadius: '4px', fontSize: '0.9rem', boxSizing: 'border-box' }}
                    />
                  </div>

                  {/* Enhet */}
                  <div>
                    <label style={{ display: 'block', marginBottom: '0.25rem', fontSize: '0.85rem', fontWeight: 600 }}>Enhet</label>
                    <select
                      value={ing.editedUnit}
                      onChange={(e) => updateIngredient(index, 'editedUnit', e.target.value)}
                      style={{ width: '100%', padding: '0.5rem', border: '1px solid #ddd', borderRadius: '4px', fontSize: '0.9rem' }}
                    >
                      {UNIT_OPTIONS.map((u) => (
                        <option key={u.value} value={u.value}>{u.label}</option>
                      ))}
                    </select>
                  </div>

                  {/* Ta bort */}
                  <button
                    onClick={() => removeIngredient(index)}
                    title="Ta bort ingrediens"
                    style={{ padding: '0.5rem 0.75rem', background: '#fee2e2', color: '#dc2626', border: '1px solid #fca5a5', borderRadius: '4px', cursor: 'pointer', fontSize: '0.9rem', alignSelf: 'end' }}
                  >
                    ✕
                  </button>
                </div>

                {/* Anteckning */}
                <div>
                  <label style={{ display: 'block', marginBottom: '0.25rem', fontSize: '0.85rem', color: '#666' }}>Anteckning</label>
                  <input
                    type="text"
                    value={ing.editedNote}
                    onChange={(e) => updateIngredient(index, 'editedNote', e.target.value)}
                    placeholder="Valfri anteckning..."
                    style={{ width: '100%', padding: '0.5rem', border: '1px solid #ddd', borderRadius: '4px', fontSize: '0.85rem', boxSizing: 'border-box' }}
                  />
                </div>
              </div>
            ))}

            {ingredients.length === 0 && (
              <p style={{ color: '#888', fontStyle: 'italic', margin: 0 }}>
                Inga ingredienser tolkades från Markdown-texten.
              </p>
            )}
          </div>

          {/* Knappar */}
          <div style={{ display: 'flex', gap: '1rem' }}>
            <button
              onClick={handleSave}
              disabled={isSaving || !editedName.trim() || ingredients.filter((i) => i.selectedProductId > 0).length === 0}
              style={{
                padding: '0.75rem 1.5rem',
                background: '#0070f3',
                color: 'white',
                border: 'none',
                borderRadius: '4px',
                cursor: isSaving ? 'not-allowed' : 'pointer',
                opacity: isSaving ? 0.6 : 1,
                fontSize: '1rem',
                fontWeight: 500,
              }}
            >
              {isSaving ? 'Sparar...' : 'Spara recept'}
            </button>
            <button
              onClick={() => setStep('input')}
              style={{ padding: '0.75rem 1rem', background: 'transparent', border: '1px solid #ddd', borderRadius: '4px', cursor: 'pointer', fontSize: '1rem' }}
            >
              ← Redigera Markdown
            </button>
            <button
              onClick={() => router.push('/recipes')}
              style={{ padding: '0.75rem 1rem', background: 'transparent', border: '1px solid #ddd', borderRadius: '4px', cursor: 'pointer', fontSize: '1rem' }}
            >
              Avbryt
            </button>
          </div>
        </section>
      )}
    </main>
  );
}
