import React, { useState, useEffect } from "react";
import { useAppDispatch, useAppSelector } from "../hooks/useRedux";
import { closeCompatibilityModal } from "../features/popup/popupSlice";
import { useMutation } from "@tanstack/react-query";
import { startLoading, stopLoading } from "../features/loading/loadingSlice";
import { contentApi } from "../apis/contentApi";
import { DeviceMeta } from "../services/content/types";
import { useTranslation } from "react-i18next";

const CompatibilityModal = () => {
  const popup = useAppSelector((state) => state.popup.compatibilityModal);
  const dispatch = useAppDispatch();
  const [brands, setBrands] = useState<DeviceMeta[] | []>([]);
  const [deviceList, setDeviceList] = useState<Record<string, string[]>>([]);
  const [selectedBrand, setSelectedBrand] = useState("");
  const { t } = useTranslation();

  useEffect(() => {
    getDeviceMetaMutation.mutate();
  }, []);

  const getDeviceMetaMutation = useMutation({
    mutationFn: async () => {
      dispatch(startLoading({}));
      const res = await contentApi.LoadDeviceMetaData();
      return res;
    },
    onSuccess: (data) => {
      dispatch(stopLoading());
      console.log("Get device metadata response data:", data);
      if (data && data.errorCode === "0") {
        console.log("Get device metadata successful");
        setBrands(data.data.brands || []);
        let deviceMap: Record<string, string[]> = {};
        data.data.brands.forEach((element) => {
          deviceMap[element.brand] = element.devices.map(
            (device) => device.modelName,
          );
        });

        setDeviceList(deviceMap);

        setSelectedBrand(
          data.data.brands.length > 0 ? data.data.brands[0].brand : "",
        );
      } else {
        console.error("Get device metadata failed, no token received");
      }
    },
    onError: (error: any) => {
      dispatch(stopLoading());
      console.error("Get device metadata error:", error.response.data);
    },
  });

  if (popup.isOpen === false) {
    return null;
  }
  return (
    <div className="fixed inset-0 z-[100] flex items-center justify-center p-4 animate-in fade-in duration-200">
      <div
        className="absolute inset-0 bg-slate-900/60 backdrop-blur-sm"
        onClick={() => {
          dispatch(closeCompatibilityModal());
        }}
      ></div>

      {/* Container is now a flex column with hidden overflow to manage scroll internally */}
      <div className="relative bg-white rounded-[32px] w-full max-w-4xl max-h-[90vh] shadow-2xl flex flex-col overflow-hidden">
        {/* Fixed Close Button (Absolute) */}
        <button
          onClick={() => {
            dispatch(closeCompatibilityModal());
          }}
          className="absolute top-4 right-4 p-2 text-slate-400 hover:text-[#EE0434] transition-colors bg-white/80 backdrop-blur-sm rounded-full shadow-sm z-20"
        >
          <svg
            className="w-6 h-6"
            fill="none"
            stroke="currentColor"
            viewBox="0 0 24 24"
          >
            <path
              strokeLinecap="round"
              strokeLinejoin="round"
              strokeWidth={2}
              d="M6 18L18 6M6 6l12 12"
            />
          </svg>
        </button>

        {/* Fixed Header */}
        <div className="shrink-0 p-8 md:p-10 lg:p-10 pb-2 text-center bg-white z-10 relative">
          <h2 className="text-xl md:text-3xl font-black text-slate-900 mb-2 tracking-tight">
            {t("doesEsimWorkWithMyDevice")} <br />
            {/* <span className="text-[#EE0434]">support eSIM ?</span> */}
          </h2>
        </div>

        {/* Scrollable Content Body */}
        <div className="flex-1 overflow-y-auto p-3 md:p-8 lg:p-10 pt-1 custom-scrollbar">
          <div className="text-center mb-8">
            <h3 className="text-xm md:text-base lg:text-xl font-black text-[#EE0434] mb-6">
              {t("selectTopicInstructions")}
            </h3>

            <div className="text-left bg-slate-50 p-3 rounded-2xl border border-slate-100 text-sm md:text-base text-slate-600 space-y-4 mb-8">
              <p className="font-bold">{t("importantNote")}</p>
              <ul className="list-disc pl-5 space-y-1 marker:text-[#EE0434]">
                <li>{t("someDualPhysicalSimModelsDoNotSupportEsim")}</li>
                <li>{t("carrierLockedDevicesMayNotSupportEsim")}</li>
                <li>
                  {t("someModelsPurchasedInCertainCountriesMayNotSupportEsim")}
                </li>
              </ul>
              <p>{t("toMakeSureYourDeviceSupportsEsim")}</p>
            </div>
          </div>

          {/* Brand Tabs */}
          <div className="flex justify-center space-x-8 mb-10 overflow-x-auto py-2">
            {brands.map((brand) => (
              <button
                key={brand.brand}
                onClick={() => setSelectedBrand(brand.brand)}
                className={`flex flex-col items-center space-y-3 group min-w-[80px] focus:outline-none`}
              >
                <div
                  className={`w-16 h-16 flex items-center justify-center transition-colors ${
                    selectedBrand === brand.brand
                      ? "text-slate-900 scale-110"
                      : "text-slate-300 group-hover:text-slate-500"
                  }`}
                >
                  {brand.brand == "Apple" ? (
                    <svg
                      className="w-8 h-8"
                      viewBox="0 0 384 512"
                      fill="currentColor"
                    >
                      <path d="M318.7 268.7c-.2-36.7 16.4-64.4 50-84.8-18.8-26.9-47.2-41.7-84.7-44.6-35.5-2.8-74.3 20.7-88.5 20.7-15 0-49.4-19.7-76.4-19.7C63.3 141.2 4 184.8 4 273.5q0 39.3 14.4 81.2c12.8 36.7 59 126.7 107.2 125.2 25.2-.6 43-17.9 75.8-17.9 31.8 0 48.3 17.9 76.4 17.9 48.6-.7 90.4-82.5 102.6-119.3-65.2-30.7-61.7-90-61.7-91.9zm-56.6-164.2c27.3-32.4 24.8-61.9 24-72.5-24.1 1.4-52 16.4-67.9 34.9-17.5 19.8-27.8 44.3-25.6 71.9 26.1 2 52.3-11.4 69.5-34.3z" />
                    </svg>
                  ) : brand.brand == "Samsung" ? (
                    <svg
                      className="w-12 h-8"
                      viewBox="0 0 24 24"
                      fill="currentColor"
                    >
                      <path d="M17.8 4.8C14.3 3.6 9.7 3.6 6.2 4.8 1.9 6.3 0 10.2 0 14.9s1.9 8.6 6.2 10.1c3.5 1.2 8.1 1.2 11.6 0 4.3-1.5 6.2-5.4 6.2-10.1s-1.9-8.6-6.2-10.1zM8 17.9c-1.3 0-2.4-.3-2.4-1.4 0-1.1 1.1-1.4 2.4-1.4 1.3 0 2.4.3 2.4 1.4 0 1.1-1.1 1.4-2.4 1.4zm0-5.7c-1.3 0-2.4-.3-2.4-1.4 0-1.1 1.1-1.4 2.4-1.4 1.3 0 2.4.3 2.4 1.4 0 1.1-1.1 1.4-2.4 1.4zm8 5.7c-1.3 0-2.4-.3-2.4-1.4 0-1.1 1.1-1.4 2.4-1.4 1.3 0 2.4.3 2.4 1.4 0 1.1-1.1 1.4-2.4 1.4zm0-5.7c-1.3 0-2.4-.3-2.4-1.4 0-1.1 1.1-1.4 2.4-1.4 1.3 0 2.4.3 2.4 1.4 0 1.1-1.1 1.4-2.4 1.4z" />
                    </svg>
                  ) : brand.brand == "Google" ? (
                    <svg
                      className="w-8 h-8"
                      viewBox="0 0 24 24"
                      fill="currentColor"
                    >
                      <path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm0 18c-4.41 0-8-3.59-8-8s3.59-8 8-8 8 3.59 8 8-3.59 8-8 8zm-1-13h2v6h-2zm0 8h2v2h-2z" />
                    </svg>
                  ) : (
                    <svg
                      className="w-6 h-8"
                      viewBox="0 0 24 24"
                      fill="currentColor"
                    >
                      <path d="M17 1.01L7 1c-1.1 0-2 .9-2 2v18c0 1.1.9 2 2 2h10c1.1 0 2-.9 2-2V3c0-1.1-.9-1.99-2-1.99zM17 19H7V5h10v14z" />
                    </svg>
                  )}
                </div>
                <span
                  className={`font-bold transition-colors text-lg md:text-lg lg:text-xl ${
                    selectedBrand === brand.brand
                      ? "text-[#EE0434]"
                      : "text-slate-300 group-hover:text-slate-500"
                  }`}
                >
                  {brand.brand}
                </span>
                {selectedBrand === brand.brand && (
                  <div className="w-12 h-1 bg-[#EE0434] rounded-full"></div>
                )}
              </button>
            ))}
          </div>

          {/* Device List (Scrolls with the body) */}
          <div className="bg-white rounded-t-3xl border-t border-slate-100">
            <div className="divide-y divide-slate-50">
              {deviceList[selectedBrand].map((device, idx) => (
                <div
                  key={idx}
                  className="py-4 px-4 text-center hover:bg-slate-50 transition-colors text-slate-700 font-bold text-x,"
                >
                  {device}
                </div>
              ))}
            </div>
          </div>

          {/* Divider */}
          <div className="my-10 border-t border-dashed border-slate-300"></div>

          {/* Apple Specific Note */}
          <div className="text-left text-slate-600 space-y-4 mb-12">
            <p className="font-bold text-[#EE0434]">
              {t("noteTheFollowingAppleDevicesDoNotSupportEsim")}
            </p>
            <ul className="list-disc pl-5 space-y-2 text-sm md:text-base">
              <li>{t("someDualPhysicalSimModelsDoNotSupportEsim")}</li>
              <li>
                {t(
                  "allIphonesPurchasedFromChinaHongKongAndMacauDoNotSupportEsim",
                )}
              </li>
            </ul>
          </div>

          {/* Divider */}
          <div className="my-10 border-t border-dashed border-slate-300"></div>

          {/* Method 2 */}
          <div className="text-center mb-12">
            <h3 className="text-xl md:text-2xl font-black text-[#EE0434] mb-4">
              {t("method2CheckDirectlyOnYourDevice")}
            </h3>
            <p className="text-slate-600 text-xs md:text-lg lg:text-xl">
              {t(
                "checkIfYourDeviceSupportsEsimAndWhetherItIsCarrierLockedByFollowing",
              )}
              {/* <button className="text-[#EE0434] font-bold hover:underline">
                {" "}
                {t("theStepsBelow")}
              </button> */}
            </p>
          </div>

          {/* Not Support */}
          <div className="text-center mb-8">
            <h3 className="text-xl md:text-2xl font-black text-[#EE0434] mb-4">
              {t("yourDeviceDoesNotSupportEsim")}
            </h3>
            <p className="text-slate-600 text-xs md:text-lg lg:text-xl">
              {t("tryFindingAPhysicalSimThatIsCompatibleWithYourDevice")}{" "}
              <button className="text-[#EE0434] font-bold hover:underline">
                {t("here")}
              </button>
            </p>
          </div>
        </div>
      </div>
    </div>
  );
};

export default CompatibilityModal;
