import React, { useEffect, useState } from 'react';
import {
  AntSelect,
  Label,
  useAxios,
} from '@bjsdistribution/dms-component-library';
import {
  useCurrentAction,
  useCustomerInfo,
  useOrderId,
  useOrderStaticData,
} from '../../../store';
import OrderActionModal from '../../../../../common/modals/order-action-modal/OrderActionModal';
import {
  HoldContentContainer,
  HoldDatePickerWrap,
  HoldRow,
  SplitText,
} from '../modalstyle';
import { DatePicker, DatePickerProps, notification } from 'antd';
import dayjs from 'dayjs';
import { ApiResponse } from '../../../types';
import { useClientPortal } from '../../../../store';

interface IProps {
  callOrderAlertsApi: any;
  callOrdersApi?: any;
  callOrderStatusApi: any;
  callUnresolvedTaskApi?: any;
}

function HoldOrderModal(props: IProps) {
  const [orderId] = useOrderId();
  const [, setCurrentAction] = useCurrentAction();
  const [orderStaticData] = useOrderStaticData();
  const [selectedDate, setDate] = useState<Date | string | null>(null);
  const [holdReason, setHoldReason] = useState<string | undefined>(undefined);
  const [customerInfo] = useCustomerInfo();
  const [isClientPortal] = useClientPortal();
  const infoText = `${customerInfo?.recipient_name}, ${customerInfo?.postcode}`;

  const onHoldReasonOptions = orderStaticData?.onhold_reasons?.map(
    (item: any) => {
      return {
        label: item?.reason,
        value: item?.reason,
      };
    }
  );

  const dynamicUrl = selectedDate
    ? `orders/${orderId}/hold/?hold_reason=${holdReason}&hold_until=${selectedDate}`
    : `orders/${orderId}/hold/?hold_reason=${holdReason}
`;

  const { fetchData: callOnHoldApi, error } = useAxios<{
    data: ApiResponse[];
  }>({
    endpoint: dynamicUrl,
    method: 'POST',
  });

  const onClose = () => {
    setCurrentAction(undefined);
  };

  const onChangeHold = (value: string) => {
    setHoldReason(value);
  };

  const handleDateChange: DatePickerProps['onChange'] = (date, _dateString) => {
    const newDate = date?.format('YYYY-MM-DDTHH:mm:ss');
    if (newDate !== undefined) {
      setDate(newDate);
    } else {
      setDate(null);
    }
  };

  const onSubmitHold = async () => {
    if (orderId) {
      const response = (await callOnHoldApi()) as {
        code: number | null;
        error?: string | null | undefined;
        [key: string]: any;
      };
      if (response?.code === 200) {
        notification.success({
          message: 'Success',
          description: `${response.message}`,
        });
        // call orders api to update status
        if (isClientPortal) {
          await props?.callUnresolvedTaskApi();
        }
        await props?.callOrderAlertsApi();
        await props?.callOrderStatusApi();
        await props?.callOrdersApi();
      }
      if (response?.code !== 200) {
        notification.error({
          message: 'Error',
          description: `${response.error}`,
        });
        setCurrentAction(undefined);
      }
    }
  };

  useEffect(() => {
    //@ts-ignore
    if (error !== null && error?.code !== 200) {
      console.log('entered');
      notification.error({
        //@ts-ignore
        message: `${error?.error}`,
        description: (
          //@ts-ignore
          <span dangerouslySetInnerHTML={{ __html: error?.message }} />
        ),
      });
      setCurrentAction(undefined);
    }
  }, [error]);

  const showSubmitBtn = holdReason !== undefined;

  return (
    <OrderActionModal
      minWidth="24vw"
      headerTitle="Hold order"
      onCloseHeader={onClose}
      onSubmit={onSubmitHold}
      showAdditionalInfo
      infoText={infoText}
      submitBtnTitle="Save Details"
      isSubmitDisabled={!showSubmitBtn}
    >
      <HoldContentContainer>
        <SplitText>
          <HoldRow>
            <Label label="Hold Until (leave blank for indefinite)" />
            <HoldDatePickerWrap>
              <DatePicker
                needConfirm
                format={'MMMM D, YYYY'}
                onChange={handleDateChange}
                value={
                  selectedDate === null ? selectedDate : dayjs(selectedDate)
                }
                disabledDate={current => {
                  return current && current < dayjs().startOf('day');
                }}
              />
            </HoldDatePickerWrap>
          </HoldRow>

          <HoldRow>
            <Label label="Hold Reason" required />
            <AntSelect
              options={onHoldReasonOptions || []}
              placeholder="Select Hold Reason"
              onChange={onChangeHold}
              disabled={false}
              style={{ width: '346px', height: 40 }}
              showSearch={true}
              popupClassName={'dropDownStyle'}
              selectWrapperClass={'rounded'}
              defaultValue={holdReason}
            />
          </HoldRow>
        </SplitText>
      </HoldContentContainer>
    </OrderActionModal>
  );
}

export default HoldOrderModal;
