"use client";

import { useTranslation } from "react-i18next";
import Input from "@/components/ui/Input";
import SelectInput from "@/components/ui/SelectInput";
import AgeRange from "@/components/ui/AgeRange";
import LearnServeCertificateFields from "./LearnServeCertificateFields";
import PayoutBankFields from "./PayoutBankFields";
import type { LearnServeFormValues } from "./learnServeFormTypes";

type Option = { label: string; value: string };

interface LearnServeAudienceFieldsProps {
  values: LearnServeFormValues;
  setFieldValue: (field: string, value: unknown) => void;
  setFieldTouched: (field: string, touched: boolean) => void;
  genderOptions: Option[];
  genderLoading: boolean;
  certificateTypeOptions: Option[];
  certificateTypeLoading: boolean;
  /** This account may charge *and* this type is chargeable. */
  canBePaid: boolean;
  isPaid: boolean;
  /** Course or internship — the two types that carry a certificate. */
  isInternshipOrCourse: boolean;
  /** The meeting link exists only for an online opportunity. */
  isOnline: boolean;
  /** The platform's cut, shown under the price field. */
  platformFeePercent: number | null;
  forsaCertificateId?: string;
}

/**
 * Columns 3 and 4 of the field grid: who the opportunity is for, how to reach
 * it, and its terms — price, certificate and nationality.
 *
 * Rendered as fragments so it stays inside the parent's four-column grid
 * rather than nesting a second one.
 */
export default function LearnServeAudienceFields({
  values,
  setFieldValue,
  setFieldTouched,
  genderOptions,
  genderLoading,
  certificateTypeOptions,
  certificateTypeLoading,
  canBePaid,
  isPaid,
  isInternshipOrCourse,
  isOnline,
  platformFeePercent,
  forsaCertificateId,
}: LearnServeAudienceFieldsProps) {
  const { t } = useTranslation();

  return (
    <>
    {/* ---- Row 3: who it is for, and how to reach it ---- */}
    <div className="min-w-0">
      <AgeRange name="age" label={t("COMMON.AGE")} />
      <p className="-mt-2 mb-4 text-xs text-secondary-102">
        {t("COMMON.MAXIMUM_AGE_OPTIONAL_HINT")}
      </p>
    </div>
    <SelectInput
      name="gender"
      label={t("COMMON.GENDER")}
      options={genderOptions}
      onChange={(selectedOption) =>
        setFieldValue("gender", selectedOption?.value || "")
      }
      disabled={genderLoading}
    />
    {/* Online only (client, 2026-10-15) — an in-person opportunity
        gives its place in the location block below the grid instead, and
        `buildLearnServePayload` sends `link` for online alone. */}
    {isOnline && (
      <Input
        name="meetingLink"
        label={t("COMMON.MEETING.LINK")}
        type="text"
      />
    )}
    {/*
      BE-65 — the opportunity's own WhatsApp contact, and not
      the same thing as the meeting link beside it: this one
      is shown to everyone, while the meeting link is revealed
      only to registered participants. A WhatsApp contact is required
      for both in-person and online opportunities.
    */}
    <Input
      name="whatsappLink"
      label={t("COMMON.WHATSAPP_LINK")}
      type="text"
    />

    {/* ---- Row 4: terms ---- */}
    {/*
      Was a checkbox. A select states both answers on screen,
      which a lone unchecked box does not — "free" was only
      ever implied by the absence of a tick. Unlike the
      certificate and nationality fields below it, this one
      applies to every learn-and-serve format.
    */}
    {/* Hidden where only "free" is allowed: internships, and
        every volunteer team (`lib/publishPermissions.ts`). */}
    {canBePaid && (
      <SelectInput
        name="is_paid"
        disabled={values.paymentTermsLocked}
        label={t("COMMON.PAID_OR_FREE")}
        options={[
          {
            label: t("COMMON.FREE_OPPORTUNITY"),
            value: "false",
          },
          {
            label: t("COMMON.PAID_OPPORTUNITY"),
            value: "true",
          },
        ]}
        onChange={(selectedOption) => {
          const nextIsPaid = selectedOption?.value === "true";
          setFieldValue("is_paid", String(nextIsPaid));
          if (!nextIsPaid) {
            // Clear as well as hide: a price left behind a
            // collapsed field would still be validated.
            setFieldValue("price", "");
            setFieldTouched("price", false);
          }
        }}
      />
    )}

    {isPaid && (
      <div>
        <Input
          name="price"
          readOnly={values.paymentTermsLocked}
          label={`${t("COMMON.PRICE")} (${t(
            "COMMON.CURRENCY_KWD"
          )})`}
          type="text"
          inputMode="decimal"
          onFocus={() => setFieldTouched("price", true)}
        />
        {/* Live on both paths now — see `platformFeePercent`. */}
        {platformFeePercent !== null && <p className="-mt-2 mb-4 text-xs text-secondary-102">
          {t("COMMON.PLATFORM_FEE_HINT", {
            percent: platformFeePercent,
          })}
        </p>}
      </div>
    )}
    {isPaid && (
      <PayoutBankFields
        values={values}
        setFieldValue={setFieldValue}
        setFieldTouched={setFieldTouched}
        platformFeePercent={platformFeePercent}
      />
    )}

      {isInternshipOrCourse && (
        <LearnServeCertificateFields
          values={values}
          setFieldValue={setFieldValue}
          certificateTypeOptions={certificateTypeOptions}
          certificateTypeLoading={certificateTypeLoading}
          forsaCertificateId={forsaCertificateId}
        />
      )}
    </>
  );
}
