import styled from 'styled-components';
import React, { useEffect, useState } from 'react';
import OrderActionModal from '../../../../../common/modals/order-action-modal/OrderActionModal';
import ReturnAction from './ReturnAction';
import ReturnReason from './ReturnReason';
import {
  useCancelOrderProducts,
  useCurrentAction,
  useCustomerInfo,
  useOrderId,
  useOrderStaticData,
  useProductDetails,
} from '../../../store';
import OrderActionsDropdown from '../../Dropdown';
import { TextArea, useAxios } from '@bjsdistribution/dms-component-library';
import { ApiResponse, CancelOrderProductsType } from '../../../types';
import { notification } from 'antd';
import CancelOrderTable from './CancelOrderTable';

interface IProps {
  callOrdersApi: any;
  callOrderStatusApi: any;
  callOrderAlertsApi: any;
  callOrderProductsApi: any;
}

function CancelOrder(props: IProps) {
  const [orderId] = useOrderId();
  const [, setCurrentAction] = useCurrentAction();
  const [orderProductDetails] = useProductDetails();
  const [
    cancelOrderProducts,
    setCancelOrderProducts,
  ] = useCancelOrderProducts();
  const [customerInfo] = useCustomerInfo();
  const infoText = `${customerInfo?.recipient_name}, ${customerInfo?.postcode}`;

  const [orderStaticData] = useOrderStaticData();

  const [cancelReason, setCancelReason] = useState<string | undefined>(
    undefined
  );

  const [cancelNotes, setCancelNotes] = useState<string>('');

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

  const { fetchData: callCancelApi } = useAxios<{
    data: ApiResponse[];
  }>({
    endpoint: `v1/orders/cancel/?order_id=${orderId}`,
    method: 'POST',
  });

  useEffect(() => {
    const receivedProducts = orderProductDetails?.filter(
      (product: any) =>
        product?.status_value === 'received' &&
        product?.order_product_type?.type !== 'return'
    );
    const modifiedReceivedProducts =
      receivedProducts?.length > 0
        ? receivedProducts?.map((product: any) => {
            return {
              order_product_id: product?.id,
              action: '',
              return_action: '',
              return_reason: '',
              code: product?.code,
              description: product?.description,
              sku: product?.sku,
              product_type: product?.order_product_type?.type,
            };
          })
        : [];
    setCancelOrderProducts(modifiedReceivedProducts);
  }, [orderProductDetails]);

  const onClose = () => {
    setCurrentAction(undefined);
    setCancelOrderProducts([]);
  };

  const onSelectCancelReason = (value: string) => {
    setCancelReason(value);
  };

  const onChangeNotes = (event: any) => {
    setCancelNotes(event.target.value);
  };

  const onSubmitCancel = async () => {
    const productsPayload = cancelOrderProducts?.map(
      (product: CancelOrderProductsType) => {
        if (product?.action === 'deliver') {
          return {
            order_product_id: product?.order_product_id,
            action: product?.action,
          };
        }
        return {
          order_product_id: product?.order_product_id,
          action: product?.action,
          return_action: product?.return_action,
          return_reason: product?.return_reason,
        };
      }
    );

    // VALIDATIONS START

    const productsPayloadActions = productsPayload?.map(
      (product: CancelOrderProductsType) => {
        if (product?.action !== '') {
          return true;
        }
        return false;
      }
    );

    if (productsPayloadActions?.includes(false)) {
      notification.error({
        message: 'Error',
        description: `please fill product status field`,
      });
      return;
    }

    const productsPayloadValidate = productsPayload?.map(
      (product: CancelOrderProductsType) => {
        if (product?.action === 'return') {
          return product?.return_action !== '' && product?.return_reason !== '';
        }
        return true;
      }
    );

    if (productsPayloadValidate?.includes(false)) {
      notification.error({
        message: 'Error',
        description: `please fill all the mandatory fields`,
      });
      return;
    }

    // VALIDATIONS END

    const apiPayload = {
      cancelled_reason: cancelReason,
      cancelled_notes: cancelNotes,
      products: productsPayload,
    };

    if (orderId) {
      const response = (await callCancelApi({
        payload: apiPayload,
      })) 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
        await props?.callOrderProductsApi();
        await props?.callOrderAlertsApi();
        await props?.callOrderStatusApi();
        await props?.callOrdersApi();
      }
      if (response?.code !== 200) {
        notification.error({
          message: 'Error',
          description: `${response.error}`,
        });
        setCurrentAction(undefined);
      }
    }
  };

  const showSubmitBtn = cancelReason !== undefined && cancelNotes?.length > 0;

  return (
    <OrderActionModal
      headerTitle="Cancel Order"
      showAdditionalInfo
      infoText={infoText}
      onCloseHeader={onClose}
      onSubmit={onSubmitCancel}
      submitBtnTitle="Save Details"
      isSubmitDisabled={!showSubmitBtn}
    >
      <ContentContainer>
        <Top>
          <TopLeft>
            <OrderActionsDropdown
              required
              label="Cancellation Reason"
              placeholder="Select Cancellation Reason"
              options={cancelReasonOptions || []}
              onSelect={onSelectCancelReason}
              value={cancelReason}
            />
            <Wrapper>
              <ReturnAction />
              <ReturnReason />
            </Wrapper>
          </TopLeft>
          <TopRight>
            <Container>
              <div style={{ display: 'flex', flexDirection: 'row' }}>
                <Label>Cancellation Note</Label>{' '}
                <RequiredAsterisk>*</RequiredAsterisk>
              </div>
              <TArea
                rows={5}
                onChange={onChangeNotes}
                value={cancelNotes}
                placeholder="Reason for Cancel  Order"
              />
            </Container>
          </TopRight>
        </Top>
        <Bottom>
          <CancelOrderTable />
        </Bottom>
      </ContentContainer>
    </OrderActionModal>
  );
}
const RequiredAsterisk = styled.span`
  color: red;
  margin-left: 2px;
  font-size: x-small;
`;

const TArea = styled(TextArea)`
  resize: none;
`;

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

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

const Wrapper = styled.div`
  display: flex;
  gap: 15px;
  width: 100%;
  > div {
    width: 50%;
  }
`;

const TopLeft = styled.div`
  display: flex;
  flex-direction: column;
  gap: 15px;
  width: 50%;
`;

const TopRight = styled.div`
  width: 50%;
`;

const Top = styled.div`
  width: 100%;
  border-radius: 16px;
  border: 1px solid #edebe8;
  background: #f8fafc;
  display: flex;
  padding: 15px;
  align-items: flex-start;
  gap: 30px;
  align-self: stretch;
`;

const Bottom = styled.div``;

const ContentContainer = styled.div`
  display: flex;
  padding: 15px;
  align-items: flex-start;
  flex-direction: column;
  width: 100%;
`;

export default CancelOrder;
