import React, { useEffect, useState } from 'react';
import { AntModal, useApiHook } from '@bjsdistribution/dms-component-library';
import { useAtom } from 'jotai';
import { countReducerAtom, useDeleteProdsID, usefetchAgain } from '../store';

import DefectsModal from './DefectsModal';
import { ApiResponse } from '../types';
import CreateReturnModal from './CreateReturnModal';
import {
  useFinalPayload,
  useGroupedPayload,
  useNewReturnPayload,
  usePostLoading,
  useSelectAll,
  useSelectedConfirmLoc,
  useSelectedOrders,
} from '../../store';
import { notification } from 'antd';
import { useNavigate } from 'react-router-dom';

const ModalManager = () => {
  const [popupName, dispatch] = useAtom(countReducerAtom);
  const [selectedRows] = useDeleteProdsID();
  const [, setIsFormValid] = useState(false);
  const [newGrouped] = useFinalPayload();
  const [postLoading, SetPostLoading] = usePostLoading();
  const [, setSelectedReturnOrder] = useSelectedOrders();
  const [forDisabledCheck, setCheck] = useSelectedConfirmLoc();
  const [, setNewPayload] = useNewReturnPayload();
  const [, setGrouped] = useGroupedPayload();
  const [, setSelectAll] = useSelectAll();
  const [, setCallForFetch] = usefetchAgain();
  const navigate = useNavigate();

  const closeModal = () => {
    dispatch({ type: 'close' });
  };

  const validateForm = () => {
    return selectedRows?.length > 0;
  };

  useEffect(() => {
    setIsFormValid(validateForm());
  }, [selectedRows]);

  // Confirm return popup
  const {
    data: response,
    setShouldPerformAction,
    loading: confirmLoading,
    // error: apiError,
    setError,
  } = useApiHook<{
    data: ApiResponse[];
  }>({
    endpoint: `/v1/return/create/`,
    method: 'POST',
    body: newGrouped,
    performAction: false,
  });
  useEffect(() => {
    SetPostLoading(confirmLoading);
  }, [confirmLoading]);

  const handleConfirmReturn = () => {
    if (newGrouped?.length > 0) {
      setShouldPerformAction(true);
      setCallForFetch(true);
      SetPostLoading(confirmLoading);
    }
    dispatch({ type: 'close' });
  };

  useEffect(() => {
    // @ts-ignore
    if (response && response?.code == 500) {
      // @ts-ignore
      notification.error({
        message: 'Failure',
        // @ts-ignore
        description: `${response?.message}`,
      });
      dispatch({ type: 'close' });
      setSelectedReturnOrder([]);
      setCheck([]);
      setNewPayload([]);
      setGrouped([]);
      setSelectAll(false);
      setShouldPerformAction(false);
      setError(null);
      // @ts-ignore
    } else if (response?.code === 201 || response?.code === 200) {
      notification.success({
        message: 'Success',
        // @ts-ignore
        description: `${response?.message}`,
      });
      dispatch({ type: 'close' });
      setSelectedReturnOrder([]);
      setCheck([]);
      setNewPayload([]);
      setShouldPerformAction(false);
      setSelectAll(false);
      setError(null);

      // for local
      // navigate('/overview');

      // for dev
      navigate('/orders/view/return/overview');
    }
  }, [postLoading]);

  return (
    <>
      {popupName?.state === 'create-return' && (
        <>
          <AntModal
            openStatus={popupName?.state == 'create-return' ? true : false}
            closeModal={() => closeModal()}
            PopupHeader={{
              heading: 'CONFIRM RETURN',
              subHeading: '',
            }}
            PopupFooter={{
              btns: [
                {
                  name: 'Submit',
                  btnStyle: 'rounded',
                  onClick: handleConfirmReturn,
                  type: 'button',
                  disabled: forDisabledCheck.length === 0,
                },
              ],

              btnAlign: 'justifyEnd',
            }}
            BodyComponent={CreateReturnModal}
            width={800}
            classNameAdd={'globalPopup'}
          />
        </>
      )}

      {popupName?.state == 'defectsModal' && (
        <AntModal
          openStatus={popupName?.state == 'defectsModal' ? true : false}
          closeModal={closeModal}
          PopupHeader={{
            heading: 'DEliver - DWLK1006 - 00605',
            subHeading: 'ALtair TV stand for TVs up to 60',
          }}
          PopupFooter={{
            btns: [
              {
                name: '',
                btnStyle: '',
                type: '',
              },
            ],
            btnAlign: '',
          }}
          BodyComponent={DefectsModal}
          width={1504}
          classNameAdd={'globalPopup'}
        />
      )}
    </>
  );
};

export default ModalManager;
