/* eslint-disable @typescript-eslint/no-explicit-any */
import Cards from "./Containers/Cards";
import Orders from "./Containers/Cards/Orders";
import { useState, useCallback } from "react";
import { useRouter } from "next/navigation";
import { toast } from "react-toastify";
import { getOrderHistroy } from "../../../Api/OrderApi";

export default function DashbaordIndex() {
  const router = useRouter();
  const [orderId, setOrderId] = useState("");
  const [isLoading, setIsLoading] = useState(false);
  const [isTracking, setIsTracking] = useState(false);
  const storedUser = localStorage.getItem("ALL_DATA");
  const allData = storedUser ? JSON.parse(storedUser)?.data : null;
  const [orderCardDetails, setOrderCardDetails] = useState({});
  const handleOrderTrack = useCallback(
    async (e: React.FormEvent) => {
      e.preventDefault();

      // Prevent empty submissions
      if (!orderId.trim()) {
        toast.warning("Please enter an order ID");
        return;
      }

      // Prevent duplicate submissions
      if (isLoading) {
        return;
      }

      setIsLoading(true);
      setIsTracking(true);

      let response: any;
      try {
        response = await getOrderHistroy(orderId);
        if (response?.id) {
          router.push(`/order-tracking?id=${response.id}`);
        } else {
          toast.warning("Order not found", {
            position: "top-right",
            autoClose: 3000,
          });
        }
      } catch (error: any) {
        console.error("Error tracking order:", error);
        toast.error(
          error?.response?.data?.message ||
            "Failed to track order. Please try again later."
        );
      } finally {
        setIsLoading(false);
        if (!response?.data?.id) {
          setIsTracking(false);
        }
      }
    },
    [orderId, isLoading, router]
  );

  return (
    <>
      <style>
        {`
          .innerPageWrap .innerHeader.h-auto { height: auto !important; }
          .header-logo-app .header-title { margin-top: 8px!important; }
          .header-logo-app .header-icon-1 { margin-top: 8px!important; }
          .input-style.mb-2 { margin-bottom: 10px !important; }
        `}
      </style>
      {allData?.email && (
        <div className="page-content innerPageWrap homePageWrap">
          <div className="header header-fixed header-logo-app innerHeader shadow-0l h-auto d-none d-lg-block">
            <a href="#" className="header-title header-subtitle">
              Dashboard
            </a>
            <a
              href="index.php"
              data-back-button=""
              className="header-icon header-icon-1"
            >
              <i className="fas fa-home"></i>
            </a>
            <div className="row mb-0 mx-0">
              <div className="col-12 col-lg-4 col-md-6 mx-auto pe-3">
                <form
                  onSubmit={handleOrderTrack}
                  className="d-float-center flex-md-nowrap"
                >
                  <label className="w-20 color-black">Track Order</label>
                  <div className="input-style has-borders has-icon validate-field mt-2 mb-2 w-100">
                    <i className="fa fa-search"></i>
                    <input
                      type="text"
                      className="form-control validate-name h-auto bg-light2 border-color73"
                      id="form1"
                      placeholder="Enter order or package ID to track"
                      value={orderId}
                      onChange={(e) => setOrderId(e.target.value)}
                      disabled={isLoading}
                    />
                  </div>
                </form>
              </div>
            </div>
          </div>

          <div className="row mb-0 mt-3 mx-0 d-lg-none">
            <div className="col-12 col-lg-4 mx-auto">
              <form onSubmit={handleOrderTrack}>
                <div className="input-style has-borders has-icon validate-field mb-4">
                  <i className="fa fa-search"></i>
                  <input
                    type="text"
                    className="form-control validate-name border-color73"
                    id="form1"
                    placeholder="Enter order or package ID to track"
                    value={orderId}
                    onChange={(e) => setOrderId(e.target.value)}
                    disabled={isLoading}
                  />
                </div>
              </form>
            </div>
          </div>
          {!isTracking && (
            <>
              <Cards setOrderCardDetails={setOrderCardDetails} />
              <Orders orderCardDetails={orderCardDetails} />
            </>
          )}
        </div>
      )}
    </>
  );
}
