import React, { useEffect, useState } from 'react';
import styled from 'styled-components';
import OrderDetails from './order-details';
import Notes from './notes';
import SystemLogs from './system-event-logs/expanded-content';
import GeneralHeader from './general-information';
import ProductsInfo from './products-info';
import OrderActions from './order-actions';
import { useApiHook, useAxios } from '@bjsdistribution/dms-component-library';
import {
  useOrderDetails,
  // useOrderStaticData,
  useStatusDetails,
  useOrderId,
  useDepotOptions,
  usePrevOrderDetails,
  useOrderProductsResources,
  useCustomerInfo,
  useLocationOptions,
  useOrderProductSystemLogs,
  useGsitCUstomerId,
  useCUstomerId,
  useRouteId,
  useGsitOrderId,
  useOrderProductId,
  useLiveRecalling,
  useGlobalStateHitOrder,
  useAtom,
  usegetClientData,
} from './store';
import { OrdersType } from './types';
import { useLocation } from 'react-router-dom';
import { notification } from 'antd';
import DetailsFilters from './details-filters/DetailsFilters';
import { useSubContracterData } from '../store';
import Notification from './notification';
import Order from './order-resources/expanded-content';
import { setResourcesCall, useAllOrderStatus } from './order-actions/store';
import { ClientType } from '../order-daily-overview/common/interface';

interface ApiResponse {
  message: string;
  code: number;
  error: string | null;
  error_traceback: string | null;
  data: [];
  setShouldPerformAction: boolean;
}

function OrderView() {
  notification.config({
    top: 150,
  });
  const [orderId, setOrderId] = useOrderId();
  const [gsitOrderId, setGsitOrderId] = useGsitOrderId();
  // For API Call
  const [orderDetails, setOrderDetails] = useOrderDetails();
  const [, setPrevOrderDetails] = usePrevOrderDetails();
  const [, setLoading] = useState<boolean>(false);
  const [, setOrderStatus] = useStatusDetails();
  const [, setDepotOptions] = useDepotOptions();
  const [, setCustomerInfo] = useCustomerInfo();
  const [, setLocationOptions] = useLocationOptions();
  const [orderResources, setOrderResources] = useOrderProductsResources();
  const [GsitCUstomerId, setGsitCUstomerId] = useGsitCUstomerId();
  const [, setOrderProductId] = useOrderProductId();
  const [, setCUstomerId] = useCUstomerId();
  const [, setRouteId] = useRouteId();
  const [liveRecalling] = useLiveRecalling();
  const [, setSubContracterData] = useSubContracterData();
  const [recallOrders] = useGlobalStateHitOrder();
  const [, setStatusVal] = useAllOrderStatus();
  const order_id = orderDetails?.id;
  const [getResources] = useAtom(setResourcesCall);
  const [, setClientData] = usegetClientData();

  useEffect(() => {
    setStatusVal(orderDetails?.status_value);
  }, [orderDetails?.status_value]);

  //get system event logs
  const {
    data: fetchedSystemLogsData,
    fetchData: callSystemLogsAPI,
    loading: logsLoading,
  } = useAxios<{
    data: any[];
  }>({
    endpoint: `/events/get/event/`,
    method: 'GET',
    pagination: { page: 1, per_page: 100 },
    filters: [
      {
        field: 'order_id',
        op: '=',
        value: `${order_id}`,
      },
    ],
  });

  // query param
  const location = useLocation();
  const [filters, setFilters] = useState<
    Array<{ field: string; op: string; value: string | null }>
  >([]);

  // for third party apps
  const {
    data: fetchedDataExternal,
    loading: loadingExternal,
    setShouldPerformAction: setShouldPerformExternal,
  } = useApiHook<{
    data: any[];
  }>({
    endpoint: `orders/`,
    method: 'GET',
    filters: filters,
    performAction: false,
  });

  useEffect(() => {
    const searchParams = new URLSearchParams(location.search);
    if (searchParams?.toString()) {
      const dynamicFilters: Array<{
        field: string;
        op: string;
        value: string | null;
      }> = [];
      searchParams?.forEach((value, key) => {
        if (key === 'order') {
          dynamicFilters.push({
            field: 'gsit_order_id',
            op: '=',
            value: value,
          });
        } else {
          dynamicFilters.push({
            field: key,
            op: '=',
            value: value,
          });
        }
      });
      setFilters(dynamicFilters);
      if (filters) {
        setShouldPerformExternal(true);
        setOrderId(fetchedDataExternal?.data[0]?.id);
      }
    } else {
      const paths = location.pathname.split('/');
      setOrderId(paths[paths?.length - 1]);
    }
  }, [location.search, loadingExternal]);

  const {
    data: fetchedData,
    loading,
    setShouldPerformAction: orderUpdate,
  } = useApiHook<{
    data: OrdersType[];
  }>({
    endpoint: `orders/${orderId}`,
    method: 'GET',
    performAction: false,
  });

  //Order status api
  const {
    data: fetchedStatusData,
    loading: statusDataLoading,
    setShouldPerformAction: setLivePerformAction,
  } = useApiHook<{
    data: ApiResponse[];
  }>({
    endpoint: `/orders/get_live_status/${orderId}`,
    method: 'GET',
    performAction: false,
  });
  const { data: fetchedDepotData, loading: depotDataLoading } = useApiHook<{
    data: ApiResponse[];
  }>({
    endpoint: `/depot/`,
    method: 'GET',
    filters: [{ field: 'visibility', op: '=', value: true }],
    //@ts-ignore
    pagination: { is_pagination: false },
  });
  useEffect(() => {
    if (orderId) {
      orderUpdate(recallOrders);
      liveRecalling ? setLivePerformAction(false) : setLivePerformAction(true);
    }
  }, [orderId, liveRecalling, recallOrders]);

  useEffect(() => {
    setLoading(loading);
    if (fetchedData && fetchedData.data) {
      const requiredData = fetchedData?.data;
      setOrderDetails(requiredData[0]);
      //@ts-ignore
      setCUstomerId(requiredData[0]?.customer_id);
      setRouteId(requiredData[0]?.order_routes?.route_id);
      //@ts-ignore
      setGsitOrderId(requiredData[0]?.gsit_order_id);
      //@ts-ignore
      setOrderProductId(requiredData[0]?.id);
      setCustomerInfo({
        recipient_name:
          requiredData[0]?.order_recipient?.recipient_name ?? null,
        postcode: requiredData[0]?.order_recipient?.postcode ?? null,
      });

      setPrevOrderDetails(requiredData[0]);

      //dbSync Api call
      if (fetchedData?.data[0]?.gsit_order_id) {
        localStorage.setItem(
          'dbSyncAPICall',
          JSON.stringify({
            status: true,
            gsit_orderId: fetchedData?.data[0]?.gsit_order_id,
          })
        );
      } else {
        localStorage.setItem('dbSyncAPICall', JSON.stringify({}));
      }
    }
    return () => {
      localStorage.removeItem('dbSyncAPICall');
    };
  }, [loading]);

  useEffect(() => {
    setLoading(statusDataLoading);
    if (fetchedStatusData && fetchedStatusData.data) {
      const requiredData = fetchedStatusData?.data;
      if (requiredData) {
        setOrderStatus(requiredData);
      } else {
        // setOrderStatus(null);
      }
    }
  }, [statusDataLoading, fetchedStatusData]);

  const {
    fetchData: callCLientApi,
    loading: clientLoading,
    data: clientData,
  } = useAxios<{
    data: ClientType[];
  }>({
    endpoint: `/v1/client/list`,
    method: 'GET',
  });

  useEffect(() => {
    if (orderId) {
      callCLientApi();
    }
  }, [orderId]);

  useEffect(() => {
    if (clientData && clientData?.data) {
      const res = clientData?.data;
      setClientData(res);
    }
  }, [clientLoading]);

  useEffect(() => {
    setLoading(depotDataLoading);
    if (fetchedDepotData && fetchedDepotData.data) {
      const requiredData = fetchedDepotData?.data;
      if (requiredData.length > 0) {
        const options = requiredData?.map((x: any) => {
          return {
            label: x.name,
            value: x.id,
          };
        });
        setDepotOptions(options);
      } else {
        setDepotOptions([]);
      }
    }
  }, [depotDataLoading]);

  // Order resources
  const {
    data: fetchedResourcesData,
    setShouldPerformAction: setActions,
  } = useApiHook<{
    data: ApiResponse[];
  }>({
    endpoint: `/orders/${orderId}/order_resources/`,
    method: 'GET',
    performAction: false,
  });

  useEffect(() => {
    if (orderId) {
      if (getResources) {
        setActions(false);
        setTimeout(() => {
          setActions(true);
        }, 200);
      } else {
        setActions(true);
      }
    }
  }, [orderId, setActions, getResources]);

  useEffect(() => {
    if (orderId) {
      setActions(true);
    }
  }, [orderId, setActions]);

  useEffect(() => {
    if (orderId) {
      setOrderResources(fetchedResourcesData);
    }
  }, [fetchedResourcesData, orderResources, setOrderResources]);

  // // Toolbox resources
  // const {
  //   data: fetchedToolboxData,
  //   setShouldPerformAction: setAction,
  // } = useApiHook<{
  //   data: ApiResponse[];
  // }>({
  //   endpoint: `/orders/${orderId}/toolbox_resources/`,
  //   method: 'GET',
  //   performAction: false,
  // });

  // useEffect(() => {
  //   if (orderId) {
  //     setAction(true);
  //   }
  // }, [orderId, setAction]);

  // useEffect(() => {
  //   if (orderId) {
  //     setOrderToolbox(fetchedToolboxData);
  //   }
  // }, [fetchedToolboxData, orderToolbox, setOrderToolbox]);

  useEffect(() => {
    return () => {
      setGsitCUstomerId((prev: any) => ({ ...prev, id: undefined }));
    };
  }, []);

  const {
    data: fetchedLocationData,
    loading: dataLoading,
    setShouldPerformAction: shouldFetch,
  } = useApiHook<{
    data: ApiResponse[];
  }>({
    endpoint: `/return_locations/?customer_id=${GsitCUstomerId?.id}`,
    method: 'GET',
    performAction: false,
  });

  useEffect(() => {
    if (GsitCUstomerId?.id) {
      shouldFetch(true);
    } else {
      shouldFetch(false);
    }
  }, [GsitCUstomerId]);

  useEffect(() => {
    if (fetchedLocationData && fetchedLocationData?.data) {
      const locationOptions = fetchedLocationData?.data?.map((item: any) => {
        return {
          label: item?.location_name + ', ' + item?.postcode,
          value: item?.token,
          is_default: item?.is_default === 'True' ? true : false,
        };
      });
      setLocationOptions(locationOptions);
    }
  }, [dataLoading]);
  const [, setSystemLogsEvents] = useOrderProductSystemLogs();

  useEffect(() => {
    if (fetchedSystemLogsData && fetchedSystemLogsData?.data) {
      setSystemLogsEvents(fetchedSystemLogsData?.data);
    }
  }, [logsLoading]);

  useEffect(() => {
    if (gsitOrderId) {
      callSystemLogsAPI();
    }
    return () => {
      setGsitOrderId(undefined);
    };
  }, [order_id]);

  const { data: fetchedSubcontractotData, loading: apiLoading } = useApiHook<{
    data: ApiResponse[];
  }>({
    endpoint: `/sub-contractor/sub_contractor/get/`,
    method: 'GET',
  });

  useEffect(() => {
    if (fetchedSubcontractotData && fetchedSubcontractotData?.data) {
      const formattedData = fetchedSubcontractotData?.data?.map(
        (item: any) => ({
          id: item.id,
          name: item.name,
        })
      );
      setSubContracterData(formattedData);
    }
  }, [fetchedSubcontractotData, fetchedSubcontractotData, apiLoading]);
  return (
    <MainContainer>
      <GeneralHeader />

      <DetailsFilters />
      <Notification />
      <OrderDetails />
      <ProductsInfo />
      <SplitLayout>
        <NotesContainer>
          <Notes />
        </NotesContainer>
        <TablesContainer>
          <Order />
          <SystemLogs />
        </TablesContainer>
      </SplitLayout>
      <OrderActions />
    </MainContainer>
  );
}

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

const SplitLayout = styled.div`
  display: flex;
  gap: 15px;
  @media (max-width: 1024px) {
    display: contents;
  }
`;

const NotesContainer = styled.div`
  flex: 1;
`;

const TablesContainer = styled.div`
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 15px;
`;

export default OrderView;
