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

function DeliveryDate() {
  const [orderDetails, setOrderDetails] = useOrderDetails();
  const [prevOrderDetails] = usePrevOrderDetails();
  const [orderStatus] = useStatusDetails();
  const [isClientPortal] = useClientPortal();
  const routedStatus = orderStatus?.[0]?.routed;
  const isOrderOnHold = orderDetails?.status === 'OO';

  const actionDate = orderDetails?.action_date
    ? new Date(orderDetails?.action_date)
    : null;

  const onChange: DatePickerProps['onChange'] = (date, _dateString) => {
    const selectedDate = date?.format('YYYY-MM-DDTHH:mm:ss');
    if (
      selectedDate !== undefined &&
      prevOrderDetails.action_date !== undefined
    ) {
      if (
        new Date(selectedDate).toLocaleDateString() ===
        new Date(prevOrderDetails.action_date!).toLocaleDateString()
      ) {
        setOrderDetails(prev => {
          return {
            ...prev,
            action_date: prevOrderDetails.action_date,
          };
        });
      } else {
        setOrderDetails(prev => {
          return {
            ...prev,
            action_date: selectedDate,
          };
        });
      }
    } else {
      setOrderDetails(prev => {
        return {
          ...prev,
          action_date: null,
        };
      });
    }
  };
  return (
    <MainContainer>
      <Label label="Delivery Date" />
      <DatePicker
        onChange={onChange}
        value={actionDate === null ? actionDate : dayjs(actionDate)}
        format="DD/MM/YY"
        disabledDate={current => current && current < dayjs().startOf('day')}
        allowClear={false}
        disabled={
          isClientPortal
            ? true
            : routedStatus ||
              orderStatus[0]?.confirmed === true ||
              isOrderOnHold
        }
      />
    </MainContainer>
  );
}

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

export default DeliveryDate;
