"use client";

import { useEffect, useRef, useState } from "react";
import { useDispatch, useSelector } from "react-redux";
import ExpandMoreIcon from "@mui/icons-material/ExpandMore";
import CheckIcon from "@mui/icons-material/Check";

import authStorage from "@/src/server_api/storage";
import { localStorageValues } from "@/src/constants/local-storage-values";
import { supportedCountries } from "@/src/constants/common";
import {
    getCountrySubDomainFromHostname,
    redirectToCountry,
} from "@/src/server_api/utils/sub-domain";

import { RootState } from "@/src/redux/store";
import { setFromCurrency, setToCurrency } from "@/src/redux/slice/currencies-slice";
import useCurrencies from "@/src/server_api/hooks/useCurrencies";

interface CountryCurrencySelectProps {
    isTransparent?: boolean;
    className?: string;
}

type CurrencyOption = {
    value: string;
    label: string;
    display: string;
};

type RegionConfig = {
    code: string;
    label: string;
    fullLabel: string;
    flag: string;
    defaultCurrency: string;
    currencies: CurrencyOption[];
};

const REGION_CONFIGS: Record<string, RegionConfig> = {
    ae: {
        code: "ae",
        label: "UAE",
        fullLabel: "United Arab Emirates",
        flag: "🇦🇪",
        defaultCurrency: "AED",
        currencies: [
            { value: "AED", label: "AED - UAE Dirham", display: "AED" },
            { value: "USD", label: "USD - US Dollar", display: "USD" },
        ],
    },
    my: {
        code: "my",
        label: "Malaysia",
        fullLabel: "Malaysia",
        flag: "🇲🇾",
        defaultCurrency: "MYR",
        currencies: [
            { value: "MYR", label: "RM - Malaysian Ringgit", display: "RM" },
            { value: "USD", label: "USD - US Dollar", display: "USD" },
        ],
    },
};

export default function CountryCurrencySelect({
    isTransparent = false,
    className = "",
}: CountryCurrencySelectProps) {
    const dispatch = useDispatch();

    const { toCurrency } = useSelector(
        (state: RootState) => state.currencies
    );

    const [regionOpen, setRegionOpen] = useState(false);
    const [currencyOpen, setCurrencyOpen] = useState(false);

    const regionRef = useRef<HTMLDivElement>(null);
    const currencyRef = useRef<HTMLDivElement>(null);

    // Detect current country from hostname ("ae" | "my")
    const currentCountryCode =
        typeof window !== "undefined"
            ? getCountrySubDomainFromHostname(window.location.hostname) || "ae"
            : "ae";

    const currentRegion = REGION_CONFIGS[currentCountryCode] || REGION_CONFIGS.ae;

    useCurrencies({
        fetchCurrency: true,
    });

    // Ensure correct base and regional currency state on mount & region detection
    useEffect(() => {
        const isMalaysia = currentCountryCode === "my";
        const baseCurrency = isMalaysia ? "MYR" : "AED";
        const allowedCurrencies = isMalaysia ? ["MYR", "USD"] : ["AED", "USD"];

        const savedForRegion = authStorage.getData(`savedCurrency_${currentCountryCode}`);
        const globalSaved = authStorage.getData(localStorageValues.currency);

        let activeCurrency = savedForRegion || globalSaved || baseCurrency;

        // If currency stored is not valid for this region (e.g. AED in Malaysia or MYR in UAE), reset to regional default
        if (!allowedCurrencies.includes(activeCurrency)) {
            activeCurrency = baseCurrency;
        }

        dispatch(setFromCurrency(baseCurrency));

        if (activeCurrency !== toCurrency) {
            dispatch(setToCurrency(activeCurrency));
            authStorage.storeData(`savedCurrency_${currentCountryCode}`, activeCurrency);
            authStorage.storeData(localStorageValues.currency, activeCurrency);
        }
    }, [currentCountryCode, dispatch, toCurrency]);

    // Close dropdowns on outside click
    useEffect(() => {
        const handleClickOutside = (event: MouseEvent) => {
            if (
                regionRef.current &&
                !regionRef.current.contains(event.target as Node)
            ) {
                setRegionOpen(false);
            }
            if (
                currencyRef.current &&
                !currencyRef.current.contains(event.target as Node)
            ) {
                setCurrencyOpen(false);
            }
        };

        document.addEventListener("mousedown", handleClickOutside);
        return () => {
            document.removeEventListener("mousedown", handleClickOutside);
        };
    }, []);

    const handleCountryChange = (targetCountryCode: string) => {
        setRegionOpen(false);
        if (targetCountryCode === currentCountryCode) return;

        // Save current region currency choice
        authStorage.storeData(`savedCurrency_${currentCountryCode}`, toCurrency);

        // Determine next currency for target region:
        // 1. Keep USD if already selected
        // 2. Otherwise check remembered selection for target region
        // 3. Fallback to regional default (AED for UAE, MYR for Malaysia)
        let nextCurrency = targetCountryCode === "my" ? "MYR" : "AED";
        if (toCurrency === "USD") {
            nextCurrency = "USD";
        } else {
            const rememberedForTarget = authStorage.getData(`savedCurrency_${targetCountryCode}`);
            if (rememberedForTarget === "USD") {
                nextCurrency = "USD";
            }
        }

        authStorage.storeData(`savedCurrency_${targetCountryCode}`, nextCurrency);
        authStorage.storeData(localStorageValues.currency, nextCurrency);
        dispatch(setToCurrency(nextCurrency));
        dispatch(setFromCurrency(targetCountryCode === "my" ? "MYR" : "AED"));

        redirectToCountry(targetCountryCode);
    };

    const handleCurrencyChange = async (value: string) => {
        dispatch(setToCurrency(value));
        await authStorage.storeData(`savedCurrency_${currentCountryCode}`, value);
        await authStorage.storeData(localStorageValues.currency, value);
        setCurrencyOpen(false);
    };

    const displayCurrencyLabel =
        toCurrency === "MYR" || toCurrency === "RM"
            ? "RM"
            : toCurrency === "USD"
                ? "USD"
                : toCurrency === "AED"
                    ? "AED"
                    : currentRegion.defaultCurrency === "MYR"
                        ? "RM"
                        : "AED";

    const textColorClass = isTransparent
        ? "text-white hover:text-white/80"
        : "text-gray-900 hover:text-black";

    return (
        <div className={`flex items-center gap-4 sm:gap-6 text-xs sm:text-sm ${className}`}>
            {/* Region Dropdown */}
            <div ref={regionRef} className="relative">
                <button
                    type="button"
                    onClick={() => {
                        setRegionOpen((prev) => !prev);
                        setCurrencyOpen(false);
                    }}
                    className={`
                        flex
                        items-center
                        gap-1
                        font-medium
                        transition
                        cursor-pointer
                        ${textColorClass}
                    `}
                >
                    <span className="font-bold">Region:</span>
                    <span className="font-semibold">{currentRegion.label}</span>
                    <ExpandMoreIcon
                        fontSize="small"
                        className={`transition-transform duration-200 text-current ${
                            regionOpen ? "rotate-180" : ""
                        }`}
                        sx={{ fontSize: "1.1rem" }}
                    />
                </button>

                {regionOpen && (
                    <div
                        className="
                            absolute
                            right-0
                            top-full
                            mt-1.5
                            w-52
                            rounded-xl
                            border
                            border-gray-200
                            bg-white
                            p-1.5
                            shadow-xl
                            z-50
                            text-gray-900
                        "
                    >
                        <div className="px-2.5 py-1 text-[11px] font-bold text-gray-400 uppercase tracking-wider">
                            Select Region
                        </div>
                        <div className="space-y-0.5">
                            {supportedCountries.map((country) => {
                                const isSelected = country.code === currentCountryCode;
                                return (
                                    <button
                                        key={country.code}
                                        type="button"
                                        onClick={() => handleCountryChange(country.code)}
                                        className={`
                                            flex
                                            w-full
                                            items-center
                                            justify-between
                                            rounded-lg
                                            px-2.5
                                            py-1.5
                                            text-xs sm:text-sm
                                            transition
                                            ${
                                                isSelected
                                                    ? "bg-gray-100 font-semibold text-black"
                                                    : "text-gray-700 hover:bg-gray-50"
                                            }
                                        `}
                                    >
                                        <div className="flex items-center gap-2">
                                            <span className="text-base">{country.flag}</span>
                                            <span>{country.code === "ae" ? "UAE" : country.code === "my" ? "Malaysia" : country.label}</span>
                                        </div>
                                        {isSelected && (
                                            <CheckIcon fontSize="small" className="text-black" />
                                        )}
                                    </button>
                                );
                            })}
                        </div>
                    </div>
                )}
            </div>

            {/* Currency Dropdown */}
            <div ref={currencyRef} className="relative">
                <button
                    type="button"
                    onClick={() => {
                        setCurrencyOpen((prev) => !prev);
                        setRegionOpen(false);
                    }}
                    className={`
                        flex
                        items-center
                        gap-1
                        font-medium
                        transition
                        cursor-pointer
                        ${textColorClass}
                    `}
                >
                    <span className="font-bold">Currency:</span>
                    <span className="font-semibold">{displayCurrencyLabel}</span>
                    <ExpandMoreIcon
                        fontSize="small"
                        className={`transition-transform duration-200 text-current ${
                            currencyOpen ? "rotate-180" : ""
                        }`}
                        sx={{ fontSize: "1.1rem" }}
                    />
                </button>

                {currencyOpen && (
                    <div
                        className="
                            absolute
                            right-0
                            top-full
                            mt-1.5
                            w-52
                            rounded-xl
                            border
                            border-gray-200
                            bg-white
                            p-1.5
                            shadow-xl
                            z-50
                            text-gray-900
                        "
                    >
                        <div className="px-2.5 py-1 text-[11px] font-bold text-gray-400 uppercase tracking-wider">
                            Select Currency
                        </div>
                        <div className="space-y-0.5">
                            {currentRegion.currencies.map((item) => {
                                const isSelected = toCurrency === item.value || (toCurrency === "RM" && item.value === "MYR");
                                return (
                                    <button
                                        key={item.value}
                                        type="button"
                                        onClick={() => handleCurrencyChange(item.value)}
                                        className={`
                                            flex
                                            w-full
                                            items-center
                                            justify-between
                                            rounded-lg
                                            px-2.5
                                            py-1.5
                                            text-xs sm:text-sm
                                            transition
                                            ${
                                                isSelected
                                                    ? "bg-gray-100 font-semibold text-black"
                                                    : "text-gray-700 hover:bg-gray-50"
                                            }
                                        `}
                                    >
                                        <span>{item.label}</span>
                                        {isSelected && (
                                            <CheckIcon fontSize="small" className="text-black" />
                                        )}
                                    </button>
                                );
                            })}
                        </div>
                    </div>
                )}
            </div>
        </div>
    );
}
