import {
  CrossIcon,
  SearchIcon,
  useAxios,
} from '@bjsdistribution/dms-component-library';
import React, { useEffect, useState } from 'react';
import styled from 'styled-components';
import {
  useAtom,
  useClientOutstandingReturnData,
  useClientPortal,
  useEndDate,
  useSearchText,
  useStartDate,
  useStatsCPCount,
} from '../store';
import dayjs from 'dayjs';
import { filtersReducerAtom } from '../order-daily-overview/header-filters/filterStore';
import { ApiResponse } from '../types';
import { javascriptStringDumpToJSON } from '../utils';
import { UsePaginationData } from '../order-daily-overview/store/store';
import { notification } from 'antd';
import { useParams } from 'react-router-dom';
import { returnCountType } from './ReturnStatus';

function ReturnSearchBar() {
  const [searchText, setSearchText] = useState('');
  const [debouncedSearchText, setDebouncedSearchText] = useSearchText();
  const [modifiedFilters, setModifiedFilters] = useState<any[]>([]);
  const [, setOutstandingData] = useClientOutstandingReturnData();
  const { status } = useParams();
  //condition on client view
  const [clientPortal] = useClientPortal();
  const [, setPaginationObject] = UsePaginationData();
  const handleInputChange = (event: React.ChangeEvent<HTMLInputElement>) => {
    setSearchText(event.target.value);
  };
  //CP
  const [startDate] = useStartDate();
  const [endDate] = useEndDate();
  const [state] = useAtom(filtersReducerAtom);
  const [, setCount] = useStatsCPCount();
  const [modifiedStatsFilters, setModifiedStatsFilters] = useState<any[]>([]);

  const { 'x-pagination': pagination } = state;

  useEffect(() => {
    const isClientOutstanding = clientPortal && status === 'outstanding_return';
    if (!isClientOutstanding) return;

    setModifiedFilters([
      { field: 'isdeleted', op: '=', value: 0 },
      { field: 'product_return_action_id', op: '=', value: 'RTS' },
    ]);
  }, []);

  useEffect(() => {
    if (!clientPortal) return;

    const stored = JSON.parse(localStorage.getItem('returnDate') || '{}');

    const sDate = startDate?.isValid?.() ? startDate : dayjs(stored?.startDate);
    const eDate = endDate?.isValid?.()
      ? endDate
      : stored?.endDate
      ? dayjs(stored?.endDate)
      : null;

    if (!sDate?.isValid?.()) return;

    let dateFilters = [];

    if (eDate && eDate.isValid()) {
      dateFilters = [
        { field: 'created_at', op: '>=', value: sDate.format('YYYY-MM-DD') },
        {
          field: 'created_at',
          op: '<=',
          value: eDate.add(1, 'day').format('YYYY-MM-DD'),
        },
      ];
    } else {
      dateFilters = [
        {
          field: 'created_at',
          op: '=',
          value: sDate.format('YYYY-MM-DD'),
        },
      ];
    }

    const updatedFilters =
      status === 'outstanding_return'
        ? [
            { field: 'isdeleted', op: '=', value: 0 },
            { field: 'product_return_action_id', op: '=', value: 'RTS' },
            ...dateFilters,
          ]
        : dateFilters;

    setModifiedFilters(updatedFilters);
  }, [startDate, endDate, status]);

  //For stats

  const getDateFilters = (
    startDate: dayjs.Dayjs | null,
    endDate: dayjs.Dayjs | null
  ) => {
    const stored = JSON.parse(localStorage.getItem('returnDate') || '{}');

    const sDate = startDate?.isValid?.() ? startDate : dayjs(stored?.startDate);
    const eDate = endDate?.isValid?.()
      ? endDate
      : stored?.endDate
      ? dayjs(stored?.endDate)
      : null;

    if (!sDate?.isValid?.()) return [];

    let dateFilters = [];

    if (eDate && eDate.isValid()) {
      dateFilters = [
        { field: 'created_at', op: '>=', value: sDate.format('YYYY-MM-DD') },
        {
          field: 'created_at',
          op: '<=',
          value: eDate.add(1, 'day').format('YYYY-MM-DD'),
        },
      ];
    } else {
      dateFilters = [
        {
          field: 'created_at',
          op: '=',
          value: sDate.format('YYYY-MM-DD'),
        },
      ];
    }

    return dateFilters;
  };

  useEffect(() => {
    if (!clientPortal) return;

    const dateFilters = getDateFilters(startDate, endDate);
    setModifiedStatsFilters(dateFilters);
  }, [startDate, endDate]);

  const {
    // loading,
    paginationData,
    fetchData: getPendingData,
    // data: fetchedReturnOrderData,
  } = useAxios<ApiResponse>({
    endpoint: '/v1/return/product/pending/',
    method: 'GET',
    filters: modifiedFilters,
    pagination: pagination,
  });

  useEffect(() => {
    if (debouncedSearchText?.length > 1) {
      getPendingData({
        endPointQuery: `?search_term=${debouncedSearchText}`,
      }).then((response: any) => {
        if (paginationData) {
          const formattedPagination = javascriptStringDumpToJSON(
            paginationData
          );
          const { ...rest } = formattedPagination;
          setPaginationObject(rest);
        }

        if (response?.data?.length > 0) {
          setOutstandingData(response?.data);
        } else {
          setOutstandingData([]);
        }
      });
    } else if (
      debouncedSearchText?.length > 0 &&
      debouncedSearchText?.length <= 2
    ) {
      notification.warning({
        message: 'Search Phrase cannot be less than 3 characters',
      });
    }
  }, [debouncedSearchText]);

  // Debouncing effect
  useEffect(() => {
    const handler = setTimeout(() => {
      setDebouncedSearchText(searchText);
    }, 1000);
    return () => {
      clearTimeout(handler);
    };
  }, [searchText]);

  useEffect(() => {
    if (debouncedSearchText?.length === 0) {
      setSearchText('');
    }
  }, [debouncedSearchText]);

  //
  const { fetchData: fetchStatsData } = useAxios<{
    data: returnCountType[];
  }>({
    endpoint: `v1/portal/return/stats/`,
    method: 'GET',
    pagination: { is_pagination: false },
    filters: modifiedStatsFilters,
  });

  useEffect(() => {
    const isClientOutstanding = clientPortal && status === 'outstanding_return';
    if (!isClientOutstanding || debouncedSearchText?.length < 3) return;

    const fetchStats = async () => {
      const response = await fetchStatsData({
        endPointQuery: `?search_term=${debouncedSearchText}&type=outstanding`,
      });
      //@ts-ignore
      if (response?.data) {
        //@ts-ignore
        setCount(response?.data); // Set the count here
      } else {
        setCount(null); // fallback if no data
      }
    };

    fetchStats();
  }, [debouncedSearchText, status, clientPortal]);

  const handleClear = () => {
    setSearchText('');
  };
  return (
    <Search>
      <SearchIcon />

      <SearchInput
        type="text"
        placeholder="Search"
        value={searchText}
        onChange={handleInputChange}
      />
      {searchText ? (
        <ClearButton className="clear" onClick={handleClear}>
          <CrossIcon />
        </ClearButton>
      ) : null}
    </Search>
  );
}

const ClearButton = styled.button`
  border: none;
  background: none;
  position: relative;
  border: none;
  cursor: pointer;
  padding: 0 4px;
  font-size: 0;
  &:hover {
    color: #000;
  }
`;

const Search = styled.div`
  display: flex;
  padding: 4px 12px;
  align-items: center;
  gap: 8px;
  align-self: stretch;
  border-radius: 20px;
  border: 1px solid var(--Neutral-Gray-Gray-100, #e0e2e7);
  background-color: var(--Flowkit-White, #fff);
  height: 35px;
  box-shadow: 0px 1px 2px 0px rgba(16, 24, 40, 0.05);
`;
const SearchInput = styled.input`
  border: none;
  outline: none;
  flex-grow: 1;
  width: 100%;
  background: transparent;
`;

export default React.memo(ReturnSearchBar);
