import React, { useEffect } from 'react';
import AddResources from './actions/add-resources';
import styled from 'styled-components';
import {
  useCurrentAction,
  useOrderAlertsData,
  useOrderDetails,
  useOrderId,
  usePrevOrderDetails,
  useProductDetails,
  useProductDetailsCopy,
  useStatusDetails,
} from '../store';
import SplitOrder from './actions/split-order';
import LogServiceRefusal from './actions/log-service-refusal';
import CancelOrder from './actions/cancel-order';
import ConfirmOrder from './actions/confirm-order';
import SendSmsModal from './actions/send-sms/SendSmsModal';
import SendEmailModal from './actions/send-email/SendEmailModal';
import ChangeCustomerAccModal from './actions/change-customer-account/ChangeCustomerAccModal';
import HoldOrderModal from './actions/hold-order/HoldOrderModal';
import UnholdOrder from './actions/unhold-order/UnholdOrder';
import ViewReminderModal from '../view-reminder/ViewReminder';
// import OrderLock from './actions/order-lock';
import ViewFlag from '../flags-action-modal/index';
import ReleaseOrder from './actions/release-order/ReleaseOrder';
import ClearBookingStatus from './actions/clear-booking-status/ClearBookingStatus';
import UncancelOrder from './actions/uncancel-order/UncancelOrder';
import RemoveFromRoute from './actions/remove-from-route/RemoveFromRoute';
import { useAxios } from '@bjsdistribution/dms-component-library';
import { ApiResponse, OrdersType } from '../types';
import { useLoading } from '../../order-daily-overview/store/store';
import { useReminderNotiData, useTasksData } from './store';
import ChargeLog from './actions/charge-log';
import ReminderModal from './actions/create-task-reminder';
import TaskModal from './actions/create-task-reminder/TaskModal';

function OrderActions() {
  const [currentAction, setCurrentAction] = useCurrentAction();
  const [orderId] = useOrderId();
  const [, setOrderDetails] = useOrderDetails();
  const [, setPrevOrderDetails] = usePrevOrderDetails();
  const [, setOrderStatus] = useStatusDetails();
  const [, setOrderAlertsData] = useOrderAlertsData();
  const [, setProductDetails] = useProductDetails();
  const [, setProductDetailsCopy] = useProductDetailsCopy();
  const [, setLoading] = useLoading();
  const [, setTasksData] = useTasksData();
  const [, setReminderNotifyData] = useReminderNotiData();

  // call orders api

  const { fetchData: callOrdersApi, loading, data: fetchedData } = useAxios<{
    data: OrdersType[];
  }>({
    endpoint: `/orders/${orderId}`,
    method: 'GET',
  });

  useEffect(() => {
    setLoading(loading);
    if (fetchedData && fetchedData?.data) {
      const requiredData = fetchedData?.data;
      setOrderDetails(requiredData[0]);
      setPrevOrderDetails(requiredData[0]);
      setCurrentAction(undefined);
    }
    if (
      (fetchedData && fetchedData?.data === null) ||
      fetchedData?.data?.length === 0
    ) {
      setCurrentAction(undefined);
    }
  }, [loading]);

  // orders api ends

  // call order products api start

  const {
    data: productsData,
    loading: orderProductsLoading,
    fetchData: callOrderProductsApi,
  } = useAxios<{
    data: ApiResponse[];
  }>({
    endpoint: `/order/order_products/${orderId}`,
    method: 'GET',
  });

  useEffect(() => {
    if (productsData && productsData?.data?.length > 0) {
      setProductDetails(productsData?.data);
      setProductDetailsCopy(productsData?.data);
    } else {
      setProductDetails(null);
      setProductDetailsCopy(null);
    }
  }, [orderProductsLoading]);

  // call order products api end

  // call alerts api

  const {
    data: alertsData,
    fetchData: callOrderAlertsApi,
    loading: alertsApiLoading,
  } = useAxios<{
    data: ApiResponse[];
  }>({
    endpoint: `v1/orders/alerts/?order_id=${orderId}`,
    method: 'GET',
  });

  useEffect(() => {
    if (alertsData && alertsData?.data) {
      setOrderAlertsData(alertsData?.data);
    }
  }, [alertsApiLoading]);

  // alerts api ends

  // call live status api

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

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

  // Call Task Get Api
  const {
    fetchData: callUnresolvedTaskApi,
    data: fetchedUnresolvedData,
    loading: unresolvedLoading,
  } = useAxios<{
    data: ApiResponse[];
  }>({
    endpoint: `/v1/task/`,
    method: 'GET',
    pagination: { is_pagination: false },
    filters: [{ field: 'order_id', op: '=', value: orderId }],
  });

  useEffect(() => {
    if (fetchedUnresolvedData && fetchedUnresolvedData?.data) {
      setTasksData(fetchedUnresolvedData?.data);
    }
  }, [unresolvedLoading]);

  // Task Api Ends

  // reminder api starts here

  //reminder get
  const {
    data: fetchedReminderData,
    loading: reminderLoading,
    fetchData: callReminderApi,
  } = useAxios<{
    data: ApiResponse[];
  }>({
    endpoint: `/v1/task/reminder/get/`,
    method: 'GET',
    pagination: { is_pagination: false },
    filters: [{ field: 'order_id', op: '=', value: orderId }],
  });

  useEffect(() => {
    if (fetchedReminderData && fetchedReminderData?.data) {
      setReminderNotifyData(fetchedReminderData?.data);
      const filteredReminders = fetchedReminderData?.data?.filter(
        (reminder: any) => reminder?.status === false
      );

      const filteredOverDueReminders = fetchedReminderData?.data?.filter(
        (reminder: any) =>
          reminder?.status === false &&
          new Date(reminder?.due_datetime).getTime() < new Date().getTime()
      );

      // Store them correctly in localStorage
      localStorage.setItem(
        'filteredRemindersCount',
        JSON.stringify(filteredReminders?.length)
      );
      localStorage.setItem(
        'filteredOverDueReminders',
        JSON.stringify(filteredOverDueReminders?.length)
      );
    }
  }, [reminderLoading]);

  const renderContent = () => {
    switch (currentAction) {
      case 'add-resources':
        return <AddResources />;
      case 'split-order':
        return <SplitOrder />;
      case 'release-order':
        return <ReleaseOrder />;
      // case 'unrelease-order':
      //   return <UnreleaseOrder />;
      case 'log-service-refusal':
        return <LogServiceRefusal callOrdersApi={callOrdersApi} />;
      case 'cancel-order':
        return (
          <CancelOrder
            callOrdersApi={callOrdersApi}
            callOrderStatusApi={fetchStatusData}
            callOrderAlertsApi={callOrderAlertsApi}
            callOrderProductsApi={callOrderProductsApi}
          />
        );
      case 'uncancel-order':
        return (
          <UncancelOrder
            callOrdersApi={callOrdersApi}
            callOrderStatusApi={fetchStatusData}
            callOrderAlertsApi={callOrderAlertsApi}
            callOrderProductsApi={callOrderProductsApi}
          />
        );
      case 'confirm-order':
        return <ConfirmOrder callOrderAlertsApi={callOrderAlertsApi} />;
      case 'send-sms':
        return <SendSmsModal />;
      case 'send-email':
        return <SendEmailModal />;
      case 'change-customer-account':
        return <ChangeCustomerAccModal callOrdersApi={callOrdersApi} />;

      case 'hold-order':
        return (
          <HoldOrderModal
            callOrdersApi={callOrdersApi}
            callOrderAlertsApi={callOrderAlertsApi}
            callOrderStatusApi={fetchStatusData}
            callUnresolvedTaskApi={callUnresolvedTaskApi}
          />
        );
      case 'create-reminder':
        return (
          <ReminderModal
            callUnresolvedTaskApi={callUnresolvedTaskApi}
            callReminderApi={callReminderApi}
          />
        );
      case 'create-task':
        return (
          <TaskModal
            callUnresolvedTaskApi={callUnresolvedTaskApi}
            callReminderApi={callReminderApi}
          />
        );
      case 'charge-log':
        return <ChargeLog />;
      case 'unhold-order':
        return (
          <UnholdOrder
            callOrdersApi={callOrdersApi}
            callOrderAlertsApi={callOrderAlertsApi}
            callUnresolvedTaskApi={callUnresolvedTaskApi}
            callOrderStatusApi={fetchStatusData}
          />
        );
      case 'view-reminder':
        return <ViewReminderModal callReminderApi={callReminderApi} />;
      // case 'order-lock':
      //   return <OrderLock />;
      case 'view-flag':
        return <ViewFlag />;
      case 'clear-date':
        return <ClearBookingStatus callOrderAlertsApi={callOrderAlertsApi} />;
      case 'remove-from-route':
        return <RemoveFromRoute callOrderAlertsApi={callOrderAlertsApi} />;
      default:
        return null;
    }
  };
  return <Container>{renderContent()}</Container>;
}

const Container = styled.div``;

export default OrderActions;
