import React, { useEffect } from 'react';
import 'react-datepicker/dist/react-datepicker.css';
import { HeaderWrapper, StyledFlex } from './RouterHeaderStyle';
import HeaderTitle from './title/HeaderTitle';
import Breadcrumb from './breadCrumb/BreadCrumb';
import styled from 'styled-components';
import dayjs from 'dayjs';
import { DatePicker, DatePickerProps } from 'antd';
import {
  useAtom,
  useClientPortal,
  useEndDate,
  useStartDate,
} from '../../../store';
import { filtersReducerReturnAtom } from '../../return-after-table/table-filters/ReturnFilterStore';
import ReturnSearchBar from '../../../client-portal/ReturnSearchBar';
import { useParams } from 'react-router-dom';
import ReturnAfterSearchBar from '../../../client-portal/ReturnAfterSearchBar';

interface RouterHeaderProps {
  breadcrumbTitle?: string;
  breadcrumbSubtitle?: string;
  breadcrumbSubPart?: string;
  showDateFilter?: boolean;
}

const RouterHeader: React.FC<RouterHeaderProps> = ({
  breadcrumbTitle = 'Clients >', // Default value
  breadcrumbSubtitle = ' Return', // Default value
  breadcrumbSubPart, // Optional
}) => {
  const [clientPortal] = useClientPortal();
  const [, dispatch] = useAtom(filtersReducerReturnAtom);
  //CP
  const [startDate, setStartDate] = useStartDate();
  const [endDate, setEndDate] = useEndDate();
  const { status } = useParams();

  useEffect(() => {
    const storedDates = JSON.parse(localStorage.getItem('returnDate') || '{}');
    const initialStart = storedDates?.startDate
      ? dayjs(storedDates.startDate)
      : null;
    const initialEnd = storedDates?.endDate ? dayjs(storedDates.endDate) : null;

    if (initialStart) setStartDate(initialStart);
    if (initialEnd) setEndDate(initialEnd);
  }, []);

  useEffect(() => {
    if (clientPortal) {
      const formattedStart = startDate?.format('YYYY-MM-DD');
      const formattedEnd = endDate ? endDate?.format('YYYY-MM-DD') : null;

      const payload = {
        startDate: formattedStart,
        endDate: formattedEnd,
      };
      localStorage.setItem('returnDate', JSON.stringify(payload));
      if (formattedStart || formattedEnd) {
        dispatch({
          type: 'SET_CP_DATE_FILTER',
          payload,
        });
      }
    }
  }, [startDate, endDate]);

  const handleStartDateChange: DatePickerProps['onChange'] = date => {
    setStartDate(date ?? dayjs());
  };

  const handleEndDateChange: DatePickerProps['onChange'] = date => {
    setEndDate(date);
  };
  return (
    <>
      <HeaderWrapper className="headerWrap">
        <StyledFlex>
          <div>
            <HeaderTitle title={'Return'} />
            <Breadcrumb
              title={breadcrumbTitle}
              subtitle={breadcrumbSubtitle}
              subPart={breadcrumbSubPart}
            />
          </div>
        </StyledFlex>

        {clientPortal && status === 'outstanding_return' && <ReturnSearchBar />}

        {clientPortal &&
          (status === 'scheduled_for_return' ||
            status === 'return_completed') && <ReturnAfterSearchBar />}

        {clientPortal && (
          <DatePickerWrap>
            <DatePicker
              value={startDate ? dayjs(startDate) : null}
              onChange={handleStartDateChange}
              format={'MMMM D, YYYY'}
              allowClear={false}
              disabledDate={current =>
                !!endDate && current.isAfter(dayjs(endDate), 'day')
              }
            />
            <DatePicker
              value={endDate ? dayjs(endDate) : null}
              onChange={handleEndDateChange}
              format={'MMMM D, YYYY'}
              disabledDate={current =>
                !!startDate && current.isBefore(dayjs(startDate), 'day')
              }
            />
          </DatePickerWrap>
        )}
      </HeaderWrapper>
    </>
  );
};
export const DatePickerWrap = styled.div`
  display: flex;
  padding-right: 10px;
  padding-left: 7px;
  justify-content: space-between;
  align-items: center;
  align-self: stretch;
  border-radius: 20px;
  border: 1px solid #e0e2e7;
  background: var(--Neutral-White, #fff);
  box-shadow: 0px 1px 2px 0px rgba(16, 24, 40, 0.05);
  min-width: 22vw;
  height: 35px;
  input[type='text'] {
    border-radius: 20px;
    background: var(--Flowkit-White, #fff);
    border: none;
    color: #6a7378;
    font-size: 13px;
    font-weight: 400;
    line-height: 18px;
    padding: 8px 0;
    padding-left: 10px;
    &:focus-visible {
      outline: none;
    }
  }

  .ant-picker-outlined {
    border-style: none !important;
  }

  .ant-picker-focused {
    box-shadow: none;
  }

  /* .ant-picker {
    .ant-picker-input {
      width: 150px;
    }
  } */
  .ant-btn {
    background-color: #3348ff !important;
  }
`;
export default RouterHeader;
