import { useSalads } from "@/hooks/use-salads";
import { useI18n } from "@/lib/i18n";
import { Loader2, Plus, Info, Leaf, ShoppingCart } from "lucide-react";
import { useState } from "react";
import { useCart } from "@/lib/cart";
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription } from "@/components/ui/dialog";
import { NutritionBadge } from "@/components/ui/NutritionBadge";
import { type Salad } from "@shared/schema";

const DEFAULT_IMAGE = "https://images.unsplash.com/photo-1546069901-ba9599a7e63c?w=800&q=80&auto=format&fit=crop";

export default function Menu() {
  const { data: salads, isLoading, error } = useSalads();
  const { addToCart } = useCart();
  const { t, language } = useI18n();
  const [selectedSalad, setSelectedSalad] = useState<Salad | null>(null);
  const [imageErrors, setImageErrors] = useState<Set<number>>(new Set());

  const handleImageError = (saladId: number) => {
    setImageErrors(prev => new Set(prev).add(saladId));
  };

  const getImageUrl = (salad: Salad) => {
    if (imageErrors.has(salad.id)) {
      return DEFAULT_IMAGE;
    }
    return salad.imageUrl || DEFAULT_IMAGE;
  };

  // Mock categories for filter tabs
  const categories = ["All", "Weight Loss", "Muscle Gain", "Detox", "Maintenance"];
  const [activeCategory, setActiveCategory] = useState("All");
  const [dietaryFilter, setDietaryFilter] = useState<"all" | "veg" | "non-veg">("all");

  const filteredSalads = salads?.filter(s => {
    const matchesCategory = activeCategory === "All" || s.category === activeCategory;
    const matchesDietary = dietaryFilter === "all" || 
      (dietaryFilter === "veg" && s.isVeg) || 
      (dietaryFilter === "non-veg" && !s.isVeg);
    return matchesCategory && matchesDietary;
  });

  if (isLoading) {
    return (
      <div className="flex items-center justify-center min-h-[60vh]">
        <Loader2 className="w-12 h-12 text-primary animate-spin" />
      </div>
    );
  }

  if (error) {
    return (
      <div className="flex flex-col items-center justify-center min-h-[60vh] text-center px-4">
        <h3 className="text-2xl font-bold text-gray-800 mb-2">Oops! Something went wrong.</h3>
        <p className="text-gray-500">Could not load the menu. Please try again later.</p>
      </div>
    );
  }

  return (
    <div className="bg-gray-50/50 min-h-screen pb-20">
      {/* Header */}
      <div className="bg-primary pt-20 pb-24 px-4 text-center text-white relative overflow-hidden">
        <div className="absolute inset-0 bg-[url('https://images.unsplash.com/photo-1490645935967-10de6ba17061?q=80&w=2053&auto=format&fit=crop')] opacity-10 bg-cover bg-center" />
        <div className="relative z-10">
          <h1 className="text-4xl md:text-5xl font-display font-bold mb-4">{t("menu.title")}</h1>
          <p className="text-white/80 max-w-xl mx-auto text-lg">
            {language === 'en' ? "Explore our range of nutritionist-approved bowls." : "आमच्या पोषणतज्ञ-मान्य बाऊल्सची श्रेणी एक्सप्लोर करा."}
          </p>
        </div>
      </div>

      <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 -mt-10 relative z-20">
        {/* Category Tabs */}
        <div className="flex flex-wrap justify-center gap-2 mb-6">
          {categories.map((cat) => (
            <button
              key={cat}
              onClick={() => setActiveCategory(cat)}
              className={`px-6 py-2.5 rounded-full text-sm font-semibold transition-all shadow-sm ${
                activeCategory === cat
                  ? "bg-accent text-white shadow-accent/20 scale-105"
                  : "bg-white text-gray-600 hover:bg-gray-100"
              }`}
            >
              {cat}
            </button>
          ))}
        </div>

        {/* Veg/Non-Veg Filter */}
        <div className="flex justify-center gap-4 mb-10">
          <button
            onClick={() => setDietaryFilter("all")}
            className={`flex items-center gap-2 px-6 py-2 rounded-xl text-sm font-bold transition-all border-2 ${
              dietaryFilter === "all"
                ? "bg-primary border-primary text-white shadow-lg shadow-primary/20"
                : "bg-white border-gray-100 text-gray-500 hover:border-primary/30"
            }`}
          >
            All
          </button>
          <button
            onClick={() => setDietaryFilter("veg")}
            className={`flex items-center gap-2 px-6 py-2 rounded-xl text-sm font-bold transition-all border-2 ${
              dietaryFilter === "veg"
                ? "bg-white border-green-600 text-green-600 shadow-lg shadow-green-100"
                : "bg-white border-gray-100 text-gray-500 hover:border-green-600/30"
            }`}
          >
            <div className="w-3 h-3 border border-green-600 flex items-center justify-center rounded-sm">
              <div className="w-1.5 h-1.5 rounded-full bg-green-600" />
            </div>
            Veg
          </button>
          <button
            onClick={() => setDietaryFilter("non-veg")}
            className={`flex items-center gap-2 px-6 py-2 rounded-xl text-sm font-bold transition-all border-2 ${
              dietaryFilter === "non-veg"
                ? "bg-white border-red-600 text-red-600 shadow-lg shadow-red-100"
                : "bg-white border-gray-100 text-gray-500 hover:border-red-600/30"
            }`}
          >
            <div className="w-3 h-3 border border-red-600 flex items-center justify-center rounded-sm">
              <div className="w-0 h-0 border-l-[4px] border-l-transparent border-r-[4px] border-r-transparent border-b-[6px] border-b-red-600" />
            </div>
            Non-Veg
          </button>
        </div>

        {/* Salad Grid */}
        <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-8">
          {filteredSalads?.map((salad) => (
            <div key={salad.id} className="bg-white rounded-3xl shadow-lg shadow-gray-200/50 overflow-hidden border border-gray-100 hover:shadow-xl hover:border-primary/20 transition-all duration-300 group flex flex-col h-full">
              {/* Image Area */}
              <div className="relative h-56 overflow-hidden bg-gray-100">
                <img 
                  src={getImageUrl(salad)}
                  alt={salad.name}
                  onError={() => handleImageError(salad.id)}
                  className="w-full h-full object-cover transition-transform duration-500 group-hover:scale-110"
                  loading="lazy"
                />
                <div className="absolute top-4 left-4 bg-white/90 backdrop-blur-sm px-3 py-1 rounded-full text-xs font-bold text-primary shadow-sm">
                  {salad.category}
                </div>
                {salad.isVeg && (
                  <div className="absolute top-4 right-4 w-6 h-6 bg-white rounded-md border border-green-600 flex items-center justify-center shadow-sm">
                    <div className="w-2.5 h-2.5 rounded-full bg-green-600"></div>
                  </div>
                )}
              </div>

              {/* Content Area */}
              <div className="p-6 flex flex-col flex-grow">
                <div className="flex justify-between items-start mb-2">
                  <h3 className="font-display font-bold text-xl text-gray-900 group-hover:text-primary transition-colors line-clamp-1">
                    {language === 'mr' && salad.marathiName ? salad.marathiName : salad.name}
                  </h3>
                </div>
                <p className="text-gray-500 text-sm line-clamp-2 mb-4 flex-grow">
                  {language === 'mr' && salad.marathiDescription ? salad.marathiDescription : salad.description}
                </p>

                <div className="flex items-center justify-between mt-auto pt-4 border-t border-gray-50">
                  <span className="font-display font-bold text-2xl text-accent">₹{salad.price}</span>
                  <div className="flex gap-2">
                    <button 
                      onClick={() => setSelectedSalad(salad)}
                      className="p-2.5 rounded-full text-gray-500 hover:bg-gray-100 transition-colors"
                      title={t("menu.details")}
                    >
                      <Info className="w-5 h-5" />
                    </button>
                    <button 
                      onClick={() => addToCart(salad)}
                      className="px-4 py-2.5 rounded-full bg-primary text-white font-semibold text-sm hover:bg-primary/90 transition-all flex items-center gap-1 shadow-lg shadow-primary/20"
                    >
                      <Plus className="w-4 h-4" />
                      {t("menu.add")}
                    </button>
                  </div>
                </div>
              </div>
            </div>
          ))}
        </div>

        {filteredSalads?.length === 0 && (
          <div className="text-center py-20 text-gray-400">
            <Leaf className="w-16 h-16 mx-auto mb-4 opacity-20" />
            <p className="text-lg">No salads found in this category.</p>
          </div>
        )}
      </div>

      {/* Detail Modal */}
      <Dialog open={!!selectedSalad} onOpenChange={(open) => !open && setSelectedSalad(null)}>
        <DialogContent className="sm:max-w-[600px] max-h-[90vh] overflow-y-auto p-0 gap-0 bg-white rounded-3xl border-0 shadow-2xl">
          {selectedSalad && (
            <>
              <div className="relative h-64 sm:h-72 w-full bg-gray-100">
                <img 
                  src={getImageUrl(selectedSalad)}
                  alt={selectedSalad.name}
                  onError={() => handleImageError(selectedSalad.id)}
                  className="w-full h-full object-cover"
                  loading="lazy"
                />
                <div className="absolute inset-0 bg-gradient-to-t from-black/60 to-transparent" />
                <div className="absolute bottom-6 left-6 text-white">
                  <div className="flex items-center gap-2 mb-2">
                    <span className="bg-accent px-2 py-0.5 rounded text-xs font-bold">{selectedSalad.category}</span>
                    {selectedSalad.isVeg && <span className="bg-green-600 px-2 py-0.5 rounded text-xs font-bold">VEG</span>}
                  </div>
                  <h2 className="font-display font-bold text-3xl">
                    {language === 'mr' && selectedSalad.marathiName ? selectedSalad.marathiName : selectedSalad.name}
                  </h2>
                </div>
              </div>

              <div className="p-6 sm:p-8">
                <DialogDescription className="text-base text-gray-600 mb-6 leading-relaxed">
                  {language === 'mr' && selectedSalad.marathiDescription ? selectedSalad.marathiDescription : selectedSalad.description}
                </DialogDescription>

                {/* Nutrition Grid */}
                <h4 className="font-bold text-sm uppercase tracking-wider text-gray-400 mb-3">{t("nav.about")} (Nutrition)</h4>
                <div className="grid grid-cols-4 gap-3 mb-8">
                  <NutritionBadge label={t("nutrition.calories")} value={selectedSalad.calories} color="orange" />
                  <NutritionBadge label={t("nutrition.protein")} value={selectedSalad.protein} color="green" />
                  <NutritionBadge label={t("nutrition.carbs")} value={selectedSalad.carbs} color="blue" />
                  <NutritionBadge label={t("nutrition.fat")} value={selectedSalad.fat} color="blue" />
                </div>

                {/* Ingredients */}
                <h4 className="font-bold text-sm uppercase tracking-wider text-gray-400 mb-3">{t("nutrition.ingredients")}</h4>
                <div className="flex flex-wrap gap-2 mb-8">
                  {selectedSalad.ingredients.map((ing, i) => (
                    <span key={i} className="px-3 py-1 bg-gray-100 rounded-full text-sm text-gray-700 font-medium">
                      {ing}
                    </span>
                  ))}
                </div>

                <div className="flex items-center justify-between pt-6 border-t border-gray-100">
                  <div className="flex flex-col">
                     <span className="text-sm text-gray-400 font-medium">{t("menu.price")}</span>
                     <span className="font-display font-bold text-3xl text-primary">₹{selectedSalad.price}</span>
                  </div>
                  <button 
                    onClick={() => {
                      addToCart(selectedSalad);
                      setSelectedSalad(null);
                    }}
                    className="px-8 py-3 rounded-xl bg-primary text-white font-bold text-lg hover:bg-primary/90 transition-all shadow-lg shadow-primary/25 hover:-translate-y-0.5"
                  >
                    {t("menu.add")}
                  </button>
                </div>
              </div>
            </>
          )}
        </DialogContent>
      </Dialog>
    </div>
  );
}
