import React, { useState, FC, useCallback } from "react";
import cx from "classnames";
import { Radio, Menu, Dropdown, Space, Input } from "antd";
import { SearchOutlined, DownOutlined } from "@ant-design/icons";
import MediaQuery, { useMediaQuery } from "react-responsive";
import { isEmpty, get, debounce, omit } from "lodash";

import Breadcrumbs from "./Breadcrumbs";
import {
  BRAND_PRICE_RADIO,
  VIEW_TYPE_VS_LABLES,
  SORT_OPTIONS_VS_LABLES,
  SORT_TYPES,
  VIEW_OPTIONS,
  SORT_OPTIONS,
  SORT_TO_PAYLOAD_CONVERT,
} from "./productHeader.constants";
import styles from "./producntHeader.module.scss";

const ProductHeaders: FC<any> = ({
  viewType,
  setViewType,
  productInfo,
  activeFilters,
  fetchProducts,
  setActiveFilters,
  productHeaderTitle,
}) => {
  const isMax = useMediaQuery({ minWidth: 1441 });
  const isSearch = useMediaQuery({ minWidth: 1200 });
  const [radioStatus, setradioStatus] = useState(BRAND_PRICE_RADIO[0].value);
  const [searchText, setsearchText] = useState("");
  const [sortType, setSortType] = useState(SORT_TYPES.POPULARITY);

  const handleDebounce = (inputText: string, activeFilter: any) => {
    let updatedFilterValue;
    if (!isEmpty(inputText)) {
      updatedFilterValue = { ...activeFilter, second_name: inputText };
    } else {
      updatedFilterValue = omit({ ...activeFilter }, "second_name");
    }
    fetchProducts(updatedFilterValue);
    setActiveFilters(updatedFilterValue);
  };
  const debounceFn = useCallback(debounce(handleDebounce, 1000), []);
  const onChange = (event: any) => {
    setradioStatus(event.target.value);
  };

  const onSearhTextChange = (event: any) => {
    setsearchText(event.target.value);
    debounceFn(event.target.value, activeFilters);
    activeFilters.subText = event.target.value;
    fetchProducts(activeFilters);
    setActiveFilters(activeFilters);
  };

  const onViewChange = (event: any) => {
    setViewType(event.key);
  };

  const onSortTypeChange = (event: any) => {
    if (event.key == "priceLowToHigh") {
      setSortType(SORT_TYPES.PRICE_LOW_TO_HIGH)
      activeFilters.sort = { f_price: "asc" };
    } else if (event.key == "priceHighToLow") {
      setSortType(SORT_TYPES.PRICE_HIGH_TO_LOW)
      activeFilters.sort = { f_price: "desc" };
    }
    //console.log(activeFilters);
    fetchProducts(activeFilters);
    setActiveFilters(activeFilters);
  };

  const viewTypeMenu = <Menu onClick={onViewChange} items={VIEW_OPTIONS} />;

  const sortTypeMenu = <Menu onClick={onSortTypeChange} items={SORT_OPTIONS} />;
  const isFreeSearch = () => {
    return (
      isEmpty(get(activeFilters, "category_id", {})) ||
      get(activeFilters, "category_id") === 1
    );
  };

  return (
    <div className={cx("w-full", styles.productHeaderWrapper)}>
      <MediaQuery minWidth={769}>
        <Breadcrumbs />
      
        <div className={cx(styles.productSearch, "flex justify-between mt-3 ")}>
          <div className="flex mb-4">
            {productHeaderTitle ? (
              <div className={styles.productSearchResultDesc}>
                {productHeaderTitle}
              </div>
            ) : (
              <>
                {isFreeSearch() ? (
                  <div className={styles.productSearchResultDesc}>
                    {`Search results for ${get(
                      activeFilters,
                      "name",
                      "' '"
                    )} in All Categories`}
                  </div>
                ) : (
                  <div className={styles.productHeaderText}>
                    {productHeaderTitle}
                  </div>
                )}
              </>
            )}

            {productInfo !== undefined && !isEmpty(productInfo) ? (
              <div className={cx(styles.pproductCount, "mt-5")}>
                ({productInfo.from}-{productInfo.to} products of{" "}
                {productInfo.total})
              </div>
            ) : null}

            {!isSearch ? (
              <Input
                value={searchText}
                placeholder="Search within these results"
                onChange={onSearhTextChange}
                style={{ width: isMax ? 300 : 220 }}
                suffix={<SearchOutlined />}
                size={"middle"}
              />
            ) : null}
          </div>
          <div>
            <Space size="middle">
              {/* <Radio.Group
								options={BRAND_PRICE_RADIO}
								onChange={onChange}
								value={radioStatus}
								optionType="button"
								buttonStyle="solid"
								size={"middle"}
							/> */}
              {isSearch ? (
                <Input
                  value={searchText}
                  placeholder="Search within these results"
                  onChange={onSearhTextChange}
                  style={{ width: isMax ? 300 : 220 }}
                  suffix={<SearchOutlined />}
                  size={"middle"}
                />
              ) : null}
              <Dropdown.Button
                icon={<DownOutlined />}
                overlay={viewTypeMenu}
                size={"middle"}
              >
                {VIEW_TYPE_VS_LABLES[viewType]}
              </Dropdown.Button>
              <Dropdown.Button
                icon={<DownOutlined />}
                overlay={sortTypeMenu}
                size={"middle"}
              >
                {SORT_OPTIONS_VS_LABLES[sortType]}
              </Dropdown.Button>
            </Space>
          </div>
        </div>
      </MediaQuery>
      <MediaQuery maxWidth={768}>
        <div className={styles.productHeaderTextMobile}> hghgg
          {productHeaderTitle ? productHeaderTitle : "All Products"}
        </div>
      </MediaQuery>
    </div>
  );
};

export default ProductHeaders;
