import { useState, useEffect, useRef } from 'react'
import { useParams, useNavigate } from 'react-router'
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
import toast from 'react-hot-toast'
import { ArrowLeft, Plus, Trash2, Camera, X, Link, Loader2 } from 'lucide-react'
import { fetchRecipe, createRecipe, updateRecipe, deleteRecipe, uploadRecipeImage, fetchOgPreview } from '../api/recipes'
import { fetchCategories } from '../api/categories'
import { Confetti } from '../components/ui/Confetti'
import type { RecipeFormData } from '../api/recipes'

interface IngredientRow {
  key: string
  name: string
  amount: string
  unit: string
  group_name: string
}

interface StepRow {
  key: string
  instruction: string
}

let keyCounter = 0
function nextKey() { return `k${++keyCounter}` }

export function RecipeFormPage() {
  const { slug } = useParams<{ slug: string }>()
  const isEdit = !!slug
  const navigate = useNavigate()
  const qc = useQueryClient()
  const fileInputRef = useRef<HTMLInputElement>(null)

  const { data: recipe, isLoading: recipeLoading } = useQuery({
    queryKey: ['recipe', slug],
    queryFn: () => fetchRecipe(slug!),
    enabled: isEdit,
  })

  const { data: categories } = useQuery({
    queryKey: ['categories'],
    queryFn: fetchCategories,
  })

  // Form state
  const [title, setTitle] = useState('')
  const [description, setDescription] = useState('')
  const [categoryId, setCategoryId] = useState('')
  const [difficulty, setDifficulty] = useState<'easy' | 'medium' | 'hard'>('medium')
  const [prepTime, setPrepTime] = useState('')
  const [cookTime, setCookTime] = useState('')
  const [servings, setServings] = useState('4')
  const [sourceUrl, setSourceUrl] = useState('')
  const [imageUrl, setImageUrl] = useState('')
  const [imageFile, setImageFile] = useState<File | null>(null)
  const [imagePreview, setImagePreview] = useState<string | null>(null)
  const [ingredients, setIngredients] = useState<IngredientRow[]>([
    { key: nextKey(), name: '', amount: '', unit: '', group_name: '' },
  ])
  const [steps, setSteps] = useState<StepRow[]>([
    { key: nextKey(), instruction: '' },
  ])
  const [tagsInput, setTagsInput] = useState('')
  const [showDeleteConfirm, setShowDeleteConfirm] = useState(false)
  const [fetchingOg, setFetchingOg] = useState(false)
  const [showConfetti, setShowConfetti] = useState(false)

  // Populate form when editing
  useEffect(() => {
    if (recipe && isEdit) {
      setTitle(recipe.title)
      setDescription(recipe.description || '')
      setCategoryId(recipe.category_id || '')
      setDifficulty(recipe.difficulty || 'medium')
      setPrepTime(recipe.prep_time_min ? String(recipe.prep_time_min) : '')
      setCookTime(recipe.cook_time_min ? String(recipe.cook_time_min) : '')
      setServings(recipe.servings ? String(recipe.servings) : '4')
      setSourceUrl((recipe as any).source_url || '')
      setImageUrl(recipe.image_url || '')
      if (recipe.image_url) setImagePreview(recipe.image_url)
      if (recipe.tags && recipe.tags.length > 0) {
        setTagsInput(recipe.tags.join(', '))
      }
      if (recipe.ingredients && recipe.ingredients.length > 0) {
        setIngredients(recipe.ingredients.map(ing => ({
          key: nextKey(),
          name: ing.name,
          amount: ing.amount ? String(ing.amount) : '',
          unit: ing.unit || '',
          group_name: ing.group_name || '',
        })))
      }
      if (recipe.steps && recipe.steps.length > 0) {
        setSteps(recipe.steps.map(s => ({
          key: nextKey(),
          instruction: s.instruction,
        })))
      }
    }
  }, [recipe, isEdit])

  const saveMutation = useMutation({
    mutationFn: async (data: RecipeFormData) => {
      if (isEdit && recipe) {
        return updateRecipe(recipe.id, data)
      }
      return createRecipe(data)
    },
    onSuccess: async (saved) => {
      // Upload image if selected
      if (imageFile && saved?.id) {
        try {
          await uploadRecipeImage(saved.id, imageFile)
        } catch {
          toast.error('Rezept gespeichert, aber Bild-Upload fehlgeschlagen')
        }
      }
      qc.invalidateQueries({ queryKey: ['recipes'] })
      qc.invalidateQueries({ queryKey: ['recipe', slug] })
      if (!isEdit) {
        setShowConfetti(true)
        toast.success('Rezept erstellt! 🎉')
        setTimeout(() => navigate(saved?.slug ? `/recipe/${saved.slug}` : '/'), 1500)
      } else {
        toast.success('Rezept aktualisiert!')
        navigate(saved?.slug ? `/recipe/${saved.slug}` : '/')
      }
    },
    onError: () => toast.error('Fehler beim Speichern'),
  })

  const deleteMutation = useMutation({
    mutationFn: () => deleteRecipe(recipe!.id),
    onSuccess: () => {
      qc.invalidateQueries({ queryKey: ['recipes'] })
      toast.success('Rezept gelöscht')
      navigate('/')
    },
    onError: () => toast.error('Fehler beim Löschen'),
  })

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault()
    if (!title.trim()) {
      toast.error('Titel ist erforderlich')
      return
    }
    const data: RecipeFormData = {
      title: title.trim(),
      description: description.trim() || undefined,
      category_id: categoryId || undefined,
      difficulty,
      prep_time: prepTime ? Number(prepTime) : undefined,
      cook_time: cookTime ? Number(cookTime) : undefined,
      servings: servings ? Number(servings) : undefined,
      source_url: sourceUrl.trim() || undefined,
      image_url: imageUrl || undefined,
      ingredients: ingredients
        .filter(i => i.name.trim())
        .map((i, idx) => ({
          name: i.name.trim(),
          amount: i.amount ? Number(i.amount) : undefined,
          unit: i.unit.trim() || undefined,
          group_name: i.group_name.trim() || undefined,
          sort_order: idx,
        })),
      steps: steps
        .filter(s => s.instruction.trim())
        .map((s, idx) => ({
          step_number: idx + 1,
          instruction: s.instruction.trim(),
        })),
      tags: tagsInput.split(',').map(t => t.trim()).filter(Boolean),
    }
    saveMutation.mutate(data)
  }

  const handleImageSelect = (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0]
    if (!file) return
    setImageFile(file)
    const url = URL.createObjectURL(file)
    setImagePreview(url)
  }

  const addIngredient = () => {
    setIngredients(prev => [...prev, { key: nextKey(), name: '', amount: '', unit: '', group_name: '' }])
  }

  const removeIngredient = (key: string) => {
    setIngredients(prev => prev.filter(i => i.key !== key))
  }

  const updateIngredient = (key: string, field: keyof IngredientRow, value: string) => {
    setIngredients(prev => prev.map(i => i.key === key ? { ...i, [field]: value } : i))
  }

  const addStep = () => {
    setSteps(prev => [...prev, { key: nextKey(), instruction: '' }])
  }

  const removeStep = (key: string) => {
    setSteps(prev => prev.filter(s => s.key !== key))
  }

  const updateStep = (key: string, instruction: string) => {
    setSteps(prev => prev.map(s => s.key === key ? { ...s, instruction } : s))
  }

  if (isEdit && recipeLoading) {
    return <div className="p-4 text-warm-grey">Laden...</div>
  }

  const inputClass = "w-full bg-surface border border-sand rounded-xl px-4 py-3 text-base text-espresso placeholder:text-warm-grey/50 focus:outline-none focus:ring-2 focus:ring-primary/30 min-h-[44px]"
  const labelClass = "block text-sm font-semibold text-espresso mb-1"

  return (
    <div className="min-h-screen bg-cream">
      <Confetti active={showConfetti} />
      {/* Header */}
      <div className="sticky top-0 z-40 bg-cream/95 backdrop-blur-sm border-b border-sand px-4 py-3 flex items-center gap-3">
        <button onClick={() => navigate(-1)} className="p-2 -ml-2 min-w-[44px] min-h-[44px] flex items-center justify-center">
          <ArrowLeft size={20} className="text-espresso" />
        </button>
        <h1 className="font-display text-lg text-espresso flex-1">
          {isEdit ? 'Rezept bearbeiten' : 'Neues Rezept'}
        </h1>
      </div>

      <form onSubmit={handleSubmit} className="p-4 pb-32 space-y-6">
        {/* Image */}
        <div>
          <label className={labelClass}>Bild</label>
          <input
            ref={fileInputRef}
            type="file"
            accept="image/*"
            capture="environment"
            onChange={handleImageSelect}
            className="hidden"
          />
          {imagePreview ? (
            <div className="relative">
              <img src={imagePreview} alt="Preview" className="w-full h-48 object-cover rounded-2xl" />
              <button
                type="button"
                onClick={() => { setImageFile(null); setImagePreview(null); setImageUrl('') }}
                className="absolute top-2 right-2 bg-surface/80 backdrop-blur-sm rounded-full p-1.5"
              >
                <X size={16} className="text-espresso" />
              </button>
            </div>
          ) : (
            <button
              type="button"
              onClick={() => fileInputRef.current?.click()}
              className="w-full h-48 border-2 border-dashed border-sand rounded-2xl flex flex-col items-center justify-center gap-2 text-warm-grey hover:border-primary/50 transition-colors"
            >
              <Camera size={32} />
              <span className="text-sm">Foto aufnehmen oder auswählen</span>
            </button>
          )}
        </div>

        {/* Title */}
        <div>
          <label className={labelClass}>Titel *</label>
          <input
            type="text"
            value={title}
            onChange={e => setTitle(e.target.value)}
            placeholder="z.B. Omas Apfelkuchen"
            className={inputClass}
            required
          />
        </div>

        {/* Description */}
        <div>
          <label className={labelClass}>Beschreibung</label>
          <textarea
            value={description}
            onChange={e => setDescription(e.target.value)}
            placeholder="Kurze Beschreibung..."
            rows={3}
            className={`${inputClass} resize-none`}
          />
        </div>

        {/* Category + Difficulty row */}
        <div className="grid grid-cols-2 gap-3">
          <div>
            <label className={labelClass}>Kategorie</label>
            <select value={categoryId} onChange={e => setCategoryId(e.target.value)} className={inputClass}>
              <option value="">Keine</option>
              {(categories || []).map(cat => (
                <option key={cat.id} value={cat.id}>{cat.name}</option>
              ))}
            </select>
          </div>
          <div>
            <label className={labelClass}>Schwierigkeit</label>
            <select value={difficulty} onChange={e => setDifficulty(e.target.value as any)} className={inputClass}>
              <option value="easy">Einfach</option>
              <option value="medium">Mittel</option>
              <option value="hard">Schwer</option>
            </select>
          </div>
        </div>

        {/* Times + Servings */}
        <div className="grid grid-cols-3 gap-3">
          <div>
            <label className={labelClass}>Vorbereitung</label>
            <input
              type="number"
              value={prepTime}
              onChange={e => setPrepTime(e.target.value)}
              placeholder="Min"
              min="0"
              className={inputClass}
            />
          </div>
          <div>
            <label className={labelClass}>Kochzeit</label>
            <input
              type="number"
              value={cookTime}
              onChange={e => setCookTime(e.target.value)}
              placeholder="Min"
              min="0"
              className={inputClass}
            />
          </div>
          <div>
            <label className={labelClass}>Portionen</label>
            <input
              type="number"
              value={servings}
              onChange={e => setServings(e.target.value)}
              placeholder="4"
              min="1"
              className={inputClass}
            />
          </div>
        </div>

        {/* Source URL + OG Fetch */}
        <div>
          <label className={labelClass}>Quelle (URL)</label>
          <div className="flex gap-2">
            <input
              type="url"
              value={sourceUrl}
              onChange={e => setSourceUrl(e.target.value)}
              placeholder="https://pinterest.com/..."
              className={`${inputClass} flex-1`}
            />
            {sourceUrl.trim() && !imagePreview && (
              <button
                type="button"
                disabled={fetchingOg}
                onClick={async () => {
                  setFetchingOg(true)
                  try {
                    const og = await fetchOgPreview(sourceUrl.trim())
                    if (og.image) {
                      setImagePreview(og.image)
                      setImageUrl(og.image)
                      toast.success('Bild gefunden! 📸')
                    } else {
                      toast.error('Kein Bild auf der Seite gefunden')
                    }
                    // Auto-fill title & description if empty
                    if (!title.trim() && og.title) setTitle(og.title)
                    if (!description.trim() && og.description) setDescription(og.description)
                  } catch {
                    toast.error('Konnte die Seite nicht laden')
                  } finally {
                    setFetchingOg(false)
                  }
                }}
                className="bg-secondary text-white px-4 py-3 rounded-xl font-medium min-h-[44px] min-w-[44px] flex items-center justify-center disabled:opacity-50 whitespace-nowrap gap-2"
              >
                {fetchingOg ? <Loader2 size={18} className="animate-spin" /> : <Link size={18} />}
                {!fetchingOg && <span className="hidden sm:inline text-sm">Bild holen</span>}
              </button>
            )}
          </div>
          {sourceUrl.trim() && (
            <p className="text-xs text-warm-grey mt-1">💡 Pinterest, Chefkoch, Blogs — Bild wird automatisch geholt</p>
          )}
        </div>

        {/* Tags */}
        <div>
          <label className={labelClass}>Tags</label>
          <input
            type="text"
            value={tagsInput}
            onChange={e => setTagsInput(e.target.value)}
            placeholder="z.B. Sommer, Schnell, Omas Rezept"
            className={inputClass}
          />
          <p className="text-xs text-warm-grey mt-1">Komma-getrennt eingeben</p>
          {tagsInput && (
            <div className="flex flex-wrap gap-1 mt-2">
              {tagsInput.split(',').map(t => t.trim()).filter(Boolean).map((tag, i) => (
                <span key={i} className="text-xs bg-sand/50 text-warm-grey px-2 py-0.5 rounded-full">#{tag}</span>
              ))}
            </div>
          )}
        </div>

        {/* Ingredients */}
        <div>
          <div className="flex items-center justify-between mb-2">
            <label className={labelClass}>Zutaten</label>
            <button type="button" onClick={addIngredient} className="flex items-center gap-1 text-primary text-sm font-medium min-h-[44px] px-2">
              <Plus size={16} /> Hinzufügen
            </button>
          </div>
          <div className="space-y-2">
            {ingredients.map((ing) => (
              <div key={ing.key} className="flex gap-2 items-start">
                <input
                  type="text"
                  value={ing.amount}
                  onChange={e => updateIngredient(ing.key, 'amount', e.target.value)}
                  placeholder="Menge"
                  className="w-16 bg-surface border border-sand rounded-xl px-3 py-3 text-sm text-espresso min-h-[44px]"
                />
                <input
                  type="text"
                  value={ing.unit}
                  onChange={e => updateIngredient(ing.key, 'unit', e.target.value)}
                  placeholder="Einheit"
                  className="w-16 bg-surface border border-sand rounded-xl px-3 py-3 text-sm text-espresso min-h-[44px]"
                />
                <input
                  type="text"
                  value={ing.name}
                  onChange={e => updateIngredient(ing.key, 'name', e.target.value)}
                  placeholder="Zutat"
                  className="flex-1 bg-surface border border-sand rounded-xl px-3 py-3 text-sm text-espresso min-h-[44px]"
                />
                <button
                  type="button"
                  onClick={() => removeIngredient(ing.key)}
                  className="p-2 text-warm-grey hover:text-berry-red min-w-[44px] min-h-[44px] flex items-center justify-center"
                >
                  <X size={16} />
                </button>
              </div>
            ))}
          </div>
        </div>

        {/* Steps */}
        <div>
          <div className="flex items-center justify-between mb-2">
            <label className={labelClass}>Zubereitung</label>
            <button type="button" onClick={addStep} className="flex items-center gap-1 text-primary text-sm font-medium min-h-[44px] px-2">
              <Plus size={16} /> Schritt
            </button>
          </div>
          <div className="space-y-3">
            {steps.map((step, idx) => (
              <div key={step.key} className="flex gap-2 items-start">
                <span className="flex-shrink-0 w-7 h-7 rounded-full bg-primary text-white text-sm flex items-center justify-center font-medium mt-2">
                  {idx + 1}
                </span>
                <textarea
                  value={step.instruction}
                  onChange={e => updateStep(step.key, e.target.value)}
                  placeholder={`Schritt ${idx + 1}...`}
                  rows={2}
                  className="flex-1 bg-surface border border-sand rounded-xl px-3 py-3 text-sm text-espresso resize-none min-h-[44px]"
                />
                <button
                  type="button"
                  onClick={() => removeStep(step.key)}
                  className="p-2 text-warm-grey hover:text-berry-red min-w-[44px] min-h-[44px] flex items-center justify-center"
                >
                  <X size={16} />
                </button>
              </div>
            ))}
          </div>
        </div>

        {/* Action Buttons */}
        <div className="space-y-3">
          <button
            type="submit"
            disabled={saveMutation.isPending}
            className="w-full bg-primary text-white px-6 py-4 rounded-2xl font-medium text-base shadow-sm transition-colors hover:bg-primary/90 disabled:opacity-50 min-h-[44px]"
          >
            {saveMutation.isPending ? 'Speichern...' : (isEdit ? 'Änderungen speichern' : 'Rezept erstellen')}
          </button>

          <button
            type="button"
            onClick={() => navigate(-1)}
            className="w-full bg-surface text-espresso px-6 py-4 rounded-2xl font-medium text-base border border-sand min-h-[44px]"
          >
            Abbrechen
          </button>

          {isEdit && (
            <>
              <button
                type="button"
                onClick={() => setShowDeleteConfirm(true)}
                className="w-full text-berry-red px-6 py-4 rounded-2xl font-medium text-base min-h-[44px]"
              >
                <Trash2 size={16} className="inline mr-2" />
                Rezept löschen
              </button>

              {/* Delete Confirmation Dialog */}
              {showDeleteConfirm && (
                <div className="fixed inset-0 z-50 bg-black/40 flex items-center justify-center p-4" onClick={() => setShowDeleteConfirm(false)}>
                  <div className="bg-surface rounded-2xl p-6 max-w-sm w-full shadow-xl space-y-4" onClick={e => e.stopPropagation()}>
                    <h2 className="font-display text-lg text-espresso">Rezept löschen?</h2>
                    <p className="text-sm text-warm-grey">
                      Möchtest du "{recipe?.title}" wirklich löschen? Das kann nicht rückgängig gemacht werden.
                    </p>
                    <div className="flex gap-3">
                      <button
                        type="button"
                        onClick={() => setShowDeleteConfirm(false)}
                        className="flex-1 bg-surface border border-sand text-espresso px-4 py-3 rounded-xl font-medium min-h-[44px]"
                      >
                        Abbrechen
                      </button>
                      <button
                        type="button"
                        onClick={() => deleteMutation.mutate()}
                        disabled={deleteMutation.isPending}
                        className="flex-1 bg-berry-red text-white px-4 py-3 rounded-xl font-medium min-h-[44px] disabled:opacity-50"
                      >
                        {deleteMutation.isPending ? 'Löschen...' : 'Löschen'}
                      </button>
                    </div>
                  </div>
                </div>
              )}
            </>
          )}
        </div>
      </form>
    </div>
  )
}
