import {
  CountItem,
  device,
  useAxios,
} from '@bjsdistribution/dms-component-library';
import React, { useEffect, useRef, useState } from 'react';
import styled from 'styled-components';
import {
  useActiveCardId,
  useAtom,
  useClientPortal,
  useEndDate,
  useSearchAfterText,
  useSearchText,
  useStartDate,
  useStatsCPCount,
} from '../store';
import { useNavigate, useParams } from 'react-router-dom';
import { filtersReducerReturnAtom } from '../order-daily-overview/return-after-table/table-filters/ReturnFilterStore';
import dayjs from 'dayjs';
export type returnCountType = {
  outstanding_count: number | null;
  scheduled_count: number;
  completed_count: number;
};
const ReturnStatus = () => {
  //CP
  type returnCountType = {
    outstanding_count: number | null;
    scheduled_count: number;
    completed_count: number;
  };

  // const [count, setCount] = useState<returnCountType[] | undefined>();
  const [activeCardId, setActiveCardId] = useActiveCardId();
  const [, dispatch] = useAtom(filtersReducerReturnAtom);
  const { status } = useParams();
  const [count, setCount] = useStatsCPCount();
  const [startDate] = useStartDate();
  const [endDate] = useEndDate();
  const [clientPortal] = useClientPortal();
  const [modifiedFilters, setModifiedFilters] = useState<any[]>([]);
  const [debouncedSearchText] = useSearchText();
  const [debouncedSearchAfterText] = useSearchAfterText();

  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);
    setModifiedFilters(dateFilters);
  }, [startDate, endDate]);

  //stats API

  const { data: statsData, loading: apiLoading, fetchData } = useAxios<{
    data: returnCountType[];
  }>({
    endpoint: `v1/portal/return/stats/`,
    method: 'GET',
    //@ts-ignore
    pagination: { is_pagination: false },
    filters: modifiedFilters,
  });

  const prevSearchTextRef = useRef('');
  const prevSearchAfterTextRef = useRef('');

  useEffect(() => {
    const prev = prevSearchTextRef.current;
    if (clientPortal && prev && debouncedSearchText === '') {
      fetchData();
    }
    prevSearchTextRef.current = debouncedSearchText;
  }, [debouncedSearchText, startDate, endDate]);

  useEffect(() => {
    const prev = prevSearchAfterTextRef.current;
    if (clientPortal && prev && debouncedSearchAfterText === '') {
      fetchData();
    }
    prevSearchAfterTextRef.current = debouncedSearchAfterText;
  }, [debouncedSearchAfterText, startDate, endDate]);

  console.log(debouncedSearchText, 'debouncedSearchText');
  console.log(debouncedSearchAfterText, 'debouncedSearchAfterText');
  useEffect(() => {
    fetchData();
  }, [startDate, endDate]);

  useEffect(() => {
    if (statsData && statsData?.data) {
      const data = statsData?.data;
      setCount(data);
    }
  }, [apiLoading]);

  const returnCounts = [
    {
      id: 1,
      icon: 'outstanding_return',
      status: 'outstanding_return',
      count: count?.outstanding_count || 0,
      label: 'Outstanding Return',
    },
    {
      id: 2,
      icon: 'scheduled_for_return',
      status: 'scheduled_for_return',
      count: count?.scheduled_count || 0,
      label: 'Scheduled For Return',
    },
    {
      id: 3,
      icon: 'return_completed',
      status: 'return_completed',
      count: count?.completed_count || 0,
      label: 'Return Completed',
    },
  ];
  const navigate = useNavigate();
  const [, setDebouncedSearchText] = useSearchAfterText();

  const handleCardClick = (item: any) => {
    if (activeCardId === item?.id) {
      return;
    }
    setActiveCardId(item?.id);
    navigate(`/return/${item?.status}`);
    setDebouncedSearchText('');
    if (item?.status == 'scheduled_for_return') {
      dispatch({
        type: 'SET_SCHEDULED_RETURN_FILTER',
        payload:
          'awaiting confirmation,awaiting route,routed,confirmed,on hold,subcontracted',
      });
      dispatch({
        type: 'SET_PAGE',
        payload: 1,
      });
    }
    if (item?.status == 'return_completed') {
      dispatch({
        type: 'SET_RETURN_COMPLETED_FILTER',
        payload: 'complete',
      });
      dispatch({
        type: 'SET_PAGE',
        payload: 1,
      });
    }
  };

  useEffect(() => {
    const matchedItem = returnCounts.find(item => item?.status === status);

    if (!matchedItem) return;

    setActiveCardId(matchedItem.id);
    if (status == 'scheduled_for_return') {
      dispatch({
        type: 'SET_SCHEDULED_RETURN_FILTER',
        payload:
          'awaiting confirmation,awaiting route,routed,confirmed,on hold,subcontracted',
      });
    }
    if (status == 'return_completed') {
      dispatch({
        type: 'SET_RETURN_COMPLETED_FILTER',
        payload: 'complete',
      });
    }
    dispatch({ type: 'SET_PAGE', payload: 1 });
  }, []);

  return (
    <div>
      {' '}
      <OrderStatusWrapper>
        <StyledListCover className="listAlignment styleCovered">
          {returnCounts?.map(item => (
            <CountItem
              key={item.id}
              countDetails={item}
              //@ts-ignore
              isActive={item.id === activeCardId}
              onClick={() => handleCardClick(item)}
            />
          ))}
        </StyledListCover>
      </OrderStatusWrapper>
    </div>
  );
};
const OrderStatusWrapper = styled.div`
  margin-bottom: 30px;
  @media ${device.smallScreen} {
    padding: 0 0px;
  }
`;

const StyledListCover = styled.ul`
  margin: 0;
  padding: 0;
  list-style: none;
  box-sizing: border-box;
  display: flex;
  gap: 25px;
  /* aligns-items: center; */
  margin-top: -40px;
  padding: 0 20px;
  flex-wrap: wrap;
`;
export default ReturnStatus;
