"use client";

import React from "react";
import Input from "@/components/ui/Input";
import { useTranslation } from "react-i18next";
import SelectInput from "@/components/ui/SelectInput";
import {
  nationalityNeedsPassport,
  nationalityResidencyOptions,
  speaksArabicApplies,
  speaksArabicOptions,
} from "@/data/Constants";
import type { FormikProps } from "formik";
import type { IndividualRegistrationValues } from "./individualRegistrationValues";

/** A field group lifted out of the form of the same family. */
export default function IndividualNationalityFields({
  values,
  setFieldValue,
  selectedLanguage,
}: {
  values: IndividualRegistrationValues;
  setFieldValue: FormikProps<IndividualRegistrationValues>["setFieldValue"];
  selectedLanguage: string;
}) {
  const { t } = useTranslation();

  return (
  <div className="grid grid-cols-2 mobilescreen:grid-cols-1 mobilescreen:gap-0 gap-6 selectfiled">
    {/* Nationality comes first here: it decides which
        identifier is asked for below it. */}
    <SelectInput
      name="nationality"
      label={t("COMMON.NATIONALITY")}
      options={nationalityResidencyOptions.map((item) => ({
        label: selectedLanguage === "ar" ? item.name_ar : item.name_en,
        value: item.value,
      }))}
      onChange={(selectedOption) => {
        const value = selectedOption?.value || "";
        setFieldValue("nationality", value);
        // Clear whichever identifier this choice does not use,
        // so a half-typed value cannot be submitted or shown
        // against the wrong question.
        if (nationalityNeedsPassport(value)) {
          setFieldValue("civil_id", "");
        } else {
          setFieldValue("passport_number", "");
        }
        // The Arabic question disappears for a Kuwaiti, so
        // drop any answer given before the switch rather than
        // submitting one the user can no longer see.
        if (!speaksArabicApplies(value)) {
          setFieldValue("speaks_arabic", "true");
        }
      }}
    />
    {nationalityNeedsPassport(values.nationality) ? (
      <Input
        name="passport_number"
        type="text"
        label={t("COMMON.PASSPORT_NUMBER")}
        maxLength={20}
      />
    ) : (
      <Input
        name="civil_id"
        type="text"
        label={t("COMMON.CIVIL_ID")}
        maxLength={12}
        digitsOnly
      />
    )}

    {(
      <SelectInput
        name="speaks_arabic"
        label={t("COMMON.SPEAKS_ARABIC")}
        options={speaksArabicOptions.map((item) => ({
          label:
            selectedLanguage === "ar"
              ? item.name_ar
              : item.name_en,
          value: item.value,
        }))}
        onChange={(selectedOption) =>
          setFieldValue(
            "speaks_arabic",
            selectedOption?.value || ""
          )
        }
      />
    )}
  </div>
  );
}
