import { useEffect, useState } from 'react'
import { useParams, useNavigate } from 'react-router-dom'
import { api, getToken } from '../api/client'
import type { Drink } from '../api/types'
import { RatingStars } from '../components/RatingStars'

const categoryLabels: Record<string, string> = {
  wine: 'Vin',
  beer: 'Bière',
  spirit: 'Spiritueux',
}

export function DrinkDetail() {
  const { id } = useParams<{ id: string }>()
  const navigate = useNavigate()
  const [drink, setDrink] = useState<Drink | null>(null)
  const [loading, setLoading] = useState(true)
  const [deleting, setDeleting] = useState(false)

  useEffect(() => {
    if (!id) return
    api.getDrink(Number(id))
      .then(setDrink)
      .catch(() => navigate('/'))
      .finally(() => setLoading(false))
  }, [id, navigate])

  const handleRating = async (rating: number) => {
    if (!drink) return
    await api.updateDrink(drink.id, { rating })
    setDrink({ ...drink, rating })
  }

  const handlePhotoUpload = async (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0]
    if (!file || !drink) return
    const updated = await api.uploadImage(drink.id, file)
    setDrink(updated)
  }

  const handleDelete = async () => {
    if (!drink) return
    if (!confirm('Supprimer cette boisson ?')) return
    setDeleting(true)
    try {
      await api.deleteDrink(drink.id)
      navigate('/')
    } catch {
      setDeleting(false)
    }
  }

  if (loading) {
    return (
      <div className="animate-pulse space-y-6">
        <div className="aspect-[3/2] bg-cellar-card rounded-xl" />
        <div className="h-8 bg-cellar-card rounded w-1/2" />
        <div className="h-4 bg-cellar-card rounded w-1/3" />
      </div>
    )
  }

  if (!drink) return null

  return (
    <div className="max-w-3xl mx-auto space-y-6">
      <button
        onClick={() => navigate(-1)}
        className="flex items-center gap-1 text-cellar-muted hover:text-cellar-cream transition-colors text-sm"
      >
        ← Retour
      </button>

      {/* Image */}
      <div className="relative aspect-[3/2] rounded-xl overflow-hidden bg-cellar-card group">
        {drink.image_path ? (
          <img
            src={`/api/drinks/${drink.id}/image?token=${getToken()}`}
            alt={drink.name}
            className="w-full h-full object-cover"
          />
        ) : (
          <div className="w-full h-full flex items-center justify-center text-8xl opacity-20">
            {drink.category === 'wine' ? '🍷' : drink.category === 'beer' ? '🍺' : '🥃'}
          </div>
        )}

        <label className="absolute bottom-3 right-3 bg-cellar-bg/80 backdrop-blur-sm px-3 py-1.5 rounded-lg text-sm font-medium cursor-pointer hover:bg-cellar-surface transition-colors border border-cellar-border/50">
          📷 Changer la photo
          <input type="file" accept="image/*" onChange={handlePhotoUpload} className="hidden" />
        </label>
      </div>

      {/* Header */}
      <div className="flex items-start justify-between gap-4">
        <div>
          <span className="text-sm text-cellar-muted font-medium">
            {categoryLabels[drink.category]}
          </span>
          <h1 className="font-display text-3xl font-bold text-cellar-cream mt-1">
            {drink.name}
          </h1>
        </div>
        <RatingStars rating={drink.rating} onRate={handleRating} size="lg" />
      </div>

      {/* Details */}
      <div className="card p-6 space-y-4">
        {drink.category === 'wine' && (
          <div className="grid grid-cols-2 sm:grid-cols-3 gap-4">
            {drink.wine_color && (
              <DetailItem label="Couleur" value={
                { red: 'Rouge', white: 'Blanc', rose: 'Rosé', sparkling: 'Effervescent' }[drink.wine_color]
              } />
            )}
            {drink.vintage && <DetailItem label="Millésime" value={String(drink.vintage)} />}
            {drink.region && <DetailItem label="Région" value={drink.region} />}
            {drink.producer && <DetailItem label="Producteur" value={drink.producer} />}
            {drink.grape_variety && <DetailItem label="Cépage" value={drink.grape_variety} />}
          </div>
        )}

        {drink.category === 'beer' && (
          <div className="grid grid-cols-2 sm:grid-cols-3 gap-4">
            {drink.beer_style && <DetailItem label="Style" value={drink.beer_style.toUpperCase()} />}
            {drink.brewery && <DetailItem label="Brasserie" value={drink.brewery} />}
            {drink.ibu && <DetailItem label="IBU" value={String(drink.ibu)} />}
            {drink.abv && <DetailItem label="AM" value={`${drink.abv}%`} />}
          </div>
        )}

        {drink.category === 'spirit' && (
          <div className="grid grid-cols-2 sm:grid-cols-3 gap-4">
            {drink.spirit_type && (
              <DetailItem label="Type" value={drink.spirit_type.charAt(0).toUpperCase() + drink.spirit_type.slice(1)} />
            )}
            {drink.age_years && <DetailItem label="Âge" value={`${drink.age_years} ans`} />}
            {drink.distillery && <DetailItem label="Distillerie" value={drink.distillery} />}
            {drink.country && <DetailItem label="Pays" value={drink.country} />}
          </div>
        )}

        {drink.notes && (
          <div className="pt-4 border-t border-cellar-border">
            <h3 className="text-sm font-medium text-cellar-muted mb-2">Notes</h3>
            <p className="text-cellar-cream/80 whitespace-pre-wrap">{drink.notes}</p>
          </div>
        )}

        <div className="pt-4 border-t border-cellar-border text-xs text-cellar-muted">
          Ajouté le {new Date(drink.created_at).toLocaleDateString('fr-FR')}
        </div>
      </div>

      {/* Actions */}
      <div className="flex gap-3">
        <button
          onClick={() => navigate(`/drink/${drink.id}/edit`)}
          className="btn-primary"
        >
          ✏️ Modifier
        </button>
        <button
          onClick={handleDelete}
          disabled={deleting}
          className="btn-danger"
        >
          {deleting ? 'Suppression...' : '🗑️ Supprimer'}
        </button>
      </div>
    </div>
  )
}

function DetailItem({ label, value }: { label: string; value: string }) {
  return (
    <div>
      <dt className="text-xs text-cellar-muted font-medium uppercase tracking-wider">{label}</dt>
      <dd className="text-cellar-cream font-medium mt-0.5">{value}</dd>
    </div>
  )
}
