'use client';

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

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

type ParsedIngredientRow = {
  rawName: string;
  quantity: number;
  unit: string;
  note?: string;
  suggestions: ProductSuggestion[];
  selectedProductId: number;
  editedQuantity: string;
  editedUnit: string;
  editedNote: string;
};

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

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)' },
  { value: 'krm', label: 'krm (kryddmått)' },
  { value: 'port', label: 'port (portioner)' },
  { value: 'efter smak', label: 'Efter smak' },
  { value: 'förp', label: 'förp (förpackning)' },
  { value: 'klyfta', label: 'klyfta' },
];

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

export default function WriteRecipePage() {
  const router = useRouter();
  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);
  const [showDebugPanel, setShowDebugPanel] = useState(false);

  useEffect(() => {
    // Hämta produkter från databas
    fetchJson<Product[]>('/api/products')
      .then(setAllProducts)
      .catch(console.error);

    // Kontrollera om det finns förifylld Markdown från snabbimport
    const prefilledMarkdown = sessionStorage.getItem('prefilled_markdown');
    if (prefilledMarkdown) {
      setMarkdown(prefilledMarkdown);
      sessionStorage.removeItem('prefilled_markdown');
      // Auto-parse markdown från snabbimport
      setIsParsing(true);
      (async () => {
        try {
          const res = await fetch('/api/parse-markdown-proxy', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ markdown: prefilledMarkdown }),
          });

          if (!res.ok) {
            const errorText = await res.text();
            throw new Error(errorText || 'Kunde inte tolka recept');
          }

          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 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 fetch('/api/recipes', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        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' }}>
      <Navigation />
      <h1 style={{ marginBottom: '0.5rem' }}>Skriv in recept</h1>
      <p style={{ color: '#666', marginBottom: '1.5rem' }}>Skriv receptet i Markdown-format — nama, ingredienser och instruktioner.</p>

      {/* 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. Skriv
        </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 }}>
              Skriv 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 och granska'}
            </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', gridTemplateColumns: showDebugPanel ? '7fr 3fr' : '1fr', gap: '1.5rem' }}>
          {/* Vänster: Receptdetaljer + Ingredienser */}
          <div 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
              </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>
          </div>

          {/* Höger: Debug Panel (Sticky) */}
          <div style={{ position: 'sticky', top: '1rem', height: 'fit-content' }}>
            <details
              open={showDebugPanel}
              onChange={(e) => setShowDebugPanel((e.target as HTMLDetailsElement).open)}
              style={{
                border: '1px solid #ddd',
                borderRadius: '8px',
                padding: '0.75rem',
                background: '#f9f9f9',
              }}
            >
              <summary style={{ cursor: 'pointer', fontWeight: 600, fontSize: '0.9rem', color: '#666', userSelect: 'none' }}>
                🔍 Import Debug {showDebugPanel ? '▼' : '▶'}
              </summary>

              {/* Raw Markdown */}
              <details
                style={{
                  marginTop: '0.75rem',
                  paddingTop: '0.75rem',
                  borderTop: '1px solid #ddd',
                }}
              >
                <summary style={{ cursor: 'pointer', fontSize: '0.8rem', fontWeight: 500, color: '#555', userSelect: 'none' }}>
                  Raw Markdown
                </summary>
                <pre
                  style={{
                    background: 'white',
                    border: '1px solid #ddd',
                    borderRadius: '4px',
                    padding: '0.5rem',
                    fontSize: '0.7rem',
                    overflow: 'auto',
                    maxHeight: '250px',
                    margin: '0.5rem 0 0',
                    fontFamily: 'monospace',
                    color: '#333',
                    wordBreak: 'break-word',
                    whiteSpace: 'pre-wrap',
                    overflowWrap: 'break-word',
                  }}
                >
                  {markdown}
                </pre>
              </details>

              {/* Parse Result */}
              <details
                style={{
                  marginTop: '0.5rem',
                  paddingTop: '0.5rem',
                  borderTop: '1px solid #ddd',
                }}
              >
                <summary style={{ cursor: 'pointer', fontSize: '0.8rem', fontWeight: 500, color: '#555', userSelect: 'none' }}>
                  Parse Result
                </summary>
                <pre
                  style={{
                    background: 'white',
                    border: '1px solid #ddd',
                    borderRadius: '4px',
                    padding: '0.5rem',
                    fontSize: '0.65rem',
                    overflow: 'auto',
                    maxHeight: '250px',
                    margin: '0.5rem 0 0',
                    fontFamily: 'monospace',
                    color: '#333',
                    wordBreak: 'break-word',
                    whiteSpace: 'pre-wrap',
                    overflowWrap: 'break-word',
                  }}
                >
                  {JSON.stringify(parsed, null, 2)}
                </pre>
              </details>
            </details>
          </div>
        </section>
      )}
    </main>
  );
}
