"use client";

import { useLanguageStore } from "@/store/languageStore";
import { useTranslation } from "react-i18next";
import Input from "@/components/ui/Input";
import SelectInput from "@/components/ui/SelectInput";
import {
  nationalityNeedsPassport,
  nationalityResidencyOptions,
  speaksArabicApplies,
  speaksArabicOptions,
} from "@/data/Constants";
import type { FormikProps } from "formik";
import type { MandateFormValues } from "./volunteerMandateParts";

/**
 * The mandate form's nationality, gender and civil-id fields.
 */
export default function MandateIdentityFields({
  values,
  setFieldValue,
}: {
  values: MandateFormValues;
  setFieldValue: FormikProps<MandateFormValues>["setFieldValue"];
}) {
  const { t } = useTranslation();
  const selectedLanguage = useLanguageStore((s) => s.language);

  return (
  <div className="grid grid-cols-2 mobilescreen:grid-cols-1 mobilescreen:gap-0 gap-6 selectfiled">
    <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);
        if (nationalityNeedsPassport(value)) {
          setFieldValue("civil_id", "");
        } else {
          setFieldValue("passport_number", "");
        }
        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
      />
    )}
    {/* BE-77 — see the email signup form; same optional
        question, asked only where it carries information. */}
    {(
      <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>
  );
}
