import React, { useEffect, useRef, useState } from 'react';
import styled from 'styled-components';
import { SearchIcon } from '../../../../../assets/icons';
import { CrossIcon, useAxios } from '@bjsdistribution/dms-component-library';
import {
  useAtom,
  useClientData,
  useInternalSearchText,
} from '../../../../order-view/store';
import { ClientData } from '../../../common/interface';
import { notification } from 'antd';
import { overviewfiltersReducerAtom } from '../../../header-filters/overViewFilter';
import { UsePaginationOverviewData } from '../../../store/store';

const SearchType = () => {
  const [searchText, setSearchText] = useState('');
  const [, setClientData] = useClientData();
  const [debouncedSearchText, setDebouncedSearchText] = useInternalSearchText();
  const [state] = useAtom(overviewfiltersReducerAtom);
  const [, setPaginationObject] = UsePaginationOverviewData();
  const didMountRef = useRef(false);
  const { 'x-filters': filters, 'x-pagination': pagination } = state;

  useEffect(() => {
    const handler = setTimeout(() => {
      setDebouncedSearchText(searchText);
    }, 1000);

    return () => clearTimeout(handler);
  }, [searchText]);

  const { fetchData: fetchSearchedData, data: searchData, loading } = useAxios<{
    data: any[];
  }>({
    endpoint: `/v1/return/search/?search_phrase=${debouncedSearchText}`,
    method: 'GET',
  });

  useEffect(() => {
    if (!didMountRef.current) {
      didMountRef.current = true;
      return;
    }

    if (debouncedSearchText?.length > 0) {
      fetchSearchedData();
    } else {
      // setOrderData([]);
      fetchAllData();
    }
  }, [debouncedSearchText]);

  useEffect(() => {
    if (searchData && Array.isArray(searchData?.data)) {
      setClientData(searchData?.data);
    }
  }, [searchData, loading]);

  const handleClear = () => {
    setSearchText('');
    setDebouncedSearchText('');
  };

  const {
    data: fetchedClientData,
    loading: statsDataLoading,
    paginationData,
    fetchData: fetchAllData,
  } = useAxios<{
    data: ClientData[];
  }>({
    endpoint: `/v1/return/product/stats/`,
    method: 'GET',
    //@ts-ignore
    pagination: pagination,
    filters: filters,
  });

  useEffect(() => {
    if (fetchedClientData && fetchedClientData.data) {
      const result = fetchedClientData?.data;
      setClientData(result);
      if (paginationData) {
        try {
          const { count, ...rest } = JSON.parse(paginationData);
          setPaginationObject(rest);
        } catch (error) {
          console.error('Error parsing paginationData:', error);
          notification.error({
            message: 'Error',
            description: 'Failed to parse pagination data',
          });
        }
      }
    }
  }, [statsDataLoading]);

  return (
    <Search>
      <SearchIcon />
      <SearchInput
        type="text"
        placeholder="Search"
        value={searchText}
        onChange={(e: any) => setSearchText(e.target.value)}
      />
      {searchText && (
        <ClearButton className="clear" onClick={handleClear}>
          <CrossIcon />
        </ClearButton>
      )}
    </Search>
  );
};

const Search = styled.div`
  position: relative;
  svg {
    position: absolute;
    left: 12px;
    top: 50%;
    transform: translateY(-50%);
  }
  .clear {
    position: absolute;
    right: 32px;
    top: 50%;
    transform: translateY(-50%);
  }
`;

const ClearButton = styled.button`
  border: none;
  color: rgba(0, 0, 0, 0.25);
  cursor: pointer;
  padding: 0 8px;
  font-size: 14px;
  background: transparent;
  &:hover {
    color: #000;
  }
`;

const SearchInput = styled.input`
  border-radius: 20px;
  border: 1px solid #e0e2e7;
  background: #fff;
  box-shadow: 0px 1px 2px rgba(16, 24, 40, 0.05);
  display: flex;
  padding: 8.5px 12px;
  padding-left: 39px;
  width: 100%;
  &:focus {
    outline: none;
    border-color: gray;
  }
`;

export default SearchType;
