/* eslint-disable @typescript-eslint/no-explicit-any */
import React, { useEffect, useState } from "react";
import OrderCard from "./Step3/OrderCard";
import CreateOrderFooter from "./CreateOrderFooter";
import { getOrders } from "../../../../Api/OrderApi";
import HourGlassLoader from "../../../Loader/Loader";
import { useAppSelector } from "@/Redux/Hooks";
import { saveStepData } from "@/Redux/Reducers/CreateOrderSlice";
import { useDispatch } from "react-redux";
import { getFormattedAddress, handleFuturePickup } from "../../../../lib/Helper";
import { OrderFlowType } from "@/Constant/enums";

const Step3: React.FC<{
  onSave: (data: any) => void;
  step: number;
  setStep: React.Dispatch<React.SetStateAction<number>>;
  defaultOrderDetails: any;
}> = ({ step, setStep }) => {
  const dispatch = useDispatch();
  const completeOrder: any = useAppSelector((state) => state.createOrder);
  const [orders, setOrders] = useState<any[]>([]);
  const [isLoading, setIsLoading] = useState<boolean>(true);

  const fetchOrders = async () => {
    setIsLoading(true);
    try {
      const orderList = await getOrders();
      const updatedCompleteOrder: any = {
        ...completeOrder?.step3,
        draftList: orderList || [],
      };
      dispatch(saveStepData({ step: "step3", data: updatedCompleteOrder }));
      setOrders(orderList);
    } catch (error) {
      console.error("Failed to fetch orders:", error);
    } finally {
      setIsLoading(false);
    }
  };
  useEffect(() => {
    fetchOrders();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);
  const handleFuturePickupFlag = async (orderId = 0, orderData: undefined) => {
    setIsLoading(true);
    try {
      const isMarked = await handleFuturePickup(orderId, orderData);
      if (isMarked) {
        await fetchOrders();
      }
    } catch (error) {
      console.error("Error in future pickup:", error);
    } finally {
      setIsLoading(false);
    }
  };
  const handleFuturePickupConfirm = async () => {
    const _id = orders?.[0]?.id ?? null;
    if(_id) await handleFuturePickupFlag(_id, orders?.[0])
  }
  return (
    <>
      {isLoading && <HourGlassLoader />}
      <div className="scrollWrap order-list-step3 mt-0">
        <div className="mb-3 d-float-center justify-content-between">
          <h5 className="mb-0">
            {isLoading ? "Loading orders..." : `No. of Orders ${orders.length}`}
          </h5>
            <p className="mb-0">
              <span className="text-muted small mt-1">No. of future pickup: {orders.filter(order => order.isFuturePickup).length}</span>
            </p>
        </div>
        <div className="row mx-0">
          {!isLoading &&
            orders.map((order: any, idx) => (
              <OrderCard
              fetchOrders={fetchOrders}
              step={step} setStep={setStep}
                key={idx}
                orderDetail={order}
                {...order}
                address={order?.orderFlowType?.id === OrderFlowType.Return ?  getFormattedAddress(order, 'order_summary_return') :  getFormattedAddress(order, 'order_summary')}
                // address={`${order?.destination_block_details?.name || ""}, ${
                //   order?.destination_road_details?.name || ""
                // } & ${order?.destination_building_details?.name || ""}, ${
                //   order?.destinationFlatOrOfficeNumber || ""
                // }`}
                handleFuturePickupFlag={handleFuturePickupFlag}
              />
            ))}
        </div>
      </div>
      <CreateOrderFooter step={step} setStep={setStep} validation={() => {}} handleFuturePickupConfirm={handleFuturePickupConfirm} />
    </>
  );
};

export default Step3;
