import React, { useState } from 'react';
import OrderActionModal from '../../../../../common/modals/order-action-modal/OrderActionModal';
import styled from 'styled-components';
import DeliveryPoint from './DeliveryPoint';
import OrderServices from './OrderServices';
import Notes from './Notes';
import {
  useCurrentAction,
  useCustomerInfo,
  useOrderDetails,
} from '../../../store';
import { useAxios } from '@bjsdistribution/dms-component-library';
import { ApiResponse } from '../../../types';
import { notification } from 'antd';

function LogServiceRefusal(props: any) {
  const [, setCurrentAction] = useCurrentAction();
  // Local States for handling service refusal
  const [refusedReason, setRefusedReason] = useState<string>('');
  const [refusedServices, setRefusedServices] = useState<string[]>([]);
  const [refusedDelPointService, setRefusedDelPointService] = useState<any>('');
  const [customerInfo] = useCustomerInfo();
  const [orderDetails] = useOrderDetails();
  const infoText = `${customerInfo?.recipient_name}, ${customerInfo?.postcode}`;

  const { fetchData: callLogRefusalApi } = useAxios<{
    data: ApiResponse[];
  }>({
    endpoint: `/v1/orders/log-refusal/`,
    method: 'POST',
  });

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

  const onSubmit = async () => {
    const allServices =
      refusedDelPointService?.length > 0
        ? [...refusedServices, refusedDelPointService]
        : refusedServices;
    const finalPayload = {
      order_id: orderDetails?.id,
      route_id: orderDetails?.order_routes?.route_id,
      refused_reason: refusedReason,
      service_name: allServices,
    };
    try {
      let response = (await callLogRefusalApi({
        payload: finalPayload,
      })) as {
        code: number | null;
        error?: string | null | undefined;
        [key: string]: any;
      };
      if (response.code == 200) {
        notification.success({
          message: 'Success',
          description: `${response?.message}`,
        });
        props?.callOrdersApi();
      } else {
        notification.error({
          message: 'Error',
          description: `${response?.error}`,
        });
        onClose();
      }
    } catch (error) {}
  };

  const disableSubmitBtn =
    refusedReason?.length === 0 ||
    (refusedServices?.length === 0 && refusedDelPointService?.length === 0);

  return (
    <OrderActionModal
      headerTitle="Service Refusal"
      showAdditionalInfo
      infoText={infoText}
      submitBtnTitle="Log Refusal"
      onCloseHeader={onClose}
      onSubmit={onSubmit}
      isSubmitDisabled={disableSubmitBtn}
    >
      <ContentContainer>
        <Left>
          <DeliveryPoint
            refusedDelPointService={refusedDelPointService}
            setRefusedDelPointService={setRefusedDelPointService}
          />
          <OrderServices
            refusedServices={refusedServices}
            setRefusedServices={setRefusedServices}
          />
        </Left>
        <Right>
          <Notes
            refusedReason={refusedReason}
            setRefusedReason={setRefusedReason}
          />
        </Right>
      </ContentContainer>
    </OrderActionModal>
  );
}

const ContentContainer = styled.div`
  display: flex;
  padding: 0px 15px;
  align-items: flex-start;
  gap: 10px;
  align-self: stretch;
`;

const Left = styled.div`
  display: flex;
  padding: 15px 12px;
  flex-direction: column;
  justify-content: center;
  align-items: flex-start;
  gap: 15px;
  flex: 1 0 0;
  border-radius: 15px;
  background: #f8fafc;
`;

const Right = styled(Left)``;

export default LogServiceRefusal;
