import { useState } from 'react'
import { useQuery } from '@tanstack/react-query'
import { useNavigate } from 'react-router'
import { motion } from 'framer-motion'
import Masonry from 'react-masonry-css'
import { Dices } from 'lucide-react'
import { fetchRecipes, fetchRandomRecipe } from '../api/recipes'
import { fetchCategories } from '../api/categories'
import { fetchTags } from '../api/tags'
import { RecipeCard } from '../components/recipe/RecipeCard'
import { RecipeCardSmall } from '../components/recipe/RecipeCardSmall'
import type { Recipe } from '../api/types'
import { Badge } from '../components/ui/Badge'
import { RecipeCardSkeleton } from '../components/ui/Skeleton'
import { EmptyState } from '../components/ui/EmptyState'

export function HomePage() {
  const [activeCategory, setActiveCategory] = useState<string | undefined>()
  const [activeTag, setActiveTag] = useState<string | undefined>()
  const navigate = useNavigate()

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

  const { data: tags } = useQuery({
    queryKey: ['tags'],
    queryFn: fetchTags,
  })

  const { data: recipesData, isLoading } = useQuery({
    queryKey: ['recipes', { category: activeCategory }],
    queryFn: () => fetchRecipes({ category: activeCategory, sort: 'newest' }),
  })

  const { data: favoritesData } = useQuery({
    queryKey: ['recipes', { favorite: true }],
    queryFn: () => fetchRecipes({ favorite: true }),
  })

  const recipes = recipesData?.data ?? []
  const totalCount = recipesData?.total ?? 0
  const favorites = favoritesData?.data ?? []

  // Filter by tag client-side if active
  const filteredRecipes = activeTag
    ? recipes.filter(r => r.tags?.includes(activeTag))
    : recipes

    const handleRandomCook = async () => {
    try {
      const recipe = await fetchRandomRecipe(['mittag', 'abend', 'fruehstueck'])
      if (recipe?.slug) navigate(`/recipe/${recipe.slug}?from=random&type=cook`)
    } catch { /* no recipes */ }
  }

  const handleRandomBake = async () => {
    try {
      const recipe = await fetchRandomRecipe(['backen', 'torten', 'desserts'])
      if (recipe?.slug) navigate(`/recipe/${recipe.slug}?from=random&type=bake`)
    } catch { /* no recipes */ }
  }

  const activeTags = (tags || []).filter(t => t.recipe_count > 0)

  return (
    <div>
      {/* TopBar */}
      <div className="flex items-center justify-between px-4 py-4">
        <h1 className="font-display text-2xl text-espresso">🧁 Luna Recipes</h1>
        <div className="w-9 h-9 rounded-full bg-primary-light flex items-center justify-center text-sm">👤</div>
      </div>

      {/* Recipe Counter */}
      {totalCount > 0 && (
        <motion.div
          className="px-4 pb-3"
          initial={{ opacity: 0, y: -10 }}
          animate={{ opacity: 1, y: 0 }}
        >
          <p className="text-sm text-warm-grey">
            Du hast <span className="font-semibold text-primary">{totalCount}</span> Rezept{totalCount !== 1 ? 'e' : ''} gesammelt! 🎉
          </p>
        </motion.div>
      )}

      {/* Random Recipe Buttons */}
      {totalCount > 1 && (
        <div className="px-4 pb-4 flex gap-2">
          <button
            onClick={handleRandomCook}
            className="flex-1 bg-gradient-to-r from-primary to-secondary text-white px-3 py-3 rounded-2xl font-medium text-sm flex items-center justify-center gap-2 shadow-sm active:scale-[0.98] transition-transform min-h-[44px]"
          >
            <Dices size={16} />
            Was koche ich? 🥘
          </button>
          <button
            onClick={handleRandomBake}
            className="flex-1 bg-gradient-to-r from-secondary to-primary text-white px-3 py-3 rounded-2xl font-medium text-sm flex items-center justify-center gap-2 shadow-sm active:scale-[0.98] transition-transform min-h-[44px]"
          >
            <Dices size={16} />
            Was backe ich? 🎂
          </button>
        </div>
      )}

      {/* Favorites Section */}
      {favorites.length > 0 && (
        <div className="pb-4">
          <h2 className="font-display text-lg text-espresso px-4 mb-2">❤️ Favoriten</h2>
          <div className="flex gap-3 px-4 overflow-x-auto scrollbar-hide pb-1">
            {favorites.map((recipe, i) => (
              <motion.div
                key={recipe.id}
                className="min-w-[260px] max-w-[260px]"
                initial={{ opacity: 0, x: 20 }}
                animate={{ opacity: 1, x: 0 }}
                transition={{ delay: i * 0.05 }}
              >
                <RecipeCardSmall recipe={recipe} />
              </motion.div>
            ))}
          </div>
        </div>
      )}

      {/* Category Chips */}
      {categories && (Array.isArray(categories) ? categories : []).length > 0 && (
        <div className="flex gap-2 px-4 pb-2 overflow-x-auto scrollbar-hide">
          <Badge active={!activeCategory} onClick={() => { setActiveCategory(undefined); setActiveTag(undefined) }}>
            Alle
          </Badge>
          {(Array.isArray(categories) ? categories : []).map((cat) => (
            <Badge
              key={cat.id}
              active={activeCategory === cat.slug}
              onClick={() => { setActiveCategory(activeCategory === cat.slug ? undefined : cat.slug); setActiveTag(undefined) }}
            >
              {cat.icon ? `${cat.icon} ` : ''}{cat.name}
            </Badge>
          ))}
        </div>
      )}

      {/* Tag Chips */}
      {activeTags.length > 0 && (
        <div className="flex gap-2 px-4 pb-4 overflow-x-auto scrollbar-hide">
          {activeTags.map((tag) => (
            <span
              key={tag.id}
              onClick={() => setActiveTag(activeTag === tag.name ? undefined : tag.name)}
              className={`inline-block px-3 py-1 rounded-full text-xs font-medium cursor-pointer transition-colors whitespace-nowrap ${
                activeTag === tag.name
                  ? 'bg-secondary text-white'
                  : 'bg-sand/50 text-warm-grey'
              }`}
            >
              #{tag.name}
            </span>
          ))}
        </div>
      )}

      {/* Recipe Grid */}
      <div className="px-4">
        {isLoading ? (
          <Masonry breakpointCols={{ default: 3, 768: 2, 480: 2 }} className="flex -ml-4" columnClassName="pl-4">
            {Array.from({ length: 6 }).map((_, i) => <RecipeCardSkeleton key={i} />)}
          </Masonry>
        ) : filteredRecipes.length === 0 ? (
          <EmptyState
            title="Noch keine Rezepte"
            description="Füge dein erstes Rezept hinzu und starte deine Sammlung! 💖"
            icon="🧁"
          />
        ) : (
          <Masonry breakpointCols={{ default: 3, 768: 2, 480: 2 }} className="flex -ml-4" columnClassName="pl-4">
            {filteredRecipes.map((recipe: Recipe, i: number) => (
              <motion.div
                key={recipe.id}
                initial={{ opacity: 0, y: 20 }}
                animate={{ opacity: 1, y: 0 }}
                transition={{ delay: i * 0.04, duration: 0.3 }}
              >
                <RecipeCard recipe={recipe} />
              </motion.div>
            ))}
          </Masonry>
        )}
      </div>
    </div>
  )
}
