"use client";

import { FieldArray, type FormikErrors, type FormikTouched } from "formik";
import { useTranslation } from "react-i18next";
import { FaMinus, FaPlus } from "react-icons/fa6";
import SelectInput from "@/components/ui/SelectInput";
import type { LearnServeFormValues } from "./learnServeFormTypes";

interface LearnServeSponsorFieldsProps {
  values: LearnServeFormValues;
  errors: FormikErrors<LearnServeFormValues>;
  touched: FormikTouched<LearnServeFormValues>;
  sponsorOptions: Array<{ label: string; value: string }>;
  sponsorsLoading: boolean;
  sponsorsFetching: boolean;
  setFieldValue: (field: string, value: unknown) => void;
  /** Pages the sponsor dropdown as it is scrolled to the bottom. */
  handleMenuScroll: (event: React.UIEvent<HTMLDivElement>) => void;
  setSponsorSearch: (value: string) => void;
  rememberSponsor: (option: { value: string; label: string } | null) => void;
}

/** Optional sponsor picker for free and paid development opportunities. */
export default function LearnServeSponsorFields({
  values,
  errors,
  touched,
  sponsorOptions,
  sponsorsLoading,
  sponsorsFetching,
  setFieldValue,
  handleMenuScroll,
  setSponsorSearch,
  rememberSponsor,
}: LearnServeSponsorFieldsProps) {
  const { t } = useTranslation();

  return (
      <FieldArray name="sponsors">
        {({ push, remove }) => (
          <div className="mb-4">
            {values.sponsors.map((sponsor, index) => (
              <div
                key={index}
                className="flex mobilescreen:flex-col gap-6 uploaddocfiles mb-4 items-center"
              >
                <SelectInput
                  key={sponsor.sponsorId}
                  className="w-full mb-0"
                  name={`sponsors[${index}].sponsorId`}
                  label={t("COMMON.SELECT_SPONSOR")}
                  options={sponsorOptions.filter(
                    (option) =>
                      !values.sponsors.some(
                        (s, i) =>
                          i !== index &&
                          s.sponsorId === option.value
                      )
                  )}
                  onMenuScrollToBottom={handleMenuScroll}
                  isLoading={sponsorsLoading || sponsorsFetching}
                  isSearchable
                  serverFiltered
                  onInputChange={setSponsorSearch}
                  // Sponsors are optional (p.18): the first row has no «−», so
                  // clearing is the only way to remove its sponsor.
                  isClearable
                  onChange={(selectedOption) => {
                    rememberSponsor(selectedOption ?? null);
                    setFieldValue(
                      `sponsors[${index}].sponsorId`,
                      selectedOption?.value || ""
                    );
                  }}
                />
                <div className="flex items-center gap-2">
                  {index === values.sponsors.length - 1 && (
                    <FaPlus
                      size={20}
                      onClick={() =>
                        push({
                          sponsorId: "",
                          position: values.sponsors.length + 1,
                        })
                      }
                      className="text-primary-5 hover:text-primary-6 hover:cursor-pointer"
                    />
                  )}
                  {index > 0 && (
                    <FaMinus
                      onClick={() => remove(index)}
                      className="text-primary-5 hover:text-primary-6 hover:cursor-pointer"
                      size={20}
                    />
                  )}
                </div>
              </div>
            ))}
            {touched.sponsors &&
              typeof errors.sponsors === "string" && (
                <div className="text-red-500 text-sm mt-2">
                  {errors.sponsors}
                </div>
              )}
          </div>
        )}
      </FieldArray>

  );
}
