import React from 'react';
import styled from 'styled-components';
import AllowTracking from './AllowTracking';
import { Button, useAxios } from '@bjsdistribution/dms-component-library';
import {
  useAtom,
  useOrderDetails,
  usePrevOrderDetails,
  errorAtom,
  useCustomerInfo,
  useGlobalStateHitAuditLog,
  useOrderStaticData,
  useGlobalStateHitOrder,
} from '../../../store';
// import useUpdateOrder from '../../../hooks/useUpdateOrder';
import { compareOrderDetailsStates, filterObject } from '../../../utils';
import { ApiResponse, OrderServiceType } from '../../../types';
import { notification } from 'antd';
import { useClientPortal } from '../../../../store';

function OrderDetailsFooter() {
  const [orderDetails, setOrderDetails] = useOrderDetails();
  const [prevOrderDetails, setPrevOrderDetails] = usePrevOrderDetails();
  const [, setCustomerInfo] = useCustomerInfo();
  // const updateOrder = useUpdateOrder();
  const [errorState] = useAtom(errorAtom);
  const [, setRecallAuditLog] = useGlobalStateHitAuditLog();
  const [orderStaticData] = useOrderStaticData();
  const [, setRecallOrders] = useGlobalStateHitOrder();
  const [isClientPortal] = useClientPortal();

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

  const errorFound = () => {
    const isError =
      errorState.w3wError.length > 0 ||
      errorState.emailError.length > 0 ||
      errorState.homeContactError.length > 0 ||
      errorState.workCOntanctError.length > 0 ||
      errorState.mobileError.length > 0 ||
      errorState.postCodeError.length > 0;

    return isError;
  };

  const isDifferent = () => {
    const keysToRemovefromOrders = [
      'order_locked',
      'order_communications',
      'updated_at',
      'updated_by',
      'order_services',
    ];
    const filteredOrderDetails = filterObject(
      orderDetails,
      keysToRemovefromOrders
    );
    const filteredPrevOrderDetails = filterObject(
      prevOrderDetails,
      keysToRemovefromOrders
    );

    const newOrderServices =
      orderDetails?.order_services?.length > 0 &&
      orderDetails?.order_services?.sort(
        (a: OrderServiceType, b: OrderServiceType) => a.id! - b.id!
      );

    const prevOrderServices =
      prevOrderDetails?.order_services?.length > 0 &&
      prevOrderDetails?.order_services.sort(
        (a: OrderServiceType, b: OrderServiceType) => a.id! - b.id!
      );

    const newOrderServicesSorted = JSON.stringify(newOrderServices);
    const prevOrderServicesSorted = JSON.stringify(prevOrderServices);
    const orderDetailsSorted = JSON.stringify(filteredOrderDetails);
    const prevOrderDetailsSorted = JSON.stringify(filteredPrevOrderDetails);
    const isSame =
      orderDetailsSorted === prevOrderDetailsSorted &&
      newOrderServicesSorted === prevOrderServicesSorted;
    return !isSame;
  };

  const onSave = async () => {
    setRecallAuditLog(false);
    setRecallOrders(false);
    const payload = compareOrderDetailsStates(prevOrderDetails, orderDetails);
    const clone = [...orderDetails?.order_services];

    // ASSEMBLE AND DISASSEMBLE SERVICES CHECK FOR ASSEMBLE TYPE
    const assembleOrderService = orderStaticData?.order_service_list?.find(
      (x: any) => x?.type?.toLowerCase() === 'assemble'
    );
    const disassembleOrderService = orderStaticData?.order_service_list?.find(
      (x: any) => x?.type?.toLowerCase() === 'disassemble'
    );

    const assemblyTypeService = clone?.find(
      (x: any) => x?.order_service_list_id === assembleOrderService?.id
    );

    const disassemblyTypeService = clone?.find(
      (x: any) => x?.order_service_list_id === disassembleOrderService?.id
    );

    if (
      assemblyTypeService !== undefined &&
      assemblyTypeService?.is_deleted === false &&
      (assemblyTypeService?.service_category_id === undefined ||
        assemblyTypeService?.service_category_id === null)
    ) {
      notification.info({
        message: 'Info',
        description: 'Assembly Type is required',
      });
      return;
    } else if (
      disassemblyTypeService !== undefined &&
      disassemblyTypeService?.is_deleted === false &&
      (disassemblyTypeService?.service_category_id === undefined ||
        disassemblyTypeService?.service_category_id === null)
    ) {
      notification.info({
        message: 'Info',
        description: 'Assembly Type is required',
      });
      return;
    } else {
      let response = (await callUpdateOrderAPI({
        payload: [payload],
      })) as {
        code: number | null;
        error?: string | null | undefined;
        [key: string]: any;
      };
      // const response = await updateOrder([payload]);
      setRecallOrders(true);
      if (response.code == 200 && response?.data?.length > 0) {
        notification.success({
          message: 'Success',
          description: `${response?.message}`,
        });
        setOrderDetails(response?.data[0]);
        setPrevOrderDetails(response?.data[0]);
        setCustomerInfo({
          recipient_name: response?.data[0]?.order_recipient?.recipient_name,
          postcode: response?.data[0]?.order_recipient?.postcode,
        });
        setRecallAuditLog(true);
      } else {
        setOrderDetails(prevOrderDetails);
      }
    }
  };

  return (
    <Container>
      <AllowTracking />
      <Button
        onClick={onSave}
        disabled={isClientPortal ? true : !isDifferent() || errorFound()}
      >
        Save Details
      </Button>
    </Container>
  );
}

const Container = styled.div`
  display: flex;
  justify-content: space-between;
  padding: 10px 15px;
  align-items: flex-start;
  border-top: 1px solid #edebe8;
  background: #f8fafc;
  margin: 0px -15px -15px -15px;
  border-radius: 0px 0px 8px 8px;
`;

export default OrderDetailsFooter;
