"use client";

import { useRef } from "react";
import { useFormikContext } from "formik";
import { useTranslation } from "react-i18next";
import { FaCloudArrowUp } from "react-icons/fa6";
import { IoInformationCircleOutline } from "react-icons/io5";

import {
  MIN_TRAINER_AGE,
  TRAINER_CERTIFICATE_TYPES,
  offeredTrainerTypes,
  type TrainerRequestSettings,
  type TrainerRequestValues,
  type TrainerTypeSlug,
} from "../trainerRequest";
import TrainerBankFields, { FieldError } from "./TrainerBankFields";

interface TrainerRequestFieldsProps {
  settings: TrainerRequestSettings;
  /**
   * An account already on file (settings card only): the bank block is
   * replaced by a one-line reminder, since the server relies on that account
   * and refuses a different one here.
   */
  bankOnFile?: { last4: string; bankName: string | null } | null;
  /** Narrowed list for an approved trainer asking for more types; defaults to every offered type. */
  types?: ReturnType<typeof offeredTrainerTypes>;
}

function Notice({ children }: { children: React.ReactNode }) {
  return (
    <p className="mb-4 flex items-start gap-2 rounded-2xl bg-[#29246D08] p-3 text-sm text-secondary-102">
      <IoInformationCircleOutline size={18} className="mt-0.5 shrink-0 text-primary-5" />
      <span>{children}</span>
    </p>
  );
}

/**
 * The trainer block from the client's design: which development types, the
 * qualification file (course only), and the payout account. Rendered inside a
 * parent Formik — the signup form and the settings card each own their form
 * and their submit, and share only these fields and `trainerRequestSchema`.
 */
export default function TrainerRequestFields({ settings, bankOnFile, types }: TrainerRequestFieldsProps) {
  const { t } = useTranslation();
  const { values, setFieldValue, setFieldTouched } =
    useFormikContext<TrainerRequestValues>();
  const fileInputRef = useRef<HTMLInputElement>(null);

  const offersCourse = values.trainer_types.includes("course");

  /*
   * Any number of types, as checkboxes (client, 2026-10-18 — was a single
   * radio choice since 2026-10-10). The API takes `trainer_types[]` as is.
   */
  const toggleType = (slug: TrainerTypeSlug) => {
    const next = values.trainer_types.includes(slug)
      ? values.trainer_types.filter((selected) => selected !== slug)
      : [...values.trainer_types, slug];
    setFieldValue("trainer_types", next);
    setFieldTouched("trainer_types", true, false);
    // Unticking Course drops the file with it — only a course asks for one.
    if (slug === "course" && !next.includes("course")) {
      setFieldValue("trainer_certificate", null);
    }
  };

  return (
    <div className="mt-2">
      <Notice>{t("COMMON.TRAINER_AGE_NOTICE", { age: MIN_TRAINER_AGE })}</Notice>

      <section className="mb-6 rounded-2xl border border-[#29246D1A] p-4">
        <h3 className="mb-3 text-lg font-bold text-primary-5">
          {t("COMMON.TRAINER_QUALIFICATIONS")}
        </h3>

        {/* BE-95 — from `trainer_types` on the settings payload, so a slug the
            API stopped accepting cannot sit here and 422 the submission. */}
        <div className="grid grid-cols-3 gap-3 mobilescreen:grid-cols-1">
          {(types ?? offeredTrainerTypes(settings)).map((type) => {
            const selected = values.trainer_types.includes(type.slug);
            return (
              <label
                key={type.slug}
                htmlFor={`trainer-type-${type.slug}`}
                className={`flex cursor-pointer items-center gap-3 rounded-xl border px-4 py-3 text-primary-5 transition-colors ${
                  selected
                    ? "border-primary-5 bg-[#29246D0D] font-semibold"
                    : "border-[#29246D1A]"
                }`}
              >
                <input
                  id={`trainer-type-${type.slug}`}
                  type="checkbox"
                  name="trainer_types"
                  value={type.slug}
                  checked={selected}
                  onChange={() => toggleType(type.slug)}
                  className="h-5 w-5 rounded accent-[#29246D]"
                />
                {t(type.labelKey)}
              </label>
            );
          })}
        </div>
        <FieldError name="trainer_types" />

        {offersCourse && (
          <div className="mt-4 rounded-2xl border border-dashed border-[#29246D33] p-4 text-center">
            <FaCloudArrowUp size={24} className="mx-auto mb-2 text-primary-5" />
            <p className="font-bold text-primary-5">
              {t("COMMON.TRAINER_CERTIFICATE_LABEL")}
              {offersCourse && (
                <span className="text-red-500"> *</span>
              )}
            </p>
            <p className="mb-3 text-xs text-secondary-102">
              {t("COMMON.TRAINER_CERTIFICATE_HINT")}
            </p>
            <input
              ref={fileInputRef}
              id="trainer_certificate"
              type="file"
              accept={TRAINER_CERTIFICATE_TYPES.join(",")}
              className="sr-only"
              onChange={(event) => {
                setFieldValue("trainer_certificate", event.target.files?.[0] ?? null);
                setFieldTouched("trainer_certificate", true, false);
              }}
            />
            <button
              type="button"
              onClick={() => fileInputRef.current?.click()}
              className="rounded-lg border border-primary-5 px-4 py-1.5 text-sm text-primary-5"
            >
              {t("COMMON.CHOOSE_FILE")}
            </button>
            {values.trainer_certificate && (
              <p className="mt-2 text-sm text-primary-5" dir="auto">
                {values.trainer_certificate.name}
              </p>
            )}
            <FieldError name="trainer_certificate" />
          </div>
        )}

        <div className="mt-4 [&>p]:mb-0">
          <Notice>{t("COMMON.TRAINER_NO_CERTIFICATE_NOTE")}</Notice>
        </div>
      </section>

      <TrainerBankFields bankOnFile={bankOnFile} />
    </div>
  );
}
