import { useState } from 'react'
import { useNavigate } from 'react-router-dom'
import { api } from '../api/client'
import type { DrinkCreate } from '../api/types'
import { RatingStars } from '../components/RatingStars'

const categories = [
  { value: 'wine' as const, label: 'Vin', icon: '🍷' },
  { value: 'beer' as const, label: 'Bière', icon: '🍺' },
  { value: 'spirit' as const, label: 'Spiritueux', icon: '🥃' },
]

const wineColors = [
  { value: 'red', label: 'Rouge' },
  { value: 'white', label: 'Blanc' },
  { value: 'rose', label: 'Rosé' },
  { value: 'sparkling', label: 'Effervescent' },
]

const beerStyles = [
  'ipa', 'stout', 'lager', 'ale', 'wheat', 'sour', 'pilsner', 'porter', 'belgian', 'other',
]

const spiritTypes = [
  'whisky', 'vodka', 'rum', 'gin', 'tequila', 'cognac', 'calvados', 'other',
]

export function AddDrink() {
  const navigate = useNavigate()
  const [submitting, setSubmitting] = useState(false)
  const [error, setError] = useState<string | null>(null)
  const [photo, setPhoto] = useState<File | null>(null)
  const [preview, setPreview] = useState<string | null>(null)

  const [form, setForm] = useState<DrinkCreate>({
    name: '',
    category: 'wine',
    rating: null,
    notes: null,
    grape_variety: null,
    vintage: null,
    region: null,
    producer: null,
    wine_color: null,
    brewery: null,
    beer_style: null,
    ibu: null,
    abv: null,
    spirit_type: null,
    age_years: null,
    distillery: null,
    country: null,
  })

  const update = <K extends keyof DrinkCreate>(key: K, value: DrinkCreate[K]) => {
    setForm((prev) => ({ ...prev, [key]: value }))
  }

  const handlePhoto = (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0]
    if (file) {
      setPhoto(file)
      setPreview(URL.createObjectURL(file))
    }
  }

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault()
    if (!form.name.trim()) {
      setError('Le nom est requis')
      return
    }

    setSubmitting(true)
    setError(null)

    try {
      const drink = await api.createDrink(form)
      if (photo) {
        await api.uploadImage(drink.id, photo)
      }
      navigate(`/drink/${drink.id}`)
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Erreur lors de la création')
    } finally {
      setSubmitting(false)
    }
  }

  return (
    <div className="max-w-2xl mx-auto">
      <h2 className="font-display text-3xl font-bold text-cellar-cream mb-6">
        Ajouter une boisson
      </h2>

      {error && (
        <div className="bg-red-900/30 border border-red-800 text-red-300 px-4 py-3 rounded-lg mb-6">
          {error}
        </div>
      )}

      <form onSubmit={handleSubmit} className="space-y-6">
        {/* Photo */}
        <div className="card p-4">
          <label className="block text-sm font-medium text-cellar-muted mb-2">
            Photo
          </label>
          <div className="flex items-center gap-4">
            {preview ? (
              <div className="relative w-24 h-32 rounded-lg overflow-hidden border border-cellar-border">
                <img src={preview} alt="Preview" className="w-full h-full object-cover" />
                <button
                  type="button"
                  onClick={() => { setPhoto(null); setPreview(null) }}
                  className="absolute top-1 right-1 bg-cellar-bg/80 rounded-full w-5 h-5 flex items-center justify-center text-xs hover:bg-red-900 transition-colors"
                >
                  ✕
                </button>
              </div>
            ) : (
              <label className="w-24 h-32 border-2 border-dashed border-cellar-border rounded-lg flex flex-col items-center justify-center cursor-pointer hover:border-cellar-gold/50 transition-colors">
                <span className="text-2xl mb-1">📷</span>
                <span className="text-xs text-cellar-muted">Photo</span>
                <input type="file" accept="image/*" capture="environment" onChange={handlePhoto} className="hidden" />
              </label>
            )}
            <p className="text-sm text-cellar-muted">
              Prenez une photo ou choisissez depuis votre galerie
            </p>
          </div>
        </div>

        {/* Nom + Catégorie */}
        <div className="card p-4 space-y-4">
          <div>
            <label className="block text-sm font-medium text-cellar-muted mb-1">
              Nom *
            </label>
            <input
              type="text"
              value={form.name}
              onChange={(e) => update('name', e.target.value)}
              placeholder="Ex: Château Margaux 2015"
              className="input-field"
              required
            />
          </div>

          <div>
            <label className="block text-sm font-medium text-cellar-muted mb-2">
              Catégorie
            </label>
            <div className="flex gap-2">
              {categories.map((cat) => (
                <button
                  key={cat.value}
                  type="button"
                  onClick={() => update('category', cat.value)}
                  className={`flex-1 flex items-center justify-center gap-2 py-2.5 rounded-lg border font-medium transition-all duration-200 ${
                    form.category === cat.value
                      ? 'bg-cellar-gold/10 border-cellar-gold text-cellar-gold'
                      : 'bg-cellar-surface border-cellar-border text-cellar-muted hover:text-cellar-cream hover:border-cellar-muted'
                  }`}
                >
                  <span>{cat.icon}</span>
                  <span>{cat.label}</span>
                </button>
              ))}
            </div>
          </div>

          <div>
            <label className="block text-sm font-medium text-cellar-muted mb-1">
              Note
            </label>
            <RatingStars
              rating={form.rating}
              onRate={(r) => update('rating', r)}
              size="lg"
            />
          </div>

          <div>
            <label className="block text-sm font-medium text-cellar-muted mb-1">
              Notes
            </label>
            <textarea
              value={form.notes || ''}
              onChange={(e) => update('notes', e.target.value || null)}
              placeholder="Vos impressions, notes de dégustation..."
              rows={3}
              className="input-field resize-none"
            />
          </div>
        </div>

        {/* Champs spécifiques Vin */}
        {form.category === 'wine' && (
          <div className="card p-4 space-y-4">
            <h3 className="font-medium text-cellar-gold flex items-center gap-2">
              🍷 Détails du vin
            </h3>
            <div className="grid grid-cols-2 gap-4">
              <div>
                <label className="block text-sm font-medium text-cellar-muted mb-1">
                  Cépage
                </label>
                <input
                  type="text"
                  value={form.grape_variety || ''}
                  onChange={(e) => update('grape_variety', e.target.value || null)}
                  placeholder="Ex: Merlot, Cabernet..."
                  className="input-field"
                />
              </div>
              <div>
                <label className="block text-sm font-medium text-cellar-muted mb-1">
                  Millésime
                </label>
                <input
                  type="number"
                  value={form.vintage || ''}
                  onChange={(e) => update('vintage', e.target.value ? Number(e.target.value) : null)}
                  placeholder="2020"
                  min="1900"
                  max="2030"
                  className="input-field"
                />
              </div>
              <div>
                <label className="block text-sm font-medium text-cellar-muted mb-1">
                  Région
                </label>
                <input
                  type="text"
                  value={form.region || ''}
                  onChange={(e) => update('region', e.target.value || null)}
                  placeholder="Ex: Bordeaux, Bourgogne..."
                  className="input-field"
                />
              </div>
              <div>
                <label className="block text-sm font-medium text-cellar-muted mb-1">
                  Producteur
                </label>
                <input
                  type="text"
                  value={form.producer || ''}
                  onChange={(e) => update('producer', e.target.value || null)}
                  placeholder="Ex: Domaine de la Romanée..."
                  className="input-field"
                />
              </div>
            </div>
            <div>
              <label className="block text-sm font-medium text-cellar-muted mb-2">
                Couleur
              </label>
              <div className="flex gap-2">
                {wineColors.map((color) => (
                  <button
                    key={color.value}
                    type="button"
                    onClick={() => update('wine_color', color.value as DrinkCreate['wine_color'])}
                    className={`px-3 py-1.5 rounded-full text-sm border transition-all ${
                      form.wine_color === color.value
                        ? 'bg-cellar-wine/20 border-cellar-wine text-cellar-cream'
                        : 'bg-cellar-surface border-cellar-border text-cellar-muted hover:text-cellar-cream'
                    }`}
                  >
                    {color.label}
                  </button>
                ))}
              </div>
            </div>
          </div>
        )}

        {/* Champs spécifiques Bière */}
        {form.category === 'beer' && (
          <div className="card p-4 space-y-4">
            <h3 className="font-medium text-cellar-gold flex items-center gap-2">
              🍺 Détails de la bière
            </h3>
            <div className="grid grid-cols-2 gap-4">
              <div>
                <label className="block text-sm font-medium text-cellar-muted mb-1">
                  Brasserie
                </label>
                <input
                  type="text"
                  value={form.brewery || ''}
                  onChange={(e) => update('brewery', e.target.value || null)}
                  placeholder="Ex: Brasserie du Mont Blanc..."
                  className="input-field"
                />
              </div>
              <div>
                <label className="block text-sm font-medium text-cellar-muted mb-1">
                  Style
                </label>
                <select
                  value={form.beer_style || ''}
                  onChange={(e) => update('beer_style', e.target.value as DrinkCreate['beer_style'])}
                  className="input-field"
                >
                  <option value="">Sélectionner...</option>
                  {beerStyles.map((s) => (
                    <option key={s} value={s}>{s.toUpperCase()}</option>
                  ))}
                </select>
              </div>
              <div>
                <label className="block text-sm font-medium text-cellar-muted mb-1">
                  IBU
                </label>
                <input
                  type="number"
                  value={form.ibu || ''}
                  onChange={(e) => update('ibu', e.target.value ? Number(e.target.value) : null)}
                  placeholder="Ex: 45"
                  min="0"
                  className="input-field"
                />
              </div>
              <div>
                <label className="block text-sm font-medium text-cellar-muted mb-1">
                  AM (%)
                </label>
                <input
                  type="number"
                  value={form.abv || ''}
                  onChange={(e) => update('abv', e.target.value ? Number(e.target.value) : null)}
                  placeholder="Ex: 5.5"
                  min="0"
                  max="20"
                  step="0.1"
                  className="input-field"
                />
              </div>
            </div>
          </div>
        )}

        {/* Champs spécifiques Spiritueux */}
        {form.category === 'spirit' && (
          <div className="card p-4 space-y-4">
            <h3 className="font-medium text-cellar-gold flex items-center gap-2">
              🥃 Détails du spiritueux
            </h3>
            <div className="grid grid-cols-2 gap-4">
              <div>
                <label className="block text-sm font-medium text-cellar-muted mb-1">
                  Type
                </label>
                <select
                  value={form.spirit_type || ''}
                  onChange={(e) => update('spirit_type', e.target.value as DrinkCreate['spirit_type'])}
                  className="input-field"
                >
                  <option value="">Sélectionner...</option>
                  {spiritTypes.map((t) => (
                    <option key={t} value={t}>{t.charAt(0).toUpperCase() + t.slice(1)}</option>
                  ))}
                </select>
              </div>
              <div>
                <label className="block text-sm font-medium text-cellar-muted mb-1">
                  Âge (années)
                </label>
                <input
                  type="number"
                  value={form.age_years || ''}
                  onChange={(e) => update('age_years', e.target.value ? Number(e.target.value) : null)}
                  placeholder="Ex: 12"
                  min="0"
                  className="input-field"
                />
              </div>
              <div>
                <label className="block text-sm font-medium text-cellar-muted mb-1">
                  Distillerie
                </label>
                <input
                  type="text"
                  value={form.distillery || ''}
                  onChange={(e) => update('distillery', e.target.value || null)}
                  placeholder="Ex: Macallan..."
                  className="input-field"
                />
              </div>
              <div>
                <label className="block text-sm font-medium text-cellar-muted mb-1">
                  Pays
                </label>
                <input
                  type="text"
                  value={form.country || ''}
                  onChange={(e) => update('country', e.target.value || null)}
                  placeholder="Ex: Écosse..."
                  className="input-field"
                />
              </div>
            </div>
          </div>
        )}

        <button
          type="submit"
          disabled={submitting}
          className="btn-primary w-full disabled:opacity-50 disabled:cursor-not-allowed"
        >
          {submitting ? 'Enregistrement...' : 'Ajouter à ma cave'}
        </button>
      </form>
    </div>
  )
}
