import { AutoComplete, Button, Input, Select } from "antd";
import styles from "./search.module.scss";
import { useRouter } from "next/router";
import get from "lodash/get";
import debounce from "lodash/debounce";
import { FiSearch } from "react-icons/fi";
import { TbCameraPlus } from "react-icons/tb";
TbCameraPlus;
import {
  AudioOutlined,
  CameraOutlined,
  CaretDownOutlined,
  DownCircleTwoTone,
  DownOutlined,
  SearchOutlined,
  UserOutlined,
} from "@ant-design/icons";
import * as GallaryApi from "../../../pages/api/gallaries";

import { FC, useEffect, useState, useContext, useCallback } from "react";
import cx from "classnames";
import { popularSearchs } from "../../../mockData/search";
import * as CategoryAPI from "../../../pages/api/category";
import {
  fetchAttributesES,
  fetchCatgories,
} from "../../../pages/api/categories";
import * as SearchAPI from "../../../pages/api/search";
import shopConetxt from "../../../context/shopConetxt";
import { createBreadcrumb, getFlattenCategory } from "../../globalUtils/utils";
import "regenerator-runtime";
import SpeechRecognition, {
  useSpeechRecognition,
} from "react-speech-recognition";
import { BiChevronDown } from "react-icons/bi";
import TypingHeadline from "./TypingHeadline";
import TaglineTransition from "./TaglineTransition";

// import { createSpeechlySpeechRecognition } from '@speechly/speech-recognition-polyfill';
// const appId = '445b23d5-fa16-4ec1-9039-3efbc500eac8';
// const SpeechlySpeechRecognition = createSpeechlySpeechRecognition(appId);
// SpeechRecognition.applyPolyfill(SpeechlySpeechRecognition);

const Suffix: any = ({ startListening, stopListening, listening }: any) => {
  const router: any = useRouter();

  return (
    <>
      <div
        role="button"
        tabIndex={0}
        className={cx(styles.audioStyle, listening ? styles.cardcontainer : "")}
        onTouchStart={startListening}
        onMouseDown={startListening}
        onTouchEnd={stopListening}
        onMouseUp={stopListening}
      >
        <AudioOutlined
          className={styles.audioicon}
          style={{
            fontSize: 20,
          }}
        />
      </div>
      {/* <div className={cx(styles.audioStyle)}>
        <TbCameraPlus
          style={{
            fontSize: 20,
          }}
        />
      </div> */}
    </>
  );
};
const Search: FC<any> = ({ brands, categoryData, categoryTreeData }): any => {
  const { setCategoryTreeNested, categoryTreeNested, setCategoryBreadcrumb } =
    useContext(shopConetxt);
  const router = useRouter();
  const [sellerBrands, setSellerBrands] = useState([]);
  const [searchTerm, setSearchTerm] = useState("");
  const [category, setCategory] = useState([]);
  const [selectedCategory, setSelectedCategory] = useState("All Category");
  const [autoComplete, setAutoComplete] = useState([]);
  const searchHandler = (): any => {
    const val = selectedCategory === "All Category" ? "All" : selectedCategory;
    if (searchTerm != "") {
      if (val !== "All") {
        const flattenCategory = getFlattenCategory(categoryTreeNested);

        const breadCrumbData = createBreadcrumb(val, flattenCategory);

        setCategoryBreadcrumb(breadCrumbData);
      } else {
        setCategoryBreadcrumb([{}]);
      }
      router.push({
        pathname: `/products/${val}`,
        query: {
          search: searchTerm,
          id: val,
        },
      });
    } else if (val !== "All") {
      const flattenCategory = getFlattenCategory(categoryTreeNested);

      const breadCrumbData = createBreadcrumb(val, flattenCategory);

      setCategoryBreadcrumb(breadCrumbData);
      router.push({
        pathname: `/products/${val}`,
      });
    }
  };

  useEffect(() => {
    // CategoryAPI.fetchCategory().then((res) => {
    // if (res)
    categoryData.sort((a: any, b: any) => a.name.localeCompare(b.name));
    setCategory(categoryData);
    // });
    // fetchCatgories({ category_id: 1 }).then((res) =>
    setCategoryTreeNested(get(categoryTreeData, "categories[0]", {}));
    // );
    setTimeout(() => {
      const _activeFilterES = {
        q: {
          from: 1,
          size: 1000,
          query: { query_string: { query: "*" } },
        },
        index: "attributes_index",
      };
      fetchAttributesES(_activeFilterES).then((res: any) => {
        const _attr = res?.hits?.hits;
        const _attr_ = _attr?.filter((attr: any) => {
          return attr?._source?.code == "brand";
        });
        if (_attr_?.length > 0) {
          const _attribute_opts =
            _attr_[0]?._source?.attribute_opts?.split(",");
          //const _attribute_values = (_attr_[0]._source.attribute_values).split(",");
          setSellerBrands(_attribute_opts);
        }
      });
    }, 200);
  }, [categoryData, categoryTreeData]);

  // useEffect(() => {
  // 	setAutoComplete([]);
  // 	if (searchTerm != "") {
  // 		_searchText(searchTerm);
  // 	}
  // }, [searchTerm]);
  const {
    transcript,
    listening,
    resetTranscript,
    browserSupportsSpeechRecognition,
  } = useSpeechRecognition();

  // if (!browserSupportsSpeechRecognition) {
  // 	return <span>Browser doesn't support speech recognition.</span>;
  // }
  const startListening = () =>
    SpeechRecognition.startListening({ continuous: true });
  const stopListening = () => {
    SpeechRecognition.stopListening();
    if (transcript != "") {
      setSearchTerm(transcript);
    }
  };
  // console.log(browserSupportsSpeechRecognition,"browserSupportsSpeechRecognition");

  const renderTitle = (title: string) => (
    <span style={{ fontSize: "14px" }}>{title}</span>
  );

  const renderItem = (title: string, text: string) => ({
    value: title,
    label: <div style={{ fontSize: "16px" }}>{title}</div>,
  });

  const renderCatItem = (title: string, id: any) => ({
    value: id,
    label: <div style={{ fontSize: "16px" }}>{title}</div>,
  });

  function containsNumbers(str: any) {
    return /[0-9]/.test(str);
  }

  const _searchText = (text: string = searchTerm) => {
    // setAutoComplete([]);
    const searchOptions: any = [
      {
        label: renderTitle("Suggestions"),
        options: [],
      },
      {
        label: renderTitle("Categories"),
        options: [],
      },
      {
        label: renderTitle("Brands"),
        options: [],
      },
    ];
    SearchAPI.fetchAutoCompleteWithMultiCall(text).then((resMulti: any) => {
      const res = resMulti[0];
      const array_strng: any = [];
      const array_strng_GroupBy: any = [];
      const array_strng_Brands: any = [];
      searchOptions[0].options = [];
      if (res?.hits?.hits.length > 0) {
        res?.hits?.hits?.forEach((element: any) => {
          const name =
            element._source.name === null
              ? element._source.product_number
              : element._source.name;

          if (element._source.groupby_key != "") {
            if (
              array_strng_GroupBy.indexOf(element._source.groupby_key) == -1
            ) {
              array_strng_GroupBy.push(element._source.groupby_key);
              array_strng.push(renderItem(element._source.groupby_key, text));
            }
          } else {
            array_strng.push(renderItem(name, text));
          }
          if (element._source.brand_label != "") {
            if (array_strng_Brands.indexOf(element._source.brand_label) == -1)
              array_strng_Brands.push(element._source.brand_label);
          }
        });
        searchOptions[0].options = [...array_strng];
      }
      const array_cat: any = [];
      const res_cat = resMulti[1];
      searchOptions[1].options = [];
      if (res_cat?.hits?.hits.length > 0) {
        res_cat?.hits?.hits?.forEach((element: any) => {
          const _sourceCat = element._source;
          array_cat.push(
            renderCatItem(_sourceCat.name, "Cat_" + _sourceCat.id)
          );
        });
        searchOptions[1].options = [...array_cat];
      }
      searchOptions[2].options = [];
      sellerBrands.map((itm: any) => {
        if (
          itm.toLowerCase().includes(text.trim().toLowerCase()) &&
          array_strng_Brands.indexOf(itm) == -1
        )
          searchOptions[2].options.push(renderItem(itm, text));
      });
      array_strng_Brands.map((itm: any) => {
        if (
          itm.toLowerCase().includes(text.trim().toLowerCase()) &&
          array_strng_Brands.indexOf(itm) == -1
        )
          searchOptions[2].options.push(renderItem(itm, text));
      });

      if (
        !(
          searchOptions[0].options.length == 0 &&
          searchOptions[1].options.length == 0 &&
          searchOptions[2].options.length == 0
        )
      ) {
        setAutoComplete(searchOptions);
      } else {
        setAutoComplete([]);
      }
      resetTranscript();
    });
  };
  const handleAutoCompleteChange = useCallback(debounce(_searchText, 100), []);

  const routeToPage = (categoryName: any) => {
    // router.push(`/categories/${categoryId}`);
    router.push({
      pathname: `/products/All`,
      query: {
        search: categoryName,
        id: "All",
      },
    });
  };

  const redirectIfCat = (option: any, evt: any) => {
    const val = option.value;
    if (val.includes("Cat_")) {
      const num1 = parseInt(val.replace("Cat_", ""));
      const flattenCategory = getFlattenCategory(categoryTreeNested);

      const breadCrumbData = createBreadcrumb(num1, flattenCategory);

      setCategoryBreadcrumb(breadCrumbData);
      router.push({
        pathname: `/products/${val.replace("Cat_", "")}`,
        query: {
          search: "",
          id: val.replace("Cat_", ""),
        },
      });
    } else {
      setSearchTerm(evt);
    }
  };

  return (
    <div
      className={cx("")}
      // className={`${styles.search} flex flex-col justify-center items-center home-search-bar`}
    >
      {/* <h2 className={cx(styles.sectionTitle)}>#100% Genuine Spare Parts</h2> */}
      {/* <TypingHeadline
        className={cx(styles.sectionTitle)}
        taglines={["All Your Industrial Needs in One Place", "Get Best Prices Instantly — Send RFQ","Procurement Made Easy — RFQ Now"]}
      /> */}
      <TaglineTransition  className={cx(styles.sectionTitle)}/>
      <div className={cx(styles.searchCol)}>
        <div className={styles.inputGroupMain}>
          <Select
            value={selectedCategory}
            placeholder="Select Category"
            optionFilterProp="children"
            className={styles.searchDropdown}
            onChange={(value) => setSelectedCategory(value)}
            suffixIcon={
              <BiChevronDown
                style={{ fontSize: "1.5em" }}
                className="ant-select-suffix"
              />
            }
          >
            <Select.Option value={"All Category"} key={"All Category"}>
              All Category
            </Select.Option>
            {category.map(({ id, name, slug }) => (
              <Select.Option value={id} key={id}>
                {name}
              </Select.Option>
            ))}
          </Select>
          <AutoComplete
            options={autoComplete}
            dropdownMatchSelectWidth={false}
            className={styles.inputBox}
            value={searchTerm}
            onChange={(evt: any) =>
              browserSupportsSpeechRecognition
                ? handleAutoCompleteChange(evt)
                : _searchText(evt)
            }
            onSelect={(evt: any, value: any) => {
              redirectIfCat(value, evt);
            }}
            onSearch={(evt: any) => {
              setSearchTerm(evt);
            }}
            onKeyDown={(event: any) => {
              if (event.keyCode === 13) {
                searchHandler();
              }
            }}
          >
            <Input
              placeholder="Search Products by title, sku, category, brand etc."
              suffix={
                browserSupportsSpeechRecognition ? (
                  <Suffix
                    startListening={startListening}
                    stopListening={stopListening}
                    listening={listening}
                  />
                ) : null
              }
            />
          </AutoComplete>
          <Button
            type="primary"
            className={styles.buttonMain}
            onClick={searchHandler}
          >
            <span className={styles.textSearch}>Search</span>
            <FiSearch style={{ fontSize: "20px", marginLeft: "1em" }} />
          </Button>
        </div>
      </div>
      <div className="flex justify-center items-center gap-4 text-xs">
        <span className="font-light">Popular Searches:</span>
        {popularSearchs.map((searctTerm) => (
          <a
            role="button"
            tabIndex={0}
            key={searctTerm.id}
            className={styles.textInputBottomText}
            onClick={() => {
              routeToPage(searctTerm.name);
            }}
          >
            {searctTerm.name}
          </a>
        ))}
      </div>
    </div>
  );
};

export default Search;
