import React, { useEffect } from 'react';
import OrderActionModal from '../../../../../common/modals/order-action-modal/OrderActionModal';
import styled from 'styled-components';
import CustomerInformation from './customer-info';
import ProductTable from './tables/ProductTable';
import NotesTable from './tables/NotesTable';
import SlotAndInstructions from './slot-and-instructions';
import { Alert, useAxios } from '@bjsdistribution/dms-component-library';
import { notification } from 'antd';
import {
  useCurrentAction,
  useCustomerInfo,
  useErrorConfirmOrder,
  useGlobalStateHitOrder,
  useNotificationConfirmedDate,
  useOrderDetails,
  useOrderDetailsConfirmOrder,
  useOrderId,
  usePrevOrderDetails,
  useSelectionAction,
  useStatusDetails,
} from '../../../store';

import { ApiResponse } from '../../../types';
import { compareOrderDetailsStates, filterObject } from '../../../utils';
import { format } from 'date-fns';
import { useConfirmOrderDate } from '../../store';

interface IProps {
  callOrderAlertsApi: any;
}

function ConfirmOrder(props: IProps) {
  const [, setCurrentAction] = useCurrentAction();
  const [orderDetails, setOrderDetails] = useOrderDetails();
  const [prevOrderDetails, setPrevOrderDetails] = usePrevOrderDetails();
  const [
    orderDetailsConfirmOrder,
    setOrderDetailsConfirmOrder,
  ] = useOrderDetailsConfirmOrder();
  const [customerInfo] = useCustomerInfo();
  const infoText = `${customerInfo?.recipient_name}, ${customerInfo?.postcode}`;
  const [deliveryDate, setDeliveryDate] = useConfirmOrderDate();
  const [orderId] = useOrderId();
  const [errorState] = useErrorConfirmOrder();
  const [, setRecallOrders] = useGlobalStateHitOrder();
  const [confirmedDate] = useNotificationConfirmedDate();
  const [selectedAction] = useSelectionAction();
  const [, setOrderStatus] = useStatusDetails();

  const contactHome = orderDetailsConfirmOrder?.order_recipient?.contact_home;
  const contactMobile =
    orderDetailsConfirmOrder?.order_recipient?.contact_mobile;
  const contactWork = orderDetailsConfirmOrder?.order_recipient?.contact_work;

  // update Order API
  const { fetchData: callUpdateOrderAPI } = useAxios<{
    data: ApiResponse[];
  }>({
    endpoint: `/orders/update/`,
    method: 'PUT',
  });

  // send notifications
  const { fetchData: notificationCall } = useAxios<{
    data: ApiResponse[];
  }>({
    endpoint: `orders/${orderId}/send-comms/?notification_type={Confirm - Accepted} `,
    method: 'POST',
  });

  const { fetchData: declineDate } = useAxios<{
    data: ApiResponse[];
  }>({
    endpoint: `orders/${orderId}/decline-date/?date=${confirmedDate?.previousDate}`,
    method: 'POST',
  });

  const { fetchData: confirmDeliveryDate } = useAxios<{
    data: ApiResponse[];
  }>({
    endpoint: `orders/${orderId}/confirm-date/?date=${confirmedDate?.currentDate}`,
    method: 'POST',
  });

  const { fetchData: sendComs } = useAxios<{
    data: ApiResponse[];
  }>({
    endpoint: `orders/${orderId}/send-comms/?notification_type=Precall`,
    method: 'POST',
  });

  const { fetchData: noResponseApi } = useAxios<{
    data: ApiResponse[];
  }>({
    endpoint: `orders/${orderId}/no-response-date/?date=${confirmedDate?.currentDate}`,
    method: 'POST',
  });

  const { fetchData: proposeDate } = useAxios<{
    data: ApiResponse[];
  }>({
    endpoint: `orders/${orderId}/propose-date/?date=${confirmedDate?.currentDate}`,
    method: 'POST',
  });

  //Order status api
  const {
    fetchData: fetchStatusData,
    data: statusData,
    loading: statusDataLoading,
  } = useAxios<{
    data: ApiResponse[];
  }>({
    endpoint: `/orders/get_live_status/${orderId}`,
    method: 'GET',
  });

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

  useEffect(() => {
    const clone = JSON.parse(JSON.stringify(orderDetails));
    setOrderDetailsConfirmOrder(clone);
    return () => {
      setOrderDetailsConfirmOrder(clone);
    };
  }, []);

  useEffect(() => {
    if (statusData && statusData?.data) {
      setOrderStatus(statusData?.data);
    }
  }, [statusDataLoading]);

  // THIS HAS BEEN REMOVED AS WE HAVE NEW APIS
  // const {
  //   loading: loadingForConfirm,
  //   data: response,
  //   setShouldPerformAction: setPerformAction,
  // } = useApiHook<{
  //   data: ApiResponse[];
  // }>({
  //   endpoint: `orders/${orderId}/confirm-date/?date=${deliveryDate}`,
  //   method: 'POST',
  //   performAction: false,
  // });

  function hasOnlyIdKey(obj: any) {
    return Object.keys(obj).length === 1 && obj.hasOwnProperty('id');
  }

  const executeActions = async () => {
    switch (selectedAction) {
      case 'decline_and_propose_new_date':
        // call propose date api
        if (confirmedDate?.previousDate !== null) {
          await declineDate();
        }
        await proposeDate();
        await fetchStatusData();
        break;

      case 'decline_and_confirm_new_date':
        if (confirmedDate?.previousDate !== null) {
          await declineDate();
        }
        await confirmDeliveryDate();
        await fetchStatusData();
        break;

      case 'declined_proposed_date(outstanding)':
        if (confirmedDate?.previousDate !== null) {
          await declineDate();
        }
        await fetchStatusData();
        break;

      case 'no_response_propose_new_date':
        if (confirmedDate?.previousDate !== null) {
          await declineDate();
        }
        await noResponseApi();
        await fetchStatusData();
        break;

      case 'confirmed':
        if (confirmedDate?.previousDate !== null) {
          await declineDate();
        }
        await confirmDeliveryDate();
        await fetchStatusData();
        break;

      default:
        break;
    }
  };

  const executeSendComs = async () => {
    switch (selectedAction) {
      case 'left_message':
      case 'contact_made':
      case 'no_contact':
        // await confirmDeliveryDate();
        notificationCall();
        await fetchStatusData();
        break;

      case 'precall':
        if (confirmedDate?.previousDate !== null) {
          await declineDate();
        }
        // await confirmDeliveryDate();
        sendComs();
        await fetchStatusData();
        break;
      default:
        break;
    }
  };

  const confirmOrder = async () => {
    setRecallOrders(false);

    if (
      selectedAction === 'left_message' ||
      selectedAction === 'contact_made' ||
      selectedAction === 'no_contact' ||
      selectedAction === 'precall'
    ) {
      if (
        contactHome?.length === 0 &&
        contactMobile?.length === 0 &&
        contactWork?.length === 0
      ) {
        notification.info({
          message: 'Info',
          description: 'Please add contact information',
        });
        return;
      }
      if (
        confirmedDate?.previousDate === null &&
        confirmedDate?.currentDate === null
      ) {
        notification.info({
          message: 'Info',
          description: 'Please add delivery date',
        });
        return;
      }
    }

    const keysToRemovefromOrders = [
      'order_locked',
      'order_communications',
      'updated_at',
      'updated_by',
      'stock_alias',
      'order_delivery_declined_dates',
      'order_eta_updates',
    ];

    const filteredOrderDetails = filterObject(
      orderDetailsConfirmOrder,
      keysToRemovefromOrders
    );
    const filteredPrevOrderDetails = filterObject(
      prevOrderDetails,
      keysToRemovefromOrders
    );
    const payload = compareOrderDetailsStates(
      filteredPrevOrderDetails,
      filteredOrderDetails
    );
    const notUpdateOrder = hasOnlyIdKey(payload);

    if (!notUpdateOrder) {
      const updatedPayload = {
        ...payload,
        action_date: confirmedDate?.currentDate,
      };

      const response = (await callUpdateOrderAPI({
        payload: [updatedPayload],
      })) as {
        code: number | null;
        error?: string | null | undefined;
        [key: string]: any;
      };

      if (response?.data?.length > 0) {
        const updatedOrder = response?.data[0];
        setOrderDetails(updatedOrder);
        setPrevOrderDetails(updatedOrder);
        setRecallOrders(true);
      } else {
        setOrderDetails(prevOrderDetails);
      }
    }

    // Execute actions first
    await executeActions();
    await executeSendComs();

    if (orderId && deliveryDate) {
      const formattedDate = format(new Date(deliveryDate), 'yyyy-MM-dd');
      setDeliveryDate(formattedDate);
    }
    await props?.callOrderAlertsApi();

    setCurrentAction(undefined);
  };

  // const isDifferent = () => {
  // const keysToRemovefromOrders = [
  // 'order_locked',
  // 'order_communications',
  // 'updated_at',
  // 'updated_by',
  // 'order_services',
  // ];
  // const filteredOrderDetails = filterObject(
  // orderDetailsConfirmOrder,
  // keysToRemovefromOrders
  // );
  // const filteredPrevOrderDetails = filterObject(
  // prevOrderDetails,
  // keysToRemovefromOrders
  // );
  //
  // const orderDetailsSorted = JSON.stringify(filteredOrderDetails);
  // const prevOrderDetailsSorted = JSON.stringify(filteredPrevOrderDetails);
  // const isSame = orderDetailsSorted === prevOrderDetailsSorted;
  //
  // console.log(orderDetailsSorted, 'orderDetailsSorted');
  // console.log(prevOrderDetailsSorted, 'prevOrderDetailsSorted');
  // console.log(isSame, 'isSameisSame');
  //
  // newOrderServicesSorted === prevOrderServicesSorted;
  // return !isSame;
  // };

  const errorFound = () => {
    const isError =
      errorState.emailError.length > 0 ||
      errorState.homeContactError.length > 0 ||
      errorState.workContactError.length > 0 ||
      errorState.mobileError.length > 0;
    return isError;
  };

  const disabledButton = confirmedDate?.currentDate === null;

  return (
    <OrderActionModal
      headerTitle="Confirm Order"
      minWidth="28vw"
      showAdditionalInfo
      infoText={infoText}
      onCloseHeader={onClose}
      onSubmit={confirmOrder}
      submitBtnTitle="Save Details"
      isSubmitDisabled={errorFound() && disabledButton}
    >
      <ContentContainer>
        <Alert
          description=""
          onClose={() => {}}
          type="info"
          title="There is Orders with identical postcodes that are yet to be delivered.View Orders"
          showOkButton={false}
          showCloseIcon={false}
        />
        <Wrapper>
          <CustomerInformation />
          <SlotAndInstructions />
        </Wrapper>
        <ProductTable />
        <NotesTable />
      </ContentContainer>
    </OrderActionModal>
  );
}

const Wrapper = styled.div`
  display: flex;
  gap: 10px;
`;

const ContentContainer = styled.div`
  /* display: flex; */
  padding: 15px 12px;
  flex: 1 0 0;
  border-radius: 15px;
  background: white;
  display: flex;
  flex-direction: column;
  gap: 15px;
  overflow: auto;
  min-height: 500px;
  overflow-x: hidden;
  max-height: 500px;
  scrollbar-width: thin;
`;

export default ConfirmOrder;
