import React, { useEffect, useState, useTransition } from "react";
import { Button } from "@/components/button";
import { useT } from "@/context/translation-map";
import useAddressStore from "@/global-store/address";
import { Area, City } from "@/types/global";
import { setCookie } from "cookies-next";
import { AsyncSelect } from "@/components/async-select";
import useCartStore from "@/global-store/cart";
import { useRouter } from "next/navigation";
import { countryService } from "@/services/country";
import { IRAN_COUNTRY_CODE } from "@/config/global";

export const CountrySelectForm = ({ onSelect }: { onSelect: () => void }) => {
  const t = useT();
  const router = useRouter();
  const selectedCountry = useAddressStore((state) => state.country);
  const updateCountry = useAddressStore((state) => state.updateCountry);
  const selectedCity = useAddressStore((state) => state.city);
  const selectedArea = useAddressStore((state) => state.area);
  const saveLocation = useAddressStore((state) => state.saveLocation);
  const [tempCountry, setTempCountry] = useState(selectedCountry);
  const [tempProvince, setTempProvince] = useState<City | null>(selectedCity);
  const [tempCity, setTempCity] = useState<Area | null>(selectedArea);
  const clearLocalCart = useCartStore((state) => state.clear);
  const [isPending, startTransition] = useTransition();
  const [isPressed, setIsPressed] = useState(false);
  const [loadingCountry, setLoadingCountry] = useState(!selectedCountry?.id);

  useEffect(() => {
    setTempProvince(selectedCity);
    setTempCity(selectedArea);
  }, [selectedCity?.id, selectedArea?.id]);

  useEffect(() => {
    let cancelled = false;
    const ensureIran = async () => {
      if (selectedCountry?.code === IRAN_COUNTRY_CODE || selectedCountry?.id) {
        if (selectedCountry?.code === IRAN_COUNTRY_CODE || selectedCountry?.id === 1) {
          setTempCountry(selectedCountry);
          setLoadingCountry(false);
          return;
        }
      }
      try {
        const res = await countryService.getAll({
          perPage: 1,
          search: "ایران",
          lang: "fa",
        });
        const iran =
          res?.data?.find((c) => c.code === IRAN_COUNTRY_CODE || c.id === 1) || res?.data?.[0];
        if (!cancelled && iran) {
          setTempCountry(iran);
          updateCountry(iran);
          setCookie("country_id", iran.id);
        }
      } catch {
        /* ignore */
      } finally {
        if (!cancelled) setLoadingCountry(false);
      }
    };
    void ensureIran();
    return () => {
      cancelled = true;
    };
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  const handleSaveAddress = () => {
    setIsPressed(true);
    const country = tempCountry;
    if (!country?.id || !tempProvince?.id || !tempCity?.id) return;

    setCookie("country_id", String(country.id));
    setCookie("city_id", String(tempProvince.id));
    setCookie("area_id", String(tempCity.id));

    saveLocation({
      country,
      city: tempProvince,
      area: tempCity,
    });
    clearLocalCart();

    setIsPressed(false);
    startTransition(() => {
      onSelect();
      router.refresh();
    });
  };

  return (
    <div className="flex flex-col gap-4">
      <AsyncSelect
        label="select.province"
        onSelect={(value) => {
          setTempProvince(value);
          setTempCity(null);
        }}
        extractTitle={(option) => option?.translation?.title as string}
        extractKey={(option) => option?.id}
        queryKey="v1/rest/cities"
        size="medium"
        queryParams={{ country_id: tempCountry?.id || 1 }}
        value={tempProvince ?? undefined}
        disabled={loadingCountry || !tempCountry?.id}
        error={isPressed && !tempProvince ? t("select.province") || "انتخاب استان" : undefined}
      />
      <AsyncSelect
        label="select.city"
        onSelect={(value) => setTempCity(value)}
        extractTitle={(option) => option?.translation?.title as string}
        extractKey={(option) => option?.id}
        queryKey="v1/rest/areas"
        size="medium"
        queryParams={{
          country_id: tempCountry?.id || 1,
          city_id: tempProvince?.id,
        }}
        value={tempCity ?? undefined}
        disabled={loadingCountry || !tempProvince?.id}
        error={isPressed && !tempCity ? t("select.city") : undefined}
      />
      <Button
        loading={isPending || loadingCountry}
        onClick={handleSaveAddress}
        disabled={!tempProvince || !tempCity || !tempCountry?.id}
        fullWidth
        size="small"
        color="black"
      >
        {t("save.address")}
      </Button>
    </div>
  );
};
