import { useQuery } from '@tanstack/react-query'
import { Link } from 'react-router-dom'
import {
  Sparkles, CookingPot, Clock, Users, ArrowLeft
} from 'lucide-react'
import { mealPlannerApi } from '../api'
import type { Recipe } from '../types'
import { Badge } from '../components/ui/Badge'
import { Card, CardBody } from '../components/ui/Card'
import { Skeleton, SkeletonText } from '../components/ui/Skeleton'
import { EmptyState } from '../components/ui/EmptyState'

export default function RecommendedRecipesPage() {
  const { data: profile } = useQuery({
    queryKey: ['profile'],
    queryFn: () => mealPlannerApi.profile.get().then(r => r.data),
  })

  const familyId = profile?.id

  const { data, isLoading } = useQuery<Recipe[]>({
    queryKey: ['recommendedRecipes', familyId],
    queryFn: async () => {
      if (!familyId) return []
      const res = await mealPlannerApi.recipes.recommended(familyId, 20)
      return res.data
    },
    enabled: !!familyId,
  })

  if (!familyId || isLoading) {
    return <RecommendedSkeleton />
  }

  const recipes = data || []

  return (
    <div className="space-y-6">
      {/* Header */}
      <div className="flex items-center gap-3">
        <Link
          to="/recipes"
          className="p-2 rounded-lg hover:bg-surface-100 transition-colors"
        >
          <ArrowLeft className="w-5 h-5 text-surface-600" />
        </Link>
        <div className="w-10 h-10 rounded-xl bg-warning-50 flex items-center justify-center">
          <Sparkles className="w-5 h-5 text-warning-600" />
        </div>
        <div>
          <h1 className="text-2xl font-bold text-surface-900">Recommended for You</h1>
          <p className="text-sm text-surface-500">
            Based on your family's feedback and preferences
          </p>
        </div>
      </div>

      {/* Grid */}
      {recipes.length === 0 ? (
        <EmptyState
          icon={Sparkles}
          title="No recommendations yet"
          description="Vote and rate more meals so we can learn your family's preferences."
        />
      ) : (
        <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-4">
          {recipes.map(recipe => (
            <RecipeCard key={recipe.id} recipe={recipe} />
          ))}
        </div>
      )}
    </div>
  )
}

function RecipeCard({ recipe }: { recipe: Recipe }) {
  const totalTime = recipe.total_time_minutes ??
    (recipe.prep_time_minutes || 0) + (recipe.cook_time_minutes || 0)
  return (
    <Link to={`/recipes/${recipe.id}`} className="group block">
      <Card className="h-full overflow-hidden hover:shadow-md transition-shadow border-surface-200 hover:border-warning-200">
        {recipe.image_url ? (
          <div className="aspect-[4/3] overflow-hidden bg-surface-100">
            <img
              src={recipe.image_url}
              alt={recipe.name}
              className="w-full h-full object-cover group-hover:scale-105 transition-transform duration-300"
            />
          </div>
        ) : (
          <div className="aspect-[4/3] bg-surface-100 flex items-center justify-center">
            <CookingPot className="w-12 h-12 text-surface-300" />
          </div>
        )}
        <CardBody className="space-y-2">
          <h3 className="font-semibold text-surface-900 group-hover:text-warning-700 transition-colors line-clamp-2">
            {recipe.name}
          </h3>
          <p className="text-xs text-surface-500 line-clamp-2">{recipe.description}</p>
          <div className="flex flex-wrap gap-1.5 pt-1">
            {recipe.cuisine_tags?.map(t => (
              <Badge key={t} variant="neutral" className="text-[10px] px-1.5 py-0">{t}</Badge>
            ))}
            {recipe.protein_type && (
              <Badge variant="primary" className="text-[10px] px-1.5 py-0">{recipe.protein_type}</Badge>
            )}
          </div>
          <div className="flex items-center gap-3 text-xs text-surface-500 pt-1">
            {totalTime > 0 && (
              <span className="flex items-center gap-1">
                <Clock className="w-3.5 h-3.5" />
                {totalTime} min
              </span>
            )}
            <span className="flex items-center gap-1">
              <Users className="w-3.5 h-3.5" />
              {recipe.servings}
            </span>
          </div>
          {recipe.discovery_reason && (
            <p className="text-[11px] text-warning-600 italic pt-1">
              {recipe.discovery_reason}
            </p>
          )}
        </CardBody>
      </Card>
    </Link>
  )
}

function RecommendedSkeleton() {
  return (
    <div className="space-y-6 animate-fade-in">
      <div className="flex items-center gap-3">
        <Skeleton className="h-12 w-12 rounded-xl" />
        <div>
          <Skeleton className="h-8 w-48" />
          <Skeleton className="h-4 w-64 mt-1" />
        </div>
      </div>
      <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-4">
        {Array.from({ length: 4 }).map((_, i) => (
          <Card key={i}>
            <Skeleton className="aspect-[4/3]" />
            <CardBody>
              <Skeleton className="h-5 w-3/4 mb-2" />
              <SkeletonText lines={2} />
              <Skeleton className="h-4 w-24 mt-2" />
            </CardBody>
          </Card>
        ))}
      </div>
    </div>
  )
}
