"use client";
import type { SelectFieldClientComponent } from "payload";

import { SelectField, useField, useFormFields } from "@payloadcms/ui";
import { City } from "country-state-city";
import { useEffect } from "react";

const InputCity: SelectFieldClientComponent = ({ field, ...props }) => {
  const stateCode = useFormFields(([fields]) => fields["addressGroup.state_code"]);
  const { setValue } = useField();

  useEffect(() => {
    if (!stateCode?.value) {
      setValue("");
    }
  }, [stateCode?.value]);

  if (!stateCode?.value) {
    // @ts-ignore
    field.admin = { ...field.admin, description: "Please select the state before select the city." };
    field.options = [];
  } else {
    // @ts-ignore
    field.admin = { ...field.admin, description: "" };
    field.options = City.getCitiesOfState("US", stateCode.value as string).map((c) => ({
      value: c.name,
      label: c.name,
    }));
  }

  return <SelectField field={field} {...props} />;
};

export default InputCity;
