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

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

function UncancelOrder(props: IProps) {
  const [orderId] = useOrderId();
  const [, setCurrentAction] = useCurrentAction();

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

  const [orderStaticData] = useOrderStaticData();
  const [unCancelReason, setUncancelReason] = useState<string | undefined>(
    undefined
  );
  const [unCancelNotes, setUncancelNotes] = useState<string>('');
  const [customerInfo] = useCustomerInfo();
  const [
    cancelOrderProducts,
    setCancelOrderProducts,
  ] = useCancelOrderProducts();
  const [orderProductDetails] = useProductDetails();
  const infoText = `${customerInfo?.recipient_name}, ${customerInfo?.postcode}`;

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

  const { fetchData: performUnCancelAction } = useAxios<{
    data: ApiResponse[];
  }>({
    endpoint: `v1/orders/uncancel/?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,
              previous_product_type: product?.previous_order_product_type,
            };
          })
        : [];
    setCancelOrderProducts(modifiedReceivedProducts);
  }, [orderProductDetails]);

  const onChange = (event: any) => {
    setUncancelNotes(event.target.value);
  };

  const onChangeUnCancelReason = (value: string) => {
    setUncancelReason(value);
  };

  const onSubmit = 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 = {
      uncancelled_reason: unCancelReason,
      uncancelled_notes: unCancelNotes,
      products: productsPayload,
    };

    if (orderId) {
      const response = (await performUnCancelAction({
        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 =
    unCancelReason !== undefined && unCancelNotes?.length > 0;

  return (
    <OrderActionModal
      headerTitle="Un-Cancel order"
      onCloseHeader={onClose}
      onSubmit={onSubmit}
      showAdditionalInfo
      infoText={infoText}
      submitBtnTitle="Save Details"
      isSubmitDisabled={!showSubmitBtn}
    >
      <MainContainer>
        <Container>
          <OrderActionsDropdown
            required
            label="Un-cancel Reason"
            placeholder="Select un-cancel Reason"
            options={unCancelReasonOptions || []}
            onSelect={onChangeUnCancelReason}
            value={unCancelReason}
            className="uncancelReasonDropdown"
          />
          <HoldRow>
            <div style={{ display: 'flex', flexDirection: 'row' }}>
              <Label>Un-cancel Note</Label>{' '}
              <RequiredAsterisk>*</RequiredAsterisk>
            </div>
            <CustomTextArea rows={5} onChange={onChange} />
          </HoldRow>
        </Container>
        <UnCancelOrderTable />
      </MainContainer>
    </OrderActionModal>
  );
}

const RequiredAsterisk = styled.span`
  color: red;
  margin-left: 2px;
  font-size: x-small;
`;

const Container = styled.div`
  display: flex;
  justify-content: space-between;
  padding: 15px;
  gap: 30px;
  border-radius: 16px;
  border: 1px solid#edebe8;
  background: #f8fafc;

  .uncancelReasonDropdown {
    flex: 1;
  }
`;

const MainContainer = styled.div`
  display: flex;
  flex-direction: column;
  padding: 20px;
  gap: 10px;
`;

const CustomTextArea = styled(TextArea)`
  width: 346px;
`;

export default UncancelOrder;
