import { useEffect, useState, useMemo, useRef } from "react";
import { useApiMutation } from "../../utils/useApiRequest";
import AutoComplete from "../AutoComplete/AutoComplete";
import { useUserProfileStore } from "../../context/zustand-store/userStore";

type FormEnterLocationsProps = {
  cityError: boolean;
  cityValue?: string | number;
  provinceValue?: string | number;
  provincError: boolean;
  cityErrorMessage?: any;
  provinceErrMessage?: any;
  roleControlled?: boolean;
  onChange?: (data: { province: string | any; city: string | any }) => void;
  onChangeValue?: (data: {
    province: string | any;
    city: string | any;
  }) => void;
};

export const FormEnterLocations = ({
  roleControlled,
  cityError,
  cityValue,
  provinceValue,
  cityErrorMessage,
  provincError,
  provinceErrMessage,
  onChange,
  onChangeValue,
}: FormEnterLocationsProps) => {
  const [provinceApiData, setProvinceAPiData] = useState<any>(null);
  const [provinceData, setProvinceData] = useState<any>([]);
  const [cityApiData, setCityAPiData] = useState<any>(null);
  const [cityData, setCityData] = useState<any>([]);
  const [selectedProvinceKeys, setSelectedProvinceKeys] = useState<
    (string | number)[]
  >([]);
  const [selectedCityKeys, setSelectedCityKeys] = useState<(string | number)[]>(
    []
  );
  const [value, setValue] = useState<{
    province: string | any;
    city: string | any;
  }>({ province: "", city: "" });
  const lastFetchedProvinceId = useRef<number | string | undefined>(undefined);

  const { profile } = useUserProfileStore();

  const isProvinceDisabled =
    roleControlled &&
    profile?.organization?.field_of_activity !== "CO" &&
    profile?.role?.type?.key !== "ADM";

  const isCityDisabled =
    roleControlled &&
    profile?.organization?.field_of_activity === "CI" &&
    profile?.role?.type?.key !== "ADM";

  const provinceId = useMemo(() => {
    return isProvinceDisabled
      ? profile?.user?.province
      : selectedProvinceKeys[0];
  }, [isProvinceDisabled, profile?.user?.province, selectedProvinceKeys]);

  const cityId = useMemo(() => {
    return isCityDisabled ? profile?.user?.city : selectedCityKeys[0];
  }, [isCityDisabled, profile?.user?.city, selectedCityKeys]);

  const mutationProvince = useApiMutation({
    api: "/auth/api/v1/province/",
    method: "get",
    disableBackdrop: provinceValue ? true : false,
  });

  const mutationCity = useApiMutation({
    api: `/auth/api/v1/city/`,
    method: "get",
    disableBackdrop: provinceValue ? true : false,
  });

  const getPages = async () => {
    const data = await mutationProvince.mutateAsync({
      page: 1,
      page_size: 1000,
    });
    setProvinceAPiData(data);
  };
  const getCities = async (provinceIdParam: number | string | undefined) => {
    if (!provinceIdParam) return;

    if (lastFetchedProvinceId.current === provinceIdParam) {
      return;
    }

    lastFetchedProvinceId.current = provinceIdParam;

    const data = await mutationCity.mutateAsync({
      page: 1,
      page_size: 1000,
      province: provinceIdParam,
    });
    setCityAPiData(data);
  };

  useEffect(() => {
    getPages();
  }, []);

  useEffect(() => {
    if (provinceApiData?.results) {
      const d = provinceApiData.results.map((province: any) => ({
        key: province.id,
        value: province.name,
      }));
      setProvinceData(d);
    }
  }, [provinceApiData]);

  useEffect(() => {
    const currentProvinceId = provinceId;

    if (currentProvinceId) {
      if (isProvinceDisabled && profile?.user?.province) {
        getCities(currentProvinceId);
      } else if (selectedProvinceKeys.length) {
        getCities(currentProvinceId);
      }
    }

    if (!isProvinceDisabled && selectedProvinceKeys.length === 0) {
      setCityData([]);
      setSelectedCityKeys([]);
      lastFetchedProvinceId.current = undefined;
    }
  }, [
    provinceId,
    selectedProvinceKeys.length,
    isProvinceDisabled,
    profile?.user?.province,
  ]);

  useEffect(() => {
    if (cityApiData) {
      const d = cityApiData.map((city: any) => ({
        key: city.id,
        value: city.name,
      }));
      setCityData(d);
    }
  }, [cityApiData]);

  useEffect(() => {
    if (
      isProvinceDisabled &&
      profile?.user?.province &&
      provinceData.length > 0
    ) {
      const initialProvince = provinceData.find(
        (province: any) => province.key === profile.user.province
      );
      if (initialProvince) {
        setSelectedProvinceKeys([initialProvince.key]);
      }
    } else if (provinceValue && provinceData.length > 0) {
      const initialProvince = provinceData.find(
        (province: any) => province.key === provinceValue
      );
      if (initialProvince) {
        setSelectedProvinceKeys([initialProvince.key]);
      }
    }
  }, [
    provinceValue,
    provinceData,
    isProvinceDisabled,
    profile?.user?.province,
  ]);

  useEffect(() => {
    if (isCityDisabled && profile?.user?.city && cityData.length > 0) {
      const initialCity = cityData.find(
        (city: any) => city.key === profile.user.city
      );
      if (initialCity) {
        setSelectedCityKeys([initialCity.key]);
      }
    } else if (cityValue && cityData.length > 0) {
      const initialCity = cityData.find((city: any) => city.key === cityValue);
      if (initialCity) {
        setSelectedCityKeys([initialCity.key]);
      }
    }
  }, [cityValue, cityData, isCityDisabled, profile?.user?.city]);

  useEffect(() => {
    if (onChange)
      onChange({
        province:
          typeof selectedProvinceKeys[0] === "number"
            ? selectedProvinceKeys[0]
            : "",
        city: typeof cityId === "number" ? cityId : "",
      });
  }, [selectedProvinceKeys, selectedCityKeys, cityId]);

  useEffect(() => {
    if (value.province && value.city) onChangeValue?.(value);
  }, [value]);

  return (
    <>
      <AutoComplete
        data={provinceData}
        selectedKeys={selectedProvinceKeys}
        onChange={(newselectedProvinceKeys) => {
          setSelectedProvinceKeys(newselectedProvinceKeys);
        }}
        onChangeValue={(r) => {
          setValue((prev) => ({ ...prev, province: r.value }));
        }}
        title="استان"
        error={provincError}
        helperText={provinceErrMessage}
        disabled={isProvinceDisabled}
      />
      <AutoComplete
        disabled={isCityDisabled || !selectedProvinceKeys.length}
        data={cityData}
        selectedKeys={selectedCityKeys}
        onChange={(newselectedProvinceKeys) => {
          setSelectedCityKeys(newselectedProvinceKeys);
        }}
        onChangeValue={(r) => {
          setValue((prev) => ({ ...prev, city: r.value }));
        }}
        title="شهر"
        error={cityError}
        helperText={cityErrorMessage}
      />
    </>
  );
};
