import { AutoComplete, Button, Input, Modal, Spin } from "antd";
import cx from "classnames";
import { useRouter } from "next/router";
import { FC, useCallback, useEffect, useState } from "react";
import styles from "./mobileSearch.module.scss";
import {
  AudioOutlined,
  CameraOutlined,
  SearchOutlined,
} from "@ant-design/icons";
import * as SearchAPI from "../../../../pages/api/search";
import { debounce } from "lodash";
import SpeechRecognition, { useSpeechRecognition } from "react-speech-recognition";
const suffix: any = (
  <>
    <div
      className="flex justify-center items-center my-2"
      style={{
        width: "32px",
        marginRight: "20px",
        height: "32px",
        border: "0.5px solid #E5E5E5",
        boxShadow: "0px 0px 2px rgba(0, 0, 0, 0.08)",
        borderRadius: "50%",
      }}
    >
      <AudioOutlined
        style={{
          fontSize: 16,
        }}
      />
    </div>
    {/* <div
      className="flex justify-center items-center"
      style={{
        width: "32px",
        height: "32px",
        border: "0.5px solid #E5E5E5",
        boxShadow: "0px 0px 2px rgba(0, 0, 0, 0.08)",
        borderRadius: "50%",
      }}
    >
      <CameraOutlined
        style={{
          fontSize: 16,
        }}
      />
    </div> */}
  </>
);

const MobileSearchPopup: FC<any> = (props) => {
  const router = useRouter();
  const searchParams = router?.query?.search;
  const { isModalVisible, handleClose } = props;
  const [searchTerm, setSearchTerm] = useState(searchParams);
  const [selectedCategory, setSelectedCategory] = useState("All");
  const [autoComplete, setAutoComplete] = useState([]);
  const [isLoading, setIsLoading] = useState(false);
  const [sellerBrands, setSellerBrands] = useState([]);
  const [isSpeechResults, setIsSpeechResults] = useState(false);
  const {
    transcript,
    listening,
    resetTranscript,
  } = useSpeechRecognition();
  const searchHandler = (): any => {
   
    if (searchTerm != "") {
      setIsLoading(true);
    if (props?.page) {
      router.push({
        pathname: `/products/${selectedCategory}`,
        query: {
          search: searchTerm,
        },
      });
    } else {
      router.push({
        pathname: `/products/${selectedCategory}`,
        query: {
          search: searchTerm,
        },
      });
    }
    setTimeout(() => {
      setIsLoading(false);
    }, 1000);
  }
  };

  useEffect(() => {
    setAutoComplete([]);
    if (searchTerm != "") {
      _searchText(searchTerm);
    }
  }, [searchTerm]);
  
  const renderTitle = (title: string) => (
    <span>
      {title}
    </span>
  );
  const renderItem = (title: string, text: string) => ({
    value: title,
    label: (
      <div>
        {title}
      </div>
    ),
  });

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


  const _searchText = (text: any = 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 startListening = () => {
    setSearchTerm('');
    setAutoComplete([]);
    setIsSpeechResults(true) ;
    SpeechRecognition.startListening({ continuous: true });
    setTimeout(() => {
        SpeechRecognition.stopListening();
        resetTranscript();
    }, 5000);
  }
 
const stopListening = () => {
  SpeechRecognition.stopListening();
  if (transcript != "") {
    setSearchTerm(transcript);
  }
};
  useEffect(() =>{
    if(transcript != ''){
      setSearchTerm(transcript);
      _searchText(transcript);   
    }
    
  },[transcript])
  const handleAutoCompleteChange = useCallback(debounce(_searchText, 1000), []);
  return (
    <>
      <Modal
        width={830}
        visible={isModalVisible}
        onOk={handleClose}
        onCancel={handleClose}
        footer={null}
        destroyOnClose={true}
        // title="Product Search"
      >
        <div className={styles.mobileSearchContainer}>
          <h2 className={styles.partsText}>Product Search</h2>
          <div className={styles.inputGroup}>
            <AutoComplete
              value={searchTerm}
              placeholder="Search Products "
              options={autoComplete}
              className={styles.inputBox}
              onChange={(evt: any) => {
                setSearchTerm(evt);
                _searchText(evt);
              }}
              onSelect={(evt: any) => {
                setSearchTerm(evt);
                _searchText(evt);
              }}
              onSearch={(evt: any) => {
                setSearchTerm(evt);
                _searchText(evt);
              }}
              onKeyDown={(event: any) => {
                if (event.keyCode === 13) {
                  searchHandler();
                }
              }}
            />
          </div>
          <div className={styles.iconsPopup}>
            <div className={styles.iconsData}>{suffix}</div>
          </div>

          <Button
            type="primary"
            className={styles.buttonMainPopUp}
            onClick={searchHandler}
          >
            <span className={styles.textSearch}>Search</span>
            <SearchOutlined />
          </Button>
          <div>
            <div className={styles.advancedText}>Advanced Search</div>
          </div>
        </div>
      </Modal>
      <div
        className={cx("justify-center align-center")}
        style={{
          width: "100%",
          left: "50%",
          top: "50%",
          background: "tranparent",
          position: "fixed",
          transform: "translate(-25% , -50%)",
        }}
      >
        <Spin spinning={isLoading} size="large" />
      </div>
    </>
  );
};

export default MobileSearchPopup;
