import { DatePicker } from 'antd';
import React, { useEffect } from 'react';
import styled from 'styled-components';
import {
  useNotificationConfirmedDate,
  useOrderDetails,
} from '../../../../store';
import dayjs, { Dayjs } from 'dayjs';
import { isValid } from 'date-fns';

function DeliveryDate() {
  const [dateOrderDetails] = useOrderDetails();
  const [confirmedDate, setConfirmedDate] = useNotificationConfirmedDate();

  const actionDate = dateOrderDetails?.action_date
    ? dayjs(dateOrderDetails.action_date).format('YYYY-MM-DD')
    : null;

  useEffect(() => {
    if (actionDate) {
      setConfirmedDate(_prev => ({
        previousDate: actionDate,
        currentDate: actionDate,
      }));
    } else {
      setConfirmedDate({
        previousDate: null,
        currentDate: null,
      });
    }
  }, [actionDate, setConfirmedDate]);

  const handleDateChange = (date: Dayjs | null) => {
    if (date && isValid(date.toDate())) {
      const formattedDate = dayjs(date).format('YYYY-MM-DD');

      setConfirmedDate(prev => ({
        previousDate: prev?.currentDate || null,
        currentDate: formattedDate,
      }));
    }
  };

  return (
    <Container>
      <Label>Delivery Date</Label>
      <DatePicker
        onChange={handleDateChange}
        format="YYYY-MM-DD"
        value={
          confirmedDate?.currentDate
            ? dayjs(confirmedDate.currentDate)
            : actionDate
            ? dayjs(actionDate)
            : null
        }
        style={{ borderRadius: '15px', minWidth: '60px' }}
        disabledDate={current =>
          current && current.isBefore(dayjs().startOf('day'))
        }
        allowClear={false}
      />
    </Container>
  );
}

const Label = styled.label`
  color: #6a7378;
  font-family: 'Lato', sans-serif;
  font-size: 14px;
  font-weight: 500;
`;

const Container = styled.div`
  display: flex;
  flex-direction: column;
  gap: 6px;
  flex: 1;
  white-space: nowrap;
`;

export default DeliveryDate;
