import React, { useState, useMemo, useEffect } from "react";
import { useLocation, useNavigate, Link, useParams } from "react-router-dom";
import { SelectedProduct } from "../../services/types";
import { Area, Package } from "../../services/product/type";
import { useMutation, useQuery } from "@tanstack/react-query";
import { DataCacheKey, staleTime } from "../../global/constants";
import { useAppDispatch, useAppSelector } from "../../hooks/useRedux";
import { startLoading, stopLoading } from "../../features/loading/loadingSlice";
import { productApi } from "../../apis/productApi";
import { openPopup } from "../../features/popup/popupSlice";
import {
  formatCurrency,
  formatNumber,
  getWithExpiry,
} from "../../logic/loigicUtils";
import ProductInfoModal from "../../components/ProductInfoModal";
import PackageOverview from "./components/PackageOverview";
import ProductCard from "../../components/ProductCard";
import { useTranslation } from "react-i18next";
import { get } from "http";

const ProductDetailView: React.FC = () => {
  const location = useLocation();
  const navigate = useNavigate();
  const dispatch = useAppDispatch();
  const { t } = useTranslation();
  // let area = location.state as Area;
  const areas = getWithExpiry<Area[]>("areas");
  const { id } = useParams<{ id: string }>();
  const loading = useAppSelector((state) => state.loading);
  const [selectedDays, setSelectedDays] = useState<number>(null);
  const [selectedData, setSelectedData] = useState<string>("Unlimited");
  const [daysOptions, setDaysOptions] = useState<number[]>([]);
  const [dataOptions, setDataOptions] = useState<string[]>([]);
  const [daysActiveOptions, setDaysActiveOptions] = useState<number[]>([]);
  const [dataActiveOptions, setDataActiveOptions] = useState<string[]>([]);
  const [relatedAreas, setRelatedAreas] = useState<Area[]>([]);
  const [prices, setPrices] = useState<{
    original: string;
    final: string;
    discountPercent: string;
  }>({
    original: "0.00",
    final: "0.00",
    discountPercent: "0",
  });
  const [simType, setSimType] = useState<"eSIM" | "Physical">("eSIM");
  const [quantity, setQuantity] = useState<number>(1);
  const [packages, setPackages] = useState<Package[]>([]);
  const [area, setArea] = useState<Area | null>(null);

  const [selectedPackage, setSelectedPackage] = useState<Package | null>(null);

  useEffect(() => {
    console.log("ProductDetailView loaded with id:", id);
    if (areas && areas.length > 0) {
      const areaTmp = areas.find((a) => a.id.toString() === id.toString());
      setArea(areaTmp);
      getProductMutation.mutate();
      getRelatedAreaMutation.mutate();
      console.log("Set area from cache:", areaTmp);
    }
  }, [id]);

  const getProductMutation = useMutation({
    mutationFn: async () => {
      dispatch(startLoading({}));
      const res = await productApi.loadPackage({
        areaId: area?.id,
        dataType: "-1",
      });
      return res;
    },
    onSuccess: (data) => {
      dispatch(stopLoading());
      console.log("Get package response data:", data);
      if (data && data.errorCode === "0") {
        const packages = data.data as Package[];
        setPackages(packages);
      } else {
        console.error("Get package failed, no token received");
      }
    },
    onError: (error: any) => {
      dispatch(stopLoading());
      console.error("Get package error:", error.response.data);
    },
  });

  const getRelatedAreaMutation = useMutation({
    mutationFn: async () => {
      dispatch(startLoading({}));
      const res = await productApi.loadRelatedArea({
        areaId: id,
      });
      return res;
    },
    onSuccess: (data) => {
      dispatch(stopLoading());
      console.log("Get package response data:", data);
      if (data && data.errorCode === "0") {
        const areas = data.data as Area[];
        setRelatedAreas(areas);
      } else {
        console.error("Get package failed, no token received");
      }
    },
    onError: (error: any) => {
      dispatch(stopLoading());
      console.error("Get package error:", error.response.data);
    },
  });

  const convertPackageToSelectedProduct = (packg: Package) => {
    return packg.title;
  };

  const options = useMemo(() => {
    console.log("Calculating options from loadPackage");

    const daysSet = new Set<number>();
    const dataSet = new Set<string>();

    packages.forEach((p) => {
      daysSet.add(p.dayDuration);
      dataSet.add(convertPackageToSelectedProduct(p));
    });

    const daysArray = Array.from(daysSet).sort((a, b) => a - b);

    // const dataArray = Array.from(dataSet).sort((a, b) => {
    //   if (a === "Unlimited") return 1;
    //   if (b === "Unlimited") return -1;
    //   return parseInt(a) - parseInt(b);
    // });

    return {
      daysArray,
      dataArray: Array.from(dataSet),
    };
  }, [packages]);

  useEffect(() => {
    setDaysOptions(options.daysArray);
    setDataOptions(options.dataArray);
    handleSelectDay(options.daysArray[0]);
    handleSelectData(options.dataArray[0]);
    // setSelectedPackage(packages.length > 0 ? packages[0] : null);
    // console.log("Set package successful", packages.length, selectedPackage);
  }, [options]);

  useEffect(() => {
    getPrices();
  }, [selectedDays, selectedData]);

  const handleSelectDay = (day: number) => {
    // filter data options based on selected day if needed
    const dataSet = new Set<string>();
    packages.forEach((p) => {
      if (p.dayDuration === day) {
        dataSet.add(convertPackageToSelectedProduct(p));
      }
    });
    setSelectedDays(day);
    setSelectedData(
      dataSet.has(selectedData) ? selectedData : Array.from(dataSet)[0],
    );
    setDataActiveOptions(Array.from(dataSet));
    setSelectedPackage(
      packages.find(
        (p) =>
          p.dayDuration === selectedDays &&
          convertPackageToSelectedProduct(p) === selectedData,
      ),
    );
  };

  const handleSelectData = (data: string) => {
    // filter day options based on selected data if needed
    const daysSet = new Set<number>();
    packages.forEach((p) => {
      if (convertPackageToSelectedProduct(p) === data) {
        daysSet.add(p.dayDuration);
      }
    });
    setSelectedData(data);
    setSelectedDays(
      daysSet.has(selectedDays) ? selectedDays : Array.from(daysSet)[0],
    );
    setDaysActiveOptions(Array.from(daysSet));
    setSelectedPackage(
      packages.find(
        (p) =>
          p.dayDuration === selectedDays &&
          convertPackageToSelectedProduct(p) === selectedData,
      ),
    );
  };

  const getPrices = (quantityParam?: number) => {
    const quantityToUse =
      quantityParam !== undefined ? quantityParam : quantity;
    // find package based on selectedDays and selectedData
    let selectedPackageTmp = packages.find(
      (p) =>
        p.dayDuration === selectedDays &&
        convertPackageToSelectedProduct(p) === selectedData,
    );
    if (!selectedPackageTmp) {
      // console.log(
      //   "No package found for the selected options " +
      //     selectedDays +
      //     " days and " +
      //     selectedData +
      //     " data"
      // );
      return {
        original: "0.00",
        final: "0.00",
        discountPercent: "0",
      };
    }
    console.log(
      "Selected package: ",
      selectedPackageTmp + " quantity " + quantityToUse,
    );
    setPrices({
      original: quantityToUse * selectedPackageTmp.displayPrice,
      final: quantityToUse * selectedPackageTmp.sellPrice,
      discountPercent: selectedPackageTmp.discountPercent,
    });
    setSelectedPackage(selectedPackageTmp);
  };

  const handleQuantityChange = (change: number) => {
    const newQuantity = Math.max(1, quantity + change);
    setQuantity(newQuantity);
    console.log("Selected quantity: ", newQuantity);
    getPrices(newQuantity);
  };

  const handleBuyNow = async () => {
    // Logic for custom order or standard buy
    console.log("Buy now clicked");
    const selectedPackage = packages.find(
      (p) =>
        p.dayDuration === selectedDays &&
        convertPackageToSelectedProduct(p) === selectedData,
    );
    if (!selectedPackage) {
      alert("Please select a valid package");
      return;
    }
    // call logic to proceed to checkout
    const res = await productApi.checkout({
      packgId: selectedPackage.id,
      quantity: quantity,
    });
    if (res && res.errorCode === "0") {
      console.log("Checkout details loaded:", res.data);
      // navigate to checkout with selected options
      navigate("/checkout", {
        state: {
          area: area,
          package: selectedPackage,
          quantity: quantity,
          simType: simType,
          checkoutDetails: res.data,
        },
      });
    } else {
      console.error("Failed to load checkout details:", res.message);
      dispatch(
        openPopup({
          isSuccess: false,
          title: "Checkout Error",
          message: res.message || "Failed to proceed to checkout.",
          buttonText: "Close",
        }),
      );
    }
  };

  if (!id || !area) {
    return (
      <div className="min-h-screen flex items-center justify-center">
        <div className="text-center">
          <p className="text-xl font-bold mb-4">{t("productDetailsMissing")}</p>
          <Link to="/buy-sim" className="text-[#EE0434] font-bold underline">
            {t("goToShop")}
          </Link>
        </div>
      </div>
    );
  }

  return (
    <div className="bg-white min-h-screen pb-20">
      <div className="max-w-7xl mx-auto px-4 py-4 md:py-6">
        <nav className="flex items-center space-x-2 text-xs md:text-sm text-slate-500">
          <Link
            to="/"
            className="hover:text-[#EE0434] transition-colors text-[18px]"
          >
            {t("home")}
          </Link>
          <svg
            className="w-3 h-3"
            fill="none"
            stroke="currentColor"
            viewBox="0 0 24 24"
          >
            <path
              d="M9 5l7 7-7 7"
              strokeWidth={2.5}
              strokeLinecap="round"
              strokeLinejoin="round"
            />
          </svg>
          <span className="text-slate-900 font-bold text-[18px]">
            {area?.areaName1}
          </span>
        </nav>
      </div>

      <div className="max-w-7xl mx-auto px-4 grid grid-cols-1 lg:grid-cols-12 gap-6 lg:gap-12">
        <div className="lg:col-span-5 space-y-4 md:space-y-6">
          <div className="relative h-48 md:h-auto aspect-[3/4] rounded-[24px] md:rounded-[32px] overflow-hidden shadow-2xl group w-full">
            <img
              src={area?.imgUrl}
              alt={area?.areaName1}
              className="w-full h-full object-cover transition-transform duration-700 group-hover:scale-110"
            />
            <div className="absolute top-4 left-4 md:top-6 md:left-6 flex items-start space-x-3 md:space-x-4">
              <div className="w-10 h-10 md:w-16 md:h-16 rounded-full overflow-hidden border-2 border-white/50 shadow-lg">
                <img
                  src={`${area?.iconUrl}`}
                  alt={area?.areaName1}
                  className="w-full h-full object-cover scale-150"
                />
              </div>
              <div className="text-white">
                <h1 className="text-2xl md:text-4xl font-black drop-shadow-md">
                  SIM {area?.areaName1}
                </h1>
                <p className="text-sm md:text-lg font-bold text-white/90">
                  {t("verified")}:{" "}
                  <span className="text-[#EE0434]">{t("highSpeed")}</span>
                </p>
              </div>
            </div>
          </div>

          {/* Product Information Card */}
          <PackageOverview packageInfo={selectedPackage} />
        </div>

        <div className="lg:col-span-7 space-y-5 md:space-y-10 pt-2 md:pt-4">
          <div className="space-y-2 md:space-y-4">
            <h3 className="text-lg md:text-xl font-black text-slate-900 tracking-tight">
              {t("numberOfDays")}
            </h3>
            <div className="flex flex-wrap gap-2 md:gap-3">
              {daysOptions.map((day) => (
                <button
                  key={day}
                  onClick={() =>
                    // daysActiveOptions.includes(day) &&
                    handleSelectDay(day)
                  }
                  className={`min-w-[50px] md:min-w-[70px] h-10 md:h-14 rounded-xl md:rounded-2xl font-bold text-base md:text-xl transition-all border-2 ${
                    selectedDays === day
                      ? "border-[#EE0434] text-white bg-[#EE0434] shadow-md"
                      : daysActiveOptions.includes(day)
                        ? "border-[#ffffff] text-black bg-[#ffffff] shadow-md"
                        : "border-slate-100 text-slate-300"
                  }`}
                >
                  {day}
                </button>
              ))}
            </div>
          </div>

          <div className="space-y-2 md:space-y-4">
            <h3 className="text-lg md:text-xl font-black text-slate-900 tracking-tight">
              Data
            </h3>
            <div className="grid grid-cols-3 md:grid-cols-4 gap-2 md:gap-3">
              {dataOptions.map((data) => (
                <button
                  key={data}
                  onClick={() =>
                    // dataActiveOptions.includes(data) &&
                    handleSelectData(data)
                  }
                  className={`h-10 md:h-14 rounded-xl md:rounded-2xl font-bold text-sm md:text-xl transition-all border-2 ${
                    selectedData === data
                      ? "border-[#EE0434] text-white bg-[#EE0434] shadow-md"
                      : dataActiveOptions.includes(data)
                        ? "border-[#ffffff] text-black bg-[#ffffff] shadow-md"
                        : "border-slate-100 text-slate-300"
                  }`}
                >
                  {data === "0" ? "Unlimited" : data}
                </button>
              ))}
            </div>
          </div>

          <div className="grid grid-cols-2 gap-2 md:gap-4">
            <div className="space-y-2 md:space-y-4">
              <h3 className="text-lg md:text-xl font-black text-slate-900 tracking-tight">
                {t("simType")}
              </h3>
              <div className="flex p-1 bg-slate-50 rounded-2xl border border-slate-100">
                <button
                  onClick={() => setSimType("eSIM")}
                  className={`flex-1 py-3 md:py-4 rounded-xl font-black text-sm md:text-2xl transition-all ${
                    simType === "eSIM"
                      ? "bg-[#EE0434] text-white shadow-lg"
                      : "text-slate-300"
                  }`}
                >
                  eSIM
                </button>
                {/* <button
                  onClick={() => setSimType("Physical")}
                  className={`flex-1 py-3 md:py-4 rounded-xl font-black text-sm md:text-2xl transition-all ${
                    simType === "Physical"
                      ? "bg-[#EE0434] text-white shadow-lg"
                      : "text-slate-300"
                  }`}
                >
                  Physical SIM
                </button> */}
              </div>
            </div>
            <div className="space-y-2 md:space-y-4">
              <h3 className="text-lg md:text-xl font-black text-slate-900 tracking-tight">
                {t("quantity")}
              </h3>
              <div className="flex items-center space-x-4 p-1 md:p-2 bg-slate-50 rounded-2xl border border-slate-100 h-[68px] md:h-[76px]">
                <button
                  onClick={() => handleQuantityChange(-1)}
                  className="w-12 h-full bg-white rounded-xl shadow-sm text-slate-600 font-bold text-2xl hover:bg-slate-100 transition-colors"
                >
                  -
                </button>
                <span className="flex-1 text-center font-black text-2xl text-slate-900">
                  {quantity}
                </span>
                <button
                  onClick={() => handleQuantityChange(1)}
                  className="w-12 h-full bg-white rounded-xl shadow-sm text-slate-600 font-bold text-2xl hover:bg-slate-100 transition-colors"
                >
                  +
                </button>
              </div>
            </div>
          </div>

          <div className="hidden md:block bg-red-50/50 border border-[#EE0434]/20 rounded-[24px] md:rounded-[40px] p-6 md:p-10 space-y-6">
            <div className="flex justify-between items-end">
              <div className="flex items-center space-x-2">
                <span className="text-[#EE0434] font-black text-lg">
                  {prices.discountPercent}%
                </span>
                <span className="text-slate-300 font-bold text-xs line-through">
                  {formatCurrency(prices.original, area?.curency)}
                </span>
              </div>
              <span className="text-[#EE0434] font-black text-2xl md:text-3xl">
                {formatCurrency(prices.final, area?.curency)}
              </span>
            </div>
            <button
              disabled={selectedData && selectedDays && loading.isSmallLoading}
              className={`w-full py-4 md:py-5 rounded-2xl font-black text-xl md:text-2xl shadow-lg transition-all flex items-center justify-center space-x-3 ${
                selectedData && selectedDays && !loading.isSmallLoading
                  ? "bg-[#EE0434] text-white hover:scale-[1.01] active:scale-[0.98]"
                  : "bg-slate-100 text-slate-300 cursor-not-allowed"
              }`}
              onClick={handleBuyNow}
            >
              {loading.isSmallLoading && (
                <div className="w-5 h-5 border-3 border-white/30 border-t-red-500 rounded-full animate-spin"></div>
              )}
              <span>{t("buyNow")}</span>
            </button>
          </div>

          {/* Suggestions Section */}
          <div className="mt-8 md:mt-12">
            <h3 className="text-xl md:text-2xl font-black text-slate-900 mb-4 md:mb-6">
              {t("suggestionsEsim")} {area.areaName1}:
            </h3>
            <div className="grid grid-cols-2 gap-2 md:gap-4">
              {relatedAreas.map((item) => (
                <ProductCard
                  key={item.id}
                  p={item}
                  onClick={() => {
                    navigate(`/product-detail/${item.id}`, {
                      state: {
                        ...item,
                      },
                    });
                    window.scrollTo({ top: 0, behavior: "smooth" });
                  }}
                />
              ))}
            </div>
          </div>
        </div>
      </div>
      {/* Mobile Sticky Bottom Bar */}
      <div className="md:hidden fixed bottom-0 left-0 right-0 bg-white border-t border-slate-100 p-4 pb-8 shadow-[0_-10px_40px_-15px_rgba(0,0,0,0.1)] z-50 flex items-center justify-between gap-4">
        <div className="flex flex-col">
          <div className="flex items-center space-x-2 mb-1">
            <span className="bg-red-100 text-[#EE0434] px-2 py-0.5 rounded text-xs font-black">
              {prices.discountPercent}%
            </span>
            <span className="text-slate-400 line-through font-bold text-sm">
              {formatCurrency(prices.original, area?.curency)}
            </span>
          </div>
          <span className="text-3xl font-black text-[#EE0434] leading-none">
            {formatCurrency(prices.final, area?.curency)}
          </span>
        </div>
        <button
          onClick={handleBuyNow}
          className="flex-1 bg-[#EE0434] text-white py-3.5 rounded-2xl font-black text-lg shadow-lg shadow-red-200"
        >
          {t("buyNow")}
        </button>
      </div>
    </div>
  );
};

export default ProductDetailView;
