"use client";

import { useTranslation } from "react-i18next";
import Input from "@/components/ui/Input";
import SelectInput from "@/components/ui/SelectInput";
import LearnServeAudienceFields from "./LearnServeAudienceFields";
import LearnServeScheduleFields from "./LearnServeScheduleFields";
import { LearnServeFormValues } from "./learnServeFormTypes";
import { LearnServeOptions } from "./useLearnServeOptions";

interface LearnServeFieldGridProps {
  values: LearnServeFormValues;
  setFieldValue: (field: string, value: unknown) => void;
  setFieldTouched: (field: string, touched: boolean) => void;

  /** Whether the optional English title input is showing. */
  showEnglishTitle: boolean;
  onAddEnglishTitle: () => void;
  onRemoveEnglishTitle: () => void;

  /** Course or internship — the two types that carry a certificate. */
  isInternshipOrCourse: boolean;
  isOnline: boolean;
  /** This account may charge *and* this type is chargeable. */
  canBePaid: boolean;
  isPaid: boolean;
  /** Clicking a time field opens the picker rather than typing into it. */
  autoSetTimeOnClick: boolean;

  /**
   * The whole dropdown layer. Passed as one prop because the grid forwards all
   * of it: the lists to the selects, and the master-choice ids to the handlers
   * that clear a field which no longer applies — an internship cannot be paid,
   * an online opportunity has no address, an in-person one has no meeting link.
   */
  options: LearnServeOptions;
  /** The platform's cut, shown under the price field. */
  platformFeePercent: number | null;
}

/**
 * The four-column field grid at the top of the development-opportunity form.
 *
 * Reads, left to right and top to bottom:
 *   1. what it is · 2. when it runs · 3. who it is for · 4. terms
 *
 * The pairs that read as one answer — age from/to and time from/to — each
 * occupy a single column, which is what keeps the rows four wide. "Where" sits
 * below the grid rather than in it, because the map picker is far taller than a
 * field and would set the height of its whole row.
 *
 * Presentation only: every conditional it renders is decided by the caller and
 * arrives as a prop, so the rules stay in one place in `LearnServeForm`.
 */
export default function LearnServeFieldGrid({
  values,
  setFieldValue,
  setFieldTouched,
  isInternshipOrCourse,
  isOnline,
  canBePaid,
  isPaid,
  autoSetTimeOnClick,
  platformFeePercent,
  options,
}: LearnServeFieldGridProps) {
  const { t } = useTranslation();
  const {
    learningTypeOptions,
    learningTypeLoading,
    learnServeFormatOptions,
    learnServeFormatLoading,
    genderOptions,
    genderLoading,
    certificateTypeOptions,
    certificateTypeLoading,
    internshipTypeId,
    inPersonFormatId,
    onlineFormatId,
    forsaCertificateId,
  } = options;

  return (
                    <div className="grid grid-cols-1 gap-x-6 md:grid-cols-2 lg:grid-cols-4">
                      {/* ---- Row 1: what it is ---- */}
                      <div>
                        <Input
                          name="title_ar"
                          label={t("COMMON.ENTER_TITLE")}
                          type="text"
                          maxLength={255}
                          dir="auto"
                          onFocus={() => setFieldTouched("title_ar", true)}
                        />
                      </div>

                      <Input name="title_en" label={t("COMMON.ENTER_TITLE_EN")} type="text" maxLength={255} dir="ltr" onFocus={() => setFieldTouched("title_en", true)} />

                      <div>
                      <SelectInput
                        name="learningType"
                        label={t("COMMON.TYPE")}
                        options={learningTypeOptions}
                        onChange={(selectedOption) => {
                          const nextType = selectedOption?.value || "";
                          setFieldValue("learningType", nextType);
                          // Internships are always free: drop a paid answer
                          // rather than leave it hidden behind the switch.
                          if (internshipTypeId && nextType === internshipTypeId) {
                            setFieldValue("is_paid", "false");
                            setFieldValue("price", "");
                            setFieldTouched("price", false);
                          }
                        }}
                        // The type is fixed once an opportunity is reposted
                        disabled={learningTypeLoading || values.paymentTermsLocked}
                      />
                        {internshipTypeId && String(values.learningType) === String(internshipTypeId) && (
                          <p className="-mt-3 mb-4 text-sm text-secondary-102">
                            {t("COMMON.INTERNSHIP_FREE_HINT")}
                          </p>
                        )}
                      </div>

                      <SelectInput
                        name="learnServeFormat"
                        label={t("COMMON.FORMAT")}
                        options={learnServeFormatOptions}
                        onChange={(selectedOption) => {
                          const selectedId = selectedOption?.value || "";
                          setFieldValue("learnServeFormat", selectedId);
                          // Switching format clears the field that no longer applies
                          if (selectedId === inPersonFormatId) {
                            setFieldValue("meetingLink", "");
                            setFieldTouched("meetingLink", false);
                          } else if (selectedId === onlineFormatId) {
                            setFieldValue("location", "");
                            setFieldTouched("location", false);
                          }
                        }}
                        disabled={learnServeFormatLoading}
                      />

                      <Input
                        name="participantsNeeded"
                        label={t("COMMON.PARTICIPANTS_NEEDED")}
                        type="text"
                      />

                      <LearnServeScheduleFields
                        autoSetTimeOnClick={autoSetTimeOnClick}
                      />

                      <LearnServeAudienceFields
                        values={values}
                        setFieldValue={setFieldValue}
                        setFieldTouched={setFieldTouched}
                        genderOptions={genderOptions}
                        genderLoading={genderLoading}
                        certificateTypeOptions={certificateTypeOptions}
                        certificateTypeLoading={certificateTypeLoading}
                        canBePaid={canBePaid}
                        isPaid={isPaid}
                        isInternshipOrCourse={isInternshipOrCourse}
                        isOnline={isOnline}
                        platformFeePercent={platformFeePercent}
                        forsaCertificateId={forsaCertificateId}
                      />
                    </div>
  );
}
