"use client";

import dynamic from "next/dynamic";
import { LoadingCard } from "@/components/loading";
import useAddressStore from "@/global-store/address";
import { Modal } from "@/components/modal";
import { useEffect, useState } from "react";
import { getCookie, setCookie } from "cookies-next";
import { areaService, cityService, countryService } from "@/services/country";
import { IRAN_COUNTRY_CODE, IRAN_COUNTRY_ID } from "@/config/global";

const CountrySelectPanel = dynamic(() => import("./country-select-panel"), {
  loading: () => <LoadingCard />,
});

export const CountrySelect = ({
  settings,
  defaultOpen = true,
}: {
  settings: Record<string, string>;
  defaultOpen: boolean;
}) => {
  const isCountrySelectModalOpen = useAddressStore((state) => state.isCountrySelectModalOpen);
  const closeCountrySelectModal = useAddressStore((state) => state.closeCountrySelectModal);
  const country = useAddressStore((state) => state.country);
  const city = useAddressStore((state) => state.city);
  const area = useAddressStore((state) => state.area);
  const updateCountry = useAddressStore((state) => state.updateCountry);
  const updateCity = useAddressStore((state) => state.updateCity);
  const updateArea = useAddressStore((state) => state.updateArea);
  const [hydrated, setHydrated] = useState(() => useAddressStore.persist.hasHydrated());
  /** تا بررسی مکان تمام نشود مودال نشان داده نمی‌شود (جلوگیری از فلش) */
  const [locationReady, setLocationReady] = useState(false);

  useEffect(() => {
    const unsub = useAddressStore.persist.onFinishHydration(() => setHydrated(true));
    if (useAddressStore.persist.hasHydrated()) setHydrated(true);
    return unsub;
  }, []);

  useEffect(() => {
    if (!hydrated) return;
    let cancelled = false;

    const restore = async () => {
      const state = useAddressStore.getState();
      if (state.city?.id && state.area?.id) {
        if (!cancelled) setLocationReady(true);
        return;
      }

      const cityId = Number(getCookie("city_id") || 0);
      const areaId = Number(getCookie("area_id") || 0);

      try {
        if (cityId && !state.city?.id) {
          const res = await cityService.get(cityId, { lang: "fa" });
          if (!cancelled && res?.data?.id) updateCity(res.data);
        }
        if (areaId && !useAddressStore.getState().area?.id) {
          const res = await areaService.get(areaId, { lang: "fa" });
          if (!cancelled && res?.data?.id) updateArea(res.data);
        }
      } catch {
        /* ignore */
      } finally {
        if (!cancelled) setLocationReady(true);
      }
    };

    void restore();
    return () => {
      cancelled = true;
    };
  }, [hydrated, updateCity, updateArea]);

  const hasLocation = !!city?.id && !!area?.id;
  const shouldOpen =
    locationReady && (isCountrySelectModalOpen || (defaultOpen && !hasLocation));

  useEffect(() => {
    let cancelled = false;
    const lockIran = async () => {
      if (country?.code === IRAN_COUNTRY_CODE || country?.id === IRAN_COUNTRY_ID) {
        setCookie("country_id", country.id);
        return;
      }
      try {
        const res = await countryService.get(IRAN_COUNTRY_ID, { lang: "fa" });
        const iran = res?.data;
        if (!cancelled && iran?.id) {
          updateCountry(iran);
          setCookie("country_id", iran.id);
        }
      } catch {
        /* ignore */
      }
    };
    void lockIran();
    return () => {
      cancelled = true;
    };
  }, [country?.id, country?.code, updateCountry]);

  return (
    <Modal
      size="large"
      isOpen={shouldOpen}
      onClose={closeCountrySelectModal}
      withCloseButton={hasLocation}
      overflowHidden={false}
    >
      <CountrySelectPanel settings={settings} />
    </Modal>
  );
};
