import { AutoComplete, Button, Input, InputRef, List, Typography } from "antd";
import cx from "classnames";
import { useRouter } from "next/router";
import { FC, useCallback, useContext, useEffect, useRef, useState } from "react";
import styles from "./mobileSearch.module.scss";
import * as SearchAPI from "../../../../pages/api/search";
import { FiSearch } from "react-icons/fi";
import {  AudioOutlined } from "@ant-design/icons";
import SpeechRecognition, {  useSpeechRecognition } from "react-speech-recognition";
import { debounce } from "lodash";
import { createBreadcrumb, getFlattenCategory } from "../../../globalUtils/utils";
import shopConetxt from "../../../../context/shopConetxt";
import TypingHeadline from "../../search/TypingHeadline";
import TaglineTransition from "../../search/TaglineTransition";

const MobileSearch: FC<any> = () => {
  const router = useRouter();
  const { setCategoryTreeNested, categoryTreeNested, setCategoryBreadcrumb } =
		useContext(shopConetxt);
  const [searchTerm, setSearchTerm] = useState("");
  const [isSpeechResults, setIsSpeechResults] = useState(false);
  const [selectedCategory, setSelectedCategory] = useState("All");
  const [autoComplete, setAutoComplete] = useState([]);
  const inputRef = useRef<InputRef>(null);
  const [sellerBrands, setSellerBrands] = useState([]);
  const searchHandler = async () => {
    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}`,
					
				});
		}
    return;
    router.push({
      pathname: `/products/${selectedCategory}`,
      query: {
        search: searchTerm,
      },
    });
  };

  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 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);
		}
	}
  const handleAutoCompleteChange = useCallback(debounce(_searchText, 1000), []);

  const Suffix: any = ({ startListening, listening }: any) => {
    return (
      <>
        <div
          className={cx(
            "flex justify-center items-center ",
            styles.audioStyle,
            listening ? styles.cardcontainer : ""
          )}          
          onTouchStart={startListening}
          onClick={startListening}
          onContextMenu={(e)=> e.preventDefault()}
        >
          <AudioOutlined
            className={styles.audioicon}
            style={{
              fontSize: 16,
            }}
          />
        </div>
      </>
    );
  };

  const {
    transcript,
    listening,
    resetTranscript,
  } = useSpeechRecognition();

  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])


  return (
    <>
      <div className={styles.mobileSearchContainer}>
        <div className={styles.inputGroupMain}>
          <div className={styles.inputGroup}>
            <AutoComplete
              value={searchTerm}
              placeholder="Search Products "
              options={isSpeechResults ? [] : autoComplete}
              className={cx(styles.inputBox,styles.mobilesearchInput)}
              onChange={(evt: any) => {
                setIsSpeechResults(false) ;
                handleAutoCompleteChange(evt);
              }}
              onSelect={(evt: any,value:any) => {							
                redirectIfCat(value,evt)
              }}
              onSearch={(evt: any) => {
                setIsSpeechResults(false) ;
                setSearchTerm(evt);
              }}
              onKeyDown={(event: any) => {
                if (event.keyCode === 13) {
                  searchHandler();
                }
              }}
            >
              {/* <Input
                ref={inputRef}
                
                placeholder=""
                className={styles.inputBox}
              /> */}
              <Input
              ref={inputRef}
              className={styles.inputBox}
                  placeholder="Search Products by title, sku, category, brand etc."
                  suffix={<Suffix
                  // isMax={isMax}
                  startListening={startListening}
                  stopListening={stopListening}
                  listening={listening}
                />}
                />
             
            </AutoComplete>
            {/* <Button
              type="default"
              className={cx(styles.buttonMain,styles.searchAction)}
            >
                
                
            </Button> */}
            <Button
              type="primary"
              className={styles.buttonMain}
              onClick={searchHandler}
            >
              <FiSearch style={{ fontSize: "22px" }} />
            </Button>
          </div>
        </div>
        {isSpeechResults && autoComplete.length > 0 && <div className={styles.autoresumts}>
          <List           
            bordered
            dataSource={autoComplete}
            renderItem={(item:any) => (
              <List.Item onClick={() => {
                setSearchTerm(item.label);
                setIsSpeechResults(false);
              }}>
                  {item.label}
              </List.Item>
            )}
          />
          </div>
          }      
        <div className={styles.genuineText}>
          {/* <span className={styles.main100Text}>#100% Genuine</span>
          <span className={styles.partsText}>Spare Parts</span> */}
           {/* <TypingHeadline
        className={cx(styles.main100Text)}
        taglines={["All Your Industrial Needs in One Place", "Get Best Prices Instantly — Send RFQ","Procurement Made Easy — RFQ Now"]}
      /> */}
        <TaglineTransition  className={cx(styles.main100Text)}/>
        </div>
      </div>
    </>
  );
};

export default MobileSearch;
