import SelectBox from "@/core/components/SelectBox";
import useEdaratLists from "@/lib/hooks/useEdaratLists";
import { useEffect, useState } from "react";

const CityContent = ({ provinceID, field, fieldState: { error } }) => {
    const { edaratList, loadingEdaratList, errorEdaratList } = useEdaratLists(provinceID);
    const [prevDependency, setPrevDependency] = useState(provinceID);

    useEffect(() => {
        if (prevDependency === provinceID) return;
        field.onChange(null);
        setPrevDependency(provinceID);
    }, [provinceID]);

    return (
        <SelectBox
            value={
                !provinceID
                    ? "dependency"
                    : errorEdaratList
                      ? "error"
                      : loadingEdaratList
                        ? "loading"
                        : field.value || ""
            }
            label={"اداره"}
            selectors={edaratList}
            schema={{ name: "name_fa", value: "id" }}
            error={error}
            onChange={field.onChange}
            helperText={error?.message}
            isLoading={loadingEdaratList}
            errorEcured={errorEdaratList}
            isDependency={!provinceID}
            dependencyLabel={"ابتدا استان را انتخاب کنید"}
        />
    );
};
export default CityContent;
