// // // src/pages/Inventory/Products.jsx
// import React, { useState, useEffect } from 'react';
// import { useNavigate } from 'react-router-dom';
// import '../../components/Filters/Filters.css';
// import './Products.css';

// const IMAGE_BASE_URL = import.meta.env.VITE_API_BASE_URL + '/products';

// export default function Products() {
//   const [products, setProducts] = useState([]);
//   const navigate = useNavigate();

//   useEffect(() => {
//     async function loadProducts() {
//       try {
//         const response = await fetch(import.meta.env.VITE_API_BASE_URL + '/products');
//         const data = await response.json();
//         setProducts(Array.isArray(data.data) ? data.data : []);
//       } catch (err) {
//         console.error('Error fetching products', err);
//         setProducts([]);
//       }
//     }
//     loadProducts();
//   }, []);

//   const handleAddNew = () => {
//     navigate('/app/new-product');

//   };

//   return (
//     <div className="products-page-container">
//       <h2>Products</h2>
//       <div className="products-grid">
//         <div className="product-card add-new-card" onClick={handleAddNew}>
//           <div className="add-icon">+</div>
//           <div className="add-text">Add new product</div>
//         </div>
//         {Array.isArray(products) &&
//           products.map((prod, index) => (
//             <div key={prod.id_product || index} className="product-card">
//               {prod.image_product && (
//                 <img
//                   src={
//                     prod.image_product.startsWith('http')
//                       ? prod.image_product
//                       : prod.image_product.length > 200
//                         ? `data:image/jpeg;base64,${prod.image_product}`
//                         : `${IMAGE_BASE_URL}/${prod.image_product}`
//                   }
//                   alt={prod.name_product}
//                   className="product-image"
//                 />
//               )}
//               <div className="product-info">
//                 <div className="product-name">{prod.name_product}</div>
//                 <div className="product-price">Price: ${prod.price_product}</div>
//                 <div className="product-units">Units: {prod.units}</div>
//               </div>
//             </div>
//           ))}
//       </div>
//     </div>
//   );
// }

import React, { useState, useEffect, useContext } from "react";
import { Link, useNavigate } from "react-router-dom";
import "../../components/Filters/Filters.css";
import "./Products.css";
import { langContext } from "../../context/LenguageContext";

const IMAGE_BASE_URL = import.meta.env.VITE_API_BASE_URL + "/products";

export default function Products() {
  const { lang } = useContext(langContext);
  const [products, setProducts] = useState([]);
  const [filteredProducts, setFilteredProducts] = useState([]);
  const [categories, setCategories] = useState([]);
  const [productTypes, setProductTypes] = useState([]);
  const [searchTerm, setSearchTerm] = useState("");
  const [categoryFilter, setCategoryFilter] = useState("");
  const [productTypeFilter, setProductTypeFilter] = useState("");
  const [stockFilter, setStockFilter] = useState("");
  const [loading, setLoading] = useState(true);
  const navigate = useNavigate();

  useEffect(() => {
    async function loadProducts() {
      try {
        setLoading(true);
        const response = await fetch(
          import.meta.env.VITE_API_BASE_URL + "/products"
        );
        const data = await response.json();
        const productsList = Array.isArray(data.data) ? data.data : [];

        const productsWithDetails = await Promise.all(
          productsList.map(async (prod) => {
            try {
              const detailResponse = await fetch(
                `${import.meta.env.VITE_API_BASE_URL}/products/product/${prod.id_product}`,
                { method: "PUT" }
              );
              const detailData = await detailResponse.json();
              if (detailData.data && detailData.data.length > 0) {
                const detail = detailData.data[0];
                return {
                  ...prod,
                  category: detail.id_category_pro || null,
                  product_type: detail.product_type || [],
                  units: detail.stock || prod.units || 0,
                };
              }
              return {
                ...prod,
                category: null,
                product_type: [],
                units: prod.units || 0,
              };
            } catch (err) {
              console.error(`Error fetching product ${prod.id_product}:`, err);
              return {
                ...prod,
                category: null,
                product_type: [],
                units: prod.units || 0,
              };
            }
          })
        );

        setProducts(productsWithDetails);
        setFilteredProducts(productsWithDetails);
      } catch (err) {
        console.error("Error fetching products", err);
        setProducts([]);
        setFilteredProducts([]);
      } finally {
        setLoading(false);
      }
    }
    loadProducts();
  }, []);

  useEffect(() => {
    async function loadFilterOptions() {
      try {
        const [categoriesRes, typesRes] = await Promise.all([
          fetch(
            import.meta.env.VITE_API_BASE_URL + "/products/productcategory"
          ),
          fetch(import.meta.env.VITE_API_BASE_URL + "/products/producttype"),
        ]);

        const categoriesData = await categoriesRes.json();
        const typesData = await typesRes.json();

        if (categoriesData.data) {
          setCategories(
            categoriesData.data
              .filter((d) => d.id_prod_category)
              .map((d) => ({
                id: d.id_prod_category,
                name: d.name_prod_category,
                spanish_name: d.spanish_name || d.name_prod_category,
              }))
          );
        }

        if (typesData.data) {
          setProductTypes(
            typesData.data.map((d) => ({
              id: d.id_product_type,
              name: d.name_product_type,
              spanish_name: d.spanish_name || d.name_product_type,
            }))
          );
        }
      } catch (err) {
        console.error("Error loading filter options", err);
      }
    }
    loadFilterOptions();
  }, []);

  useEffect(() => {
    let filtered = [...products];

    if (searchTerm) {
      filtered = filtered.filter((prod) =>
        prod.name_product?.toLowerCase().includes(searchTerm.toLowerCase())
      );
    }

    if (categoryFilter) {
      filtered = filtered.filter(
        (prod) => prod.category && prod.category.toString() === categoryFilter
      );
    }

    if (productTypeFilter) {
      filtered = filtered.filter((prod) => {
        if (!prod.product_type || !Array.isArray(prod.product_type))
          return false;
        return prod.product_type.some(
          (type) =>
            type.toString() === productTypeFilter ||
            (typeof type === "object" &&
              type.id_product_type?.toString() === productTypeFilter)
        );
      });
    }

    if (stockFilter) {
      switch (stockFilter) {
        case "out":
          filtered = filtered.filter(
            (prod) => (parseInt(prod.units) || 0) === 0
          );
          break;
        case "low":
          filtered = filtered.filter((prod) => {
            const units = parseInt(prod.units) || 0;
            return units > 0 && units < 10;
          });
          break;
        case "in":
          filtered = filtered.filter(
            (prod) => (parseInt(prod.units) || 0) >= 10
          );
          break;
        default:
          break;
      }
    }

    setFilteredProducts(filtered);
  }, [searchTerm, categoryFilter, productTypeFilter, stockFilter, products]);

  const handleAddNew = () => {
    navigate("/app/new-product");
  };

  const clearFilters = () => {
    setSearchTerm("");
    setCategoryFilter("");
    setProductTypeFilter("");
    setStockFilter("");
  };

  return (
    <div className="products-page-container">
      <div className="page-header">
        <h2 className="page-title">
          {lang === "es" ? "Productos" : "Products"}
        </h2>
      </div>

      <div className="products-filters">
        <input
          type="text"
          placeholder={
            lang === "es" ? "Search products..." : "Search products..."
          }
          value={searchTerm}
          onChange={(e) => setSearchTerm(e.target.value)}
          className="filter-search"
        />
        <select
          value={categoryFilter}
          onChange={(e) => setCategoryFilter(e.target.value)}
          className="filter-select"
        >
          <option value="">
            {lang === "es" ? "Todas las categorías" : "All Categories"}
          </option>
          {categories
            .sort((a, b) => {
              const nameA = lang === "en" ? a.name : a.spanish_name;
              const nameB = lang === "en" ? b.name : b.spanish_name;
              return nameA.localeCompare(nameB);
            })
            .map((cat, index) => (
              <option key={index} value={cat.id}>
                {lang === "en" ? cat.name : cat.spanish_name}
              </option>
            ))}
        </select>

        <select
          value={productTypeFilter}
          onChange={(e) => setProductTypeFilter(e.target.value)}
          className="filter-select"
        >
          <option value="">
            {lang === "es" ? "Todos los tipos" : "All Types"}
          </option>
          {productTypes
            .sort((a, b) => {
              const nameA = lang === "en" ? a.name : a.spanish_name;
              const nameB = lang === "en" ? b.name : b.spanish_name;
              return nameA.localeCompare(nameB);
            })
            .map((type, index) => (
              <option key={index} value={type.id}>
                {lang === "en" ? type.name : type.spanish_name}
              </option>
            ))}
        </select>

        <select
          value={stockFilter}
          onChange={(e) => setStockFilter(e.target.value)}
          className="filter-select"
        >
          <option value="">
            {lang === "es" ? "Todo el stock" : "All Stock"}
          </option>
          <option value="out">
            {lang === "es" ? "Sin stock" : "Out of Stock"}
          </option>
          <option value="low">
            {lang === "es" ? "Stock bajo (< 10)" : "Low Stock (< 10)"}
          </option>
          <option value="in">
            {lang === "es" ? "En stock (≥ 10)" : "In Stock (≥ 10)"}
          </option>
        </select>

        <button onClick={clearFilters} className="clear-filters-btn">
          {lang === "es" ? "Limpiar filtros" : "Clear filters"}
        </button>
      </div>

      {loading ? (
        <p>{lang === "es" ? "Cargando productos..." : "Loading products..."}</p>
      ) : (
        <div className="products-grid">
          <div className="product-card add-new-card" onClick={handleAddNew}>
            <div className="add-icon">+</div>
            <div className="add-text">
              {lang === "es" ? "Agregar nuevo producto" : "Add new product"}
            </div>
          </div>
          {Array.isArray(filteredProducts) &&
            filteredProducts.map((prod, index) => (
              <Link
                key={prod.id_product || index}
                to={`/app/alter-product/${prod.id_product}`}
                style={{ textDecoration: "none", color: "#213547" }}
              >
                <div className="product-card">
                  {prod.image_product && (
                    <img
                      src={
                        prod.image_product.startsWith("http")
                          ? prod.image_product
                          : prod.image_product.length > 200
                            ? `data:image/jpeg;base64,${prod.image_product}`
                            : `${IMAGE_BASE_URL}/${prod.image_product}`
                      }
                      alt={prod.name_product}
                      className="product-image"
                    />
                  )}
                  <div className="product-info">
                    <div className="product-name">{prod.name_product}</div>
                    <div className="product-price">
                      {lang === "es" ? "Precio: $" : "Price: $"}
                      {prod.price_product}
                    </div>
                    <div className="product-units">
                      {lang === "es" ? "Unidades: " : "Units: "}
                      {prod.units}
                    </div>
                  </div>
                </div>
              </Link>
            ))}
        </div>
      )}
    </div>
  );
}
