/* eslint-disable @typescript-eslint/no-explicit-any */
import Image from "next/image";
import Link from "next/link";
import React from "react";
import OrderCard from "./Containers/OrderCard";
import { useSearchParams, useRouter } from "next/navigation";
import OrderFilter from "../../Modal/Filters/OrderFilter";
import Modal from "../../Modal/Modal";
import { getDashboard } from "../../../Api/CustomerApi";
import HourGlassLoader from "../../Loader/Loader";
import CommonFilter from "../../Filters/CommonFilter";
interface FormData {
  serviceTypes: any;
  orderFlowType: any;
  orderId: string;
  customerOrderId: string;
  deliveryMobile: string;
  orderStatus: any;
  packageId: string;
  noOfPackages: string;
  packageWeight: string;
  packageValue: string;
  packageStatus: any;
  blockNumber: any;
  roadNumber: any;
  buildingNumber: any;
  flatNumber: string;
}
export default function NotificationsIndex() {
  const searchParams: any = useSearchParams();
  const router = useRouter();
  const defaultTab = searchParams.get("_") || "draft";
  const [tab, setTab] = React.useState<string>(defaultTab);
  const [filterModal, setFilterModal] = React.useState<boolean>(false);
  React.useEffect(() => {
    setTab(defaultTab);
  }, [defaultTab]);
  const [filters, setFilters] = React.useState<any>({});

  // Function to check if any filters are applied
  const hasActiveFilters = () => {
    return !!(
      (filters.serviceTypes?.id && filters.serviceTypes?.id !== "") ||
      (filters.orderFlowType?.id && filters.orderFlowType?.id !== "") ||
      (filters.orderId && filters.orderId.trim() !== "") ||
      (filters.customerOrderId && filters.customerOrderId.trim() !== "") ||
      (filters.deliveryMobile && filters.deliveryMobile.trim() !== "") ||
      (filters.orderStatus?.id && filters.orderStatus?.id !== "") ||
      (filters.packageId && filters.packageId.trim() !== "") ||
      (filters.noOfPackages && filters.noOfPackages.trim() !== "") ||
      (filters.packageWeight && filters.packageWeight.trim() !== "") ||
      (filters.packageValue && filters.packageValue.trim() !== "") ||
      (filters.packageStatus?.id && filters.packageStatus?.id !== "") ||
      (filters.blockNumber && filters.blockNumber !== null) ||
      (filters.roadNumber && filters.roadNumber !== null) ||
      (filters.buildingNumber && filters.buildingNumber !== null) ||
      (filters.flatNumber && filters.flatNumber.trim() !== "")
    );
  };

  // Function to clear specific filter
  const clearFilter = (filterKey: string) => {
    setFilters((prev: any) => {
      const newFilters = { ...prev };
      delete newFilters[filterKey];
      return newFilters;
    });
  };

  // Function to clear all filters
  const clearAllFilters = () => {
    setFilters({});
  };

  const handleTab = (_tab: string) => {
    setTab(_tab || "draft");
    router.push(`/my-orders?_=${_tab || "draft"}`);
  };
  const toggleFilter = () => setFilterModal(!filterModal);
  const onSaveFilter = (filter: FormData) => {
    setFilters(filter);
    toggleFilter();
  };

  const [dashboard, setDashboard] = React.useState<any>(null);
  const [draftCount, setDraftCount] = React.useState<number>(0)
  const [isLoading, setIsLoading] = React.useState(true);
  React.useEffect(() => {
    const fetchDashboard = async () => {
      setIsLoading(true);
      try {
        const data = await getDashboard();
        setDashboard(data);
        setDraftCount(data?.draft_orders || 0)
      } catch {
        setDashboard(null);
      } finally {
        setIsLoading(false);
      }
    };
    fetchDashboard();
  }, [tab]);
  return (
    <>
      <style>
        {`
          /* Smartphones (portrait and landscape) */
          @media only screen and (min-device-width : 990px) and (max-device-width : 2000px) {
            html, body, .az-body.az-light, .az-content-dashboard-six, .az-content-body { height: 100%; }
            .draft-orders-row {
                min-height: 32rem;
            }
          }
            // .rounded-xl { border-radius: 5px !important; }
            // .orders-list .content.collapse a { color: #752f8a !important; }
            .tab-controls a ( border-left: 0 solid !important; )

            .tab-controls {
              width: 100%;
              overflow: hidden;
              overflow-x: auto;
            }
            .tab-controls a {
              width: -webkit-fill-available;
              white-space: nowrap;
              padding: 0 15px;
            }
              .oder-list-page .my-orders-row .order-list-box .card-style.order-list-heightSame { height: 213px; }
        `}
      </style>
      {isLoading && <HourGlassLoader />}
      <div className="page-content innerPageWrap ordersPageWrap oder-list-page">
        <div className="header header-fixed header-logo-app innerHeader">
          <Link href="my-orders" className="header-title header-subtitle">
            Orders
          </Link>
          <Link href="/dashboard" className="header-icon header-icon-1">
            <i className="fas fa-arrow-left" />
          </Link>
          {tab === "draft" ? (
            <a
              href="#"
              // onClick={toggleFilter}
              className="color-theme show-on-theme-light header-icon header-icon-2 font-16"
            >
              <i className="fa fa-filter-circle-dollar" />
            </a>
          ) : (
            <a
              href="#"
              onClick={toggleFilter}
              className="color-theme show-on-theme-light header-icon header-icon-2 font-16"
            >
              <i className="fa fa-filter" />
            </a>
          )}

        </div>
        <div className="innerContentWrap orders-list">
          {tab !== "draft" && hasActiveFilters() ? (
            <CommonFilter
              type="orders"
              filters={filters}
              clearFilter={clearFilter}
              clearAllFilters={clearAllFilters}
            />
          ) : (
            ""
          )}
          <div className="card card-style bg-transparent pb-0 m-0 rounded-0">
            <div className="content m-0" id="tab-group-1">
              <div
                className="tab-controls tabs-small tabs-rounded tab-controls-order-list"
                data-highlight="bg-purple"
              >
                <a
                  href="#"
                  onClick={() => handleTab("draft")}
                  data-active
                  data-bs-toggle="collapse"
                  data-bs-target="#tab-1"
                  className={`rounded-0 font-600 ${
                    tab === "draft" ? "bg-purple  no-click" : ""
                  }`}
                >
                  Draft ({ draftCount || 0})
                </a>
                <a
                  href="#"
                  onClick={() => handleTab("in_progress")}
                  data-bs-toggle="collapse"
                  data-bs-target="#tab-2"
                  className={`rounded-0 font-600 ${
                    tab === "in_progress" ? "bg-purple  no-click" : ""
                  }`}
                >
                  Inprogress ({dashboard?.in_progress_orders || 0})
                </a>
                <a
                  href="#"
                  onClick={() => handleTab("completed")}
                  data-bs-toggle="collapse"
                  data-bs-target="#tab-3"
                  className={`rounded-0 font-600 ${
                    tab === "completed" ? "bg-purple  no-click" : ""
                  }`}
                >
                  Completed ({dashboard?.delivered_orders || 0})
                </a>
                <a
                  href="#"
                  onClick={() => handleTab("cancel")}
                  data-bs-toggle="collapse"
                  data-bs-target="#tab-4"
                  className={`rounded-0 font-600 ${
                    tab === "cancel" ? "bg-purple no-click" : ""
                  }`}
                >
                  Canceled ({dashboard?.cancelled_orders || 0})
                </a>
              </div>
              {/* <div class="clearfix mb-3"></div> */}
              <div
                data-bs-parent="#tab-group-1"
                className="content draft mx-0 bg-transparent px-0 collapse show"
                id="tab-1"
              >
                <div className="row my-orders-row">
                  {/* <div class="col-lg-12 my-orders-box">
                   <h5 class="font-15 pb-1">Saved Orders</h5>
               </div> */}
                  <OrderCard
                    tab={tab}
                    edit={false}
                    filters={filters}
                    setDashboard={setDashboard}
                    dashboard={dashboard}
                  />
                  {tab === "draft" && dashboard?.draft_orders > 0 ? (
                    <div className="draft-order-btns card-bottom my-3 d-flex justify-content-between gap-2 px-0">
                      <button
                        className="btn btn-m rounded-m delybell-primary font-700 text-uppercase flex-fill text-center"
                        onClick={() => {
                          const url = `/create-order`;
                          window.location.href = url;
                        }}
                      >
                        <i className="fa fa-plus me-1" /> Add More
                      </button>
                      <button
                        className="btn btn-m rounded-m bg-green2 font-700 text-uppercase flex-fill text-center"
                        onClick={() => {
                          const url = `/create-order?_=draft`;
                          window.location.href = url;
                        }}
                      >
                        <i className="fa fa-check me-1" /> Place Order
                      </button>
                    </div>
                  ) : null}
                </div>
              </div>
              <div
                data-bs-parent="#tab-group-1"
                className="content inprogress collapse"
                id="tab-2"
              >
                <div className="row my-orders-row">
                  <div className="col-lg-3 order-list-box">
                    <div className="card card-style mb-4 mx-0">
                      <div className="content">
                        <div className="maindiv">
                          <div className="w-100">
                            <div className="card-info d-float-center justify-content-between">
                              <h6 className="font-400 font-14 mb-2 d-float-center">
                                <a className="color-blue" href="order-view.php">
                                  FMPP189153529
                                </a>
                              </h6>
                              <span className="badge delybell-blue rounded-xl font-12 px-2">
                                Pickup Scheduled
                              </span>
                            </div>
                            <div>
                              <h6 className="font-500 font-16 mb-2 d-float-center">
                                <span className="font-700 text-dark">
                                  Les Snider
                                </span>
                              </h6>
                            </div>
                            <h6 className="font-400 font-13 mb-2">
                              <span className="opacity-50">
                                <i
                                  className="fa fa-map-marker me-1"
                                  aria-hidden="true"
                                />
                                Block-567,&nbsp;Road-457,&nbsp;Flat-4758
                              </span>
                            </h6>
                            <div className="order-info-icons d-float-center justify-content-between">
                              <div className="d-float-center gap-15">
                                <p className="mb-0 font-13 font-400">
                                  <span className="badge card-status rounded-xl font-12 px-2">
                                    Next Day
                                  </span>
                                </p>
                                <div className="d-float-center box">
                                  <Image
                                    className="order-icons img-fluid"
                                    src="/images/icons/box.svg"
                                    alt="Box Icon"
                                    width={32}
                                    height={32}
                                  />{" "}
                                  <h6 className="font-13 font-400 mb-0">
                                    <span className="">2 Pkgs</span>
                                  </h6>
                                </div>
                                <div className="d-float-center weight">
                                  <Image
                                    className="order-icons img-fluid"
                                    src="/images/icons/weight.svg"
                                    alt="Weight Icon"
                                    width={32}
                                    height={32}
                                  />{" "}
                                  <h6 className="font-13 font-400 mb-0">
                                    <span className="">5 KG</span>
                                  </h6>
                                </div>
                              </div>
                              <div className="d-float-center wallet">
                                <Image
                                  className="order-icons img-fluid"
                                  src="/images/icons/wallet.svg"
                                  alt="Wallet Icon"
                                  width={32}
                                  height={32}
                                />{" "}
                                <h6 className="font-13 font-700 mb-0">
                                  <span className="color-red-dark">
                                    250.000
                                  </span>
                                </h6>
                              </div>
                            </div>
                          </div>
                        </div>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
              <div
                data-bs-parent="#tab-group-1"
                className="content completed collapse"
                id="tab-3"
              >
                <div className="col-lg-3 order-list-box">
                  <div className="card card-style mb-4 mx-0">
                    <div className="content">
                      <div className="maindiv">
                        <div className="w-100">
                          <div className="card-info d-float-center justify-content-between">
                            <h6 className="font-400 font-14 mb-2 d-float-center">
                              <a className="color-blue" href="order-view.php">
                                FMPP189153529
                              </a>
                            </h6>
                            <span className="badge bg-green2 rounded-xl font-12 px-2">
                              Cash in Hand
                            </span>
                          </div>
                          <div>
                            <h6 className="font-500 font-16 mb-2 d-float-center">
                              <span className="font-700 text-dark">
                                Les Snider
                              </span>
                            </h6>
                          </div>
                          <h6 className="font-400 font-13 mb-2">
                            <span className="opacity-50">
                              <i
                                className="fa fa-map-marker me-1"
                                aria-hidden="true"
                              />
                              Block-567,&nbsp;Road-457,&nbsp;Flat-4758
                            </span>
                          </h6>
                          <div className="order-info-icons d-float-center justify-content-between">
                            <div className="d-float-center gap-15">
                              {/* <p class="mb-0 font-13 font-400">
                                           <span class="badge card-status rounded-xl font-12 px-2">Next Day</span>
                                       </p> */}
                              <div className="d-float-center box">
                                <Image
                                  className="order-icons img-fluid"
                                  src="/images/icons/box.svg"
                                  alt="Box Icon"
                                  width={32}
                                  height={32}
                                />{" "}
                                <h6 className="font-13 font-400 mb-0">
                                  <span className="">2 Pkgs</span>
                                </h6>
                              </div>
                              <div className="d-float-center weight">
                                <Image
                                  className="order-icons img-fluid"
                                  src="/images/icons/weight.svg"
                                  alt="Weight Icon"
                                  width={32}
                                  height={32}
                                />{" "}
                                <h6 className="font-13 font-400 mb-0">
                                  <span className="">5 KG</span>
                                </h6>
                              </div>
                            </div>
                            <div className="d-float-center wallet">
                              <Image
                                className="order-icons img-fluid"
                                src="/images/icons/wallet.svg"
                                alt="Wallet Icon"
                                width={32}
                                height={32}
                              />{" "}
                              <h6 className="font-13 font-700 mb-0">
                                <span className="color-red-dark">250.000</span>
                              </h6>
                            </div>
                          </div>
                        </div>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
              <div
                data-bs-parent="#tab-group-1"
                className="content cancel collapse"
                id="tab-4"
              >
                <div className="row my-orders-row">
                  <div className="col-lg-3 order-list-box">
                    <div className="card card-style mb-4">
                      <div className="content">
                        <div className="maindiv">
                          <div className="w-100">
                            <p className="mb-1">
                              <span className="badge color-primary border border-primary rounded-xl font-12 px-2 me-1">
                                Local
                              </span>
                              <span className="badge card-status rounded-xl font-12 px-2">
                                Next Day
                              </span>
                            </p>
                            <div className="d-float-center justify-content-between">
                              <h6 className="font-500 font-14 mb-2 d-float-center">
                                <a href="order-view.php">#ORD154</a>-{" "}
                                <span className="font-700 font-15 text-dark">
                                  Les Snider
                                </span>
                              </h6>
                            </div>
                            <h6 className="font-400 font-13 opacity-50 mb-2">
                              <i className="fa fa-phone" aria-hidden="true" />{" "}
                              +973 145784212, +973 123456789
                            </h6>
                            <h6 className="font-400 font-13 opacity-50 mb-2">
                              <span className="">
                                <i
                                  className="fa fa-map-marker me-1"
                                  aria-hidden="true"
                                />
                                Block-567,&nbsp;Road-457,&nbsp;Flat-4758
                              </span>
                            </h6>
                            <div className="order-info-icons d-float-center justify-content-between">
                              <div className="d-float-center gap-15">
                                <div className="d-float-center box">
                                  <Image
                                    className="order-icons img-fluid"
                                    src="/images/icons/box.svg"
                                    alt="Box Icon"
                                    width={32}
                                    height={32}
                                  />{" "}
                                  <h6 className="font-13 font-400 mb-0">
                                    <span className="">2 Packages</span>
                                  </h6>
                                </div>
                                <div className="d-float-center weight">
                                  <Image
                                    className="order-icons img-fluid"
                                    src="/images/icons/weight.svg"
                                    alt="Weight Icon"
                                    width={32}
                                    height={32}
                                  />{" "}
                                  <h6 className="font-13 font-400 mb-0">
                                    <span className="">5 KG</span>
                                  </h6>
                                </div>
                              </div>
                              <div className="d-float-center wallet">
                                <Image
                                  className="order-icons img-fluid"
                                  src="/images/icons/wallet.svg"
                                  alt="Wallet Icon"
                                  width={32}
                                  height={32}
                                />{" "}
                                <h6 className="font-13 font-700 mb-0">
                                  <span className="color-red-dark">
                                    250.000
                                  </span>
                                </h6>
                              </div>
                            </div>
                          </div>
                        </div>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
      {filterModal && (
        <Modal
          show={filterModal}
          onHide={toggleFilter}
          header={false}
          title=""
          fullscreen={"xl"}
          centered={true}
          classname="custom-center-modal"
          position={"top"}
        >
          <OrderFilter onHide={toggleFilter} onSaveFilter={onSaveFilter} filters={filters} />
        </Modal>
      )}
    </>
  );
}
