"use client";

import { useTranslation } from "react-i18next";
import ModalInput from "@/components/ui/ModalInput";
import InlineSpinner from "@/components/ui/InlineSpinner";
import { ModalPhoneInput } from "@/components/ui/PhoneInput";
import CountryCodeSelect, {
  FIELD_LABEL_CLASS,
} from "./registerVolunteerParts";
import type { FormikErrors, FormikProps } from "formik";
import type { RegisterVolunteerValues } from "./registerVolunteerValues";
import type { NicknameAvailability } from "@/features/shared/nicknameAvailability";

/** A field group lifted out of the form of the same family. */
export default function RegisterVolunteerContactFields({
  values,
  setFieldValue,
  errors,
  nicknameAvailability,
  checkNicknameAvailability,
}: {
  values: RegisterVolunteerValues;
  setFieldValue: FormikProps<RegisterVolunteerValues>["setFieldValue"];
  errors: FormikErrors<RegisterVolunteerValues>;
  nicknameAvailability: NicknameAvailability;
  checkNicknameAvailability: (nickname: string) => void;
}) {
  const { t } = useTranslation();

  return (
  <div className="grid grid-cols-2 mobilescreen:gap-[0px] mobilescreen:grid-cols-1 gap-[100px]">
    <div>
      <p className={FIELD_LABEL_CLASS}>
        {t("COMMON.PHONENUMBER")}
      </p>
      <div className="flex gap-2">
        <div>
          <CountryCodeSelect
            name="country_code"
            className="w-full"
            onChange={(value: string) =>
              setFieldValue("country_code", value)
            }
          />
        </div>
        <ModalPhoneInput
          name="phone_number"
          placeholder={t("COMMON.PHONENUMBER")}
          countryCode={values.country_code}
        />
      </div>
    </div>
    <div className="relative">
      <p className={FIELD_LABEL_CLASS}>{t("COMMON.NICKNAME")}</p>
      <ModalInput
        name="nickname"
        endAdornment={
          nicknameAvailability.checking ? (
            <InlineSpinner label={t("COMMON.CHECKING_AVAILABILITY")} />
          ) : null
        }
        type="text"
        placeholder={t("COMMON.NICKNAME")}
        autoComplete="off"
        onChange={(event) => {
          setFieldValue("nickname", event.target.value);
          checkNicknameAvailability(event.target.value);
        }}
      />
      {values.nickname && !errors.nickname && (
        <div className="text-sm -mt-3 mb-4">
          {!nicknameAvailability.checking &&
            nicknameAvailability.available === true && (
              <span className="text-green-600">
                ✓ {nicknameAvailability.message}
              </span>
            )}
          {!nicknameAvailability.checking &&
            nicknameAvailability.available === false && (
              <span className="text-red-600">
                ✗ {nicknameAvailability.message}
              </span>
            )}
        </div>
      )}
    </div>
  </div>
  );
}
