import React from 'react';
import styled from 'styled-components';
import { Label } from '@bjsdistribution/dms-component-library';
import { useOrderDetails, usePrevOrderDetails } from '../../../store';
import { DatePicker, DatePickerProps } from 'antd';
import dayjs from 'dayjs';

function ScheduleAfter() {
  const [orderDetails, setOrderDetails] = useOrderDetails();
  const [prevOrderDetails] = usePrevOrderDetails();
  const scheduleDate = orderDetails?.schedule_after
    ? new Date(orderDetails?.schedule_after)
    : null;

  const onChange: DatePickerProps['onChange'] = (date, _dateString) => {
    const selectedDate = date?.format('YYYY-MM-DDTHH:mm:ss');
    if (
      selectedDate !== undefined &&
      prevOrderDetails.schedule_after !== undefined
    ) {
      if (
        new Date(selectedDate).toLocaleDateString() ===
        new Date(prevOrderDetails.schedule_after!).toLocaleDateString()
      ) {
        setOrderDetails(prev => {
          return {
            ...prev,
            schedule_after: prevOrderDetails.schedule_after,
          };
        });
      } else {
        setOrderDetails(prev => {
          return {
            ...prev,
            schedule_after: selectedDate,
          };
        });
      }
    } else {
      setOrderDetails(prev => {
        return {
          ...prev,
          schedule_after: null,
        };
      });
    }
  };

  return (
    <MainContainer>
      <Label label="Schedule After" />
      <DatePicker
        onChange={onChange}
        value={scheduleDate === null ? scheduleDate : dayjs(scheduleDate)}
        format="DD/MM/YY"
        disabledDate={current => current && current < dayjs().startOf('day')}
        allowClear={false}
      />
    </MainContainer>
  );
}

const MainContainer = styled.div`
  display: flex;
  flex-direction: column;
  gap: 6px;
  flex: 1;
`;

export default ScheduleAfter;
