"use client";

import { useEffect, useState } from "react";
import { motion, AnimatePresence } from "framer-motion";
import { Search, X } from "lucide-react";
import { productApi, categoryApi } from "@/lib/api";
import ProductCard from "@/components/menu/ProductCard";
import CategorySlider from "@/components/menu/CategorySlider";
import BottomNav from "@/components/menu/BottomNav";

interface Product {
  id: number; name: string; description: string; price: number;
  image_url: string; stock_quantity: number; category_name: string;
  category_id: number; is_featured: number;
}
interface Category {
  id: number; name: string; icon: string; product_count?: number;
}

export default function MenuPage() {
  const [products, setProducts] = useState<Product[]>([]);
  const [categories, setCategories] = useState<Category[]>([]);
  const [activeCategory, setActiveCategory] = useState<number | null>(null);
  const [searchQuery, setSearchQuery] = useState("");
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    Promise.all([
      productApi.getActive(),
      categoryApi.getAll(),
    ]).then(([prodRes, catRes]) => {
      setProducts(prodRes.data || []);
      setCategories(catRes.data || []);
      setLoading(false);
    }).catch(() => setLoading(false));
  }, []);

  const filtered = products.filter((p) => {
    const matchesCategory = !activeCategory || p.category_id === activeCategory;
    const matchesSearch = !searchQuery || 
      p.name.toLowerCase().includes(searchQuery.toLowerCase()) ||
      p.description.toLowerCase().includes(searchQuery.toLowerCase());
    return matchesCategory && matchesSearch;
  });

  // Group by category for display
  const grouped = filtered.reduce<Record<string, Product[]>>((acc, p) => {
    const key = p.category_name;
    if (!acc[key]) acc[key] = [];
    acc[key].push(p);
    return acc;
  }, {});

  return (
    <div className="min-h-screen pb-20">
      {/* Header */}
      <div className="sticky top-0 z-40 glass border-b border-border/30">
        <div className="max-w-lg mx-auto px-4 py-3">
          <h1 className="text-xl font-bold mb-3">Menü</h1>

          {/* Search */}
          <div className="relative mb-3">
            <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-muted-foreground" />
            <input
              type="text"
              placeholder="Yemek ara..."
              value={searchQuery}
              onChange={(e) => setSearchQuery(e.target.value)}
              className="w-full bg-muted/50 border border-border/50 rounded-xl py-2.5 pl-10 pr-10 text-sm focus:outline-none focus:ring-2 focus:ring-primary/30 transition-all"
            />
            {searchQuery && (
              <button onClick={() => setSearchQuery("")} className="absolute right-3 top-1/2 -translate-y-1/2">
                <X className="w-4 h-4 text-muted-foreground" />
              </button>
            )}
          </div>

          {/* Category Slider */}
          <CategorySlider
            categories={categories}
            activeId={activeCategory}
            onSelect={setActiveCategory}
          />
        </div>
      </div>

      {/* Products */}
      <div className="max-w-lg mx-auto px-4 mt-4">
        {loading ? (
          <div className="grid grid-cols-2 gap-3">
            {[...Array(6)].map((_, i) => (
              <div key={i} className="bg-card rounded-2xl border border-border/50 overflow-hidden animate-pulse">
                <div className="h-40 bg-muted" />
                <div className="p-4 space-y-2">
                  <div className="h-4 bg-muted rounded w-3/4" />
                  <div className="h-3 bg-muted rounded w-full" />
                  <div className="h-8 bg-muted rounded-full w-20 ml-auto" />
                </div>
              </div>
            ))}
          </div>
        ) : filtered.length === 0 ? (
          <motion.div
            initial={{ opacity: 0 }}
            animate={{ opacity: 1 }}
            className="text-center py-20"
          >
            <p className="text-4xl mb-3">🔍</p>
            <p className="text-muted-foreground">Aramanızla eşleşen ürün bulunamadı.</p>
          </motion.div>
        ) : activeCategory ? (
          <div className="grid grid-cols-2 gap-3">
            <AnimatePresence mode="popLayout">
              {filtered.map((product) => (
                <motion.div key={product.id} layout exit={{ opacity: 0, scale: 0.9 }}>
                  <ProductCard {...product} />
                </motion.div>
              ))}
            </AnimatePresence>
          </div>
        ) : (
          Object.entries(grouped).map(([categoryName, categoryProducts]) => (
            <div key={categoryName} className="mb-6">
              <h2 className="text-sm font-bold text-muted-foreground uppercase tracking-wider mb-3 px-1">{categoryName}</h2>
              <div className="grid grid-cols-2 gap-3">
                {categoryProducts.map((product) => (
                  <ProductCard key={product.id} {...product} />
                ))}
              </div>
            </div>
          ))
        )}
      </div>

      <BottomNav />
    </div>
  );
}
