import PageLayout from "../components/PageLayout";
import * as api from "../api/index";
import { useState, useEffect, useMemo } from "react";
import CategoryTabs from "../components/CategoryTabs";
import CardItem from "../components/CardItem";

export default function Shop() {
  const [items, setItems] = useState([]);
  const [categories, setCategories] = useState([]);
  const [activeCategory, setActiveCategory] = useState("все");
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    Promise.all([api.getAllItems(), api.getAllCategories()])
      .then(([itemsRes, categoriesRes]) => {
        setItems(itemsRes?.data || []);
        setCategories(categoriesRes?.data || []);
        setLoading(false);
      })
      .catch((err) => {
        console.error("Ошибка при загрузке товара", err);
        alert(err);
        setLoading(false);
      });
  }, []);

  const filteredItems = useMemo(() => {
    return activeCategory === "все"
      ? items || []
      : (items || []).filter((item) => {
        if (!item || !item.category) return false;

        return item.category.toLowerCase() === activeCategory.toLowerCase();
      });
  }, [items, activeCategory]);

  const handleAddToCart = (product, selectedWeight) => {
    console.log(`Добавлен товар ${product.name}, Вес ${selectedWeight} кг`);
  };

  return (
    <PageLayout>
      <main className="px-6 md:px-16 grow w-full ">
        <h1 className="text-2xl md:text-4xl text-white font-medium md:mt-10">
          Ассортимент
        </h1>
        <CategoryTabs
          categories={["все", ...(categories || [])]}
          activeCategory={activeCategory}
          onSelectCategory={setActiveCategory}
        />
        <div className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 gap-6 mb-4">
          {filteredItems.map((item) => (
            <CardItem key={item.id} item={item} onAddToCart={handleAddToCart} />
          ))}
        </div>
      </main>
    </PageLayout>
  );
}
