import React, { useState, useMemo } from "react";
import { Drawer, Input, Checkbox } from "antd";
import styles from "./BrandsSidebar.module.scss";
import { useTranslation } from "react-i18next";
import brand from "../../assets/icons/brand.svg";

const BrandSidebar = ({ 
  brands = [], 
  selectedBrand = null,
  onBrandSelect,
  onBrandDeselect 
}) => {
  const [isOpen, setIsOpen] = useState(false);
  const [searchTerm, setSearchTerm] = useState("");
  const { t } = useTranslation();

  const handleToggle = () => {
    setIsOpen(!isOpen);
  };

  const handleSearch = (e) => {
    setSearchTerm(e.target.value.toLowerCase());
  };

  const filteredBrands = useMemo(() => {
    if (!brands || brands.length === 0) return [];
    
    return brands.filter((brand) =>
      brand.name.toLowerCase().includes(searchTerm)
    );
  }, [brands, searchTerm]);

  const handleBrandChange = (brandId, checked) => {
    if (checked) {
      onBrandSelect?.(brandId);
    } else {
      onBrandDeselect?.();
    }
  };

  return (
    <div className={styles.sidebarContainer}>
      <button onClick={handleToggle} className={styles.mobileNavButton}>
        <img src={brand} alt="" />
        {t("navbar.brands")}
        {selectedBrand && <span className={styles.badge}>1</span>}
      </button>

      <Drawer
        title={t("navbar.brands")}
        placement="right"
        onClose={handleToggle}
        open={isOpen}
        className={styles.sidebarDrawer}
        width={320}
      >
        <Input
          placeholder={t("common.search")}
          value={searchTerm}
          onChange={handleSearch}
          className={styles.searchInput}
        />
        
        {filteredBrands.length > 0 ? (
          <div className={styles.brandsList}>
            {filteredBrands.map((brand) => (
              <div key={brand.id} className={styles.brandItem}>
                <Checkbox
                  checked={selectedBrand === brand.id}
                  onChange={(e) => handleBrandChange(brand.id, e.target.checked)}
                >
                  {brand.name}
                </Checkbox>
              </div>
            ))}
          </div>
        ) : (
          <div className={styles.emptyState}>
            {brands.length === 0 
              ? t("common.noData") 
              : t("common.noResults")}
          </div>
        )}
      </Drawer>
    </div>
  );
};

export default BrandSidebar;