import {
  CrossIcon,
  SearchIcon,
  useAxios,
} from '@bjsdistribution/dms-component-library';
import React, { useEffect, useState } from 'react';
import styled from 'styled-components';
import {
  useAtom,
  useClientPortal,
  useEndDate,
  useReturnConfirmedOrderData,
  useSearchAfterText,
  useStartDate,
  useStatsCPCount,
} from '../store';

import { ApiResponse } from '../types';
import { javascriptStringDumpToJSON } from '../utils';
import { UsePaginationData } from '../order-daily-overview/store/store';
import { notification } from 'antd';
import { filtersReducerReturnAtom } from '../order-daily-overview/return-after-table/table-filters/ReturnFilterStore';
import dayjs from 'dayjs';
import { returnCountType } from './ReturnStatus';
import { useParams } from 'react-router-dom';

function ReturnAfterSearchBar() {
  const [searchText, setSearchText] = useState('');
  const [debouncedSearchText, setDebouncedSearchText] = useSearchAfterText();
  const [, setReturnConfirmedData] = useReturnConfirmedOrderData();
  //condition on client view
  const [, setPaginationObject] = UsePaginationData();
  const handleInputChange = (event: React.ChangeEvent<HTMLInputElement>) => {
    setSearchText(event.target.value);
  };
  //CP
  const [modifiedStatsFilters, setModifiedStatsFilters] = useState<any[]>([]);
  const [startDate] = useStartDate();
  const [endDate] = useEndDate();
  const [state] = useAtom(filtersReducerReturnAtom);
  const { 'x-filters': filters, 'x-pagination': pagination } = state;
  const [count, setCount] = useStatsCPCount();
  const [clientPortal] = useClientPortal();
  const { status } = useParams();

  const { paginationData, fetchData: returnAfterCall } = useAxios<ApiResponse>({
    endpoint: '/v1/return/orders/',
    method: 'GET',
    filters: filters && filters?.length > 0 ? filters : undefined,
    pagination: pagination,
  });

  useEffect(() => {
    if (debouncedSearchText?.length > 1) {
      returnAfterCall({
        endPointQuery: `?search_term=${debouncedSearchText}`,
      }).then((response: any) => {
        if (paginationData) {
          const formattedPagination = javascriptStringDumpToJSON(
            paginationData
          );
          const { ...rest } = formattedPagination;
          setPaginationObject(rest);
        }
        if (response?.data) {
          setReturnConfirmedData(response?.data);
        } else {
          setReturnConfirmedData([]);
        }
      });
    } 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 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 { data: statsData, fetchData: fetchStatsData } = useAxios<{
    data: returnCountType[];
  }>({
    endpoint: `v1/portal/return/stats/`,
    method: 'GET',
    pagination: { is_pagination: false },
    filters: modifiedStatsFilters,
  });

  useEffect(() => {
    const validStatuses = ['scheduled_for_return', 'return_completed'];
    const isClientView = clientPortal && validStatuses.includes(status || '');

    if (!isClientView || debouncedSearchText?.length < 3) return;
    console.log('IN after view entered');
    const statusTypeMap: Record<string, string> = {
      scheduled_for_return: 'scheduled',
      return_completed: 'complete',
    };

    const type = statusTypeMap[status as keyof typeof statusTypeMap];

    const fetchStats = async () => {
      const response = await fetchStatsData({
        endPointQuery: `?search_term=${debouncedSearchText}&type=${type}`,
      });
      //@ts-ignore
      if (response?.data) {
        console.log('inside response', response);
        // @ts-ignore
        setCount(response?.data);
      } else {
        setCount(null);
      }
    };

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

  console.log(statsData, 'statsData');

  console.log(count, 'new count');

  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(ReturnAfterSearchBar);
