"use client";

import React from "react";
import {
  FieldArray,
} from "formik";
import { FaMinus, FaPlus } from "react-icons/fa";
import SelectInput from "@/components/ui/SelectInput";
import type { FormikErrors, FormikProps, FormikTouched } from "formik";
import type { EventFormValues } from "./eventFormTypes";
import type { useEventForm } from "./useEventForm";

/** A field group lifted out of the form of the same family. */
export default function EventSponsorsField({
  screen,
  values,
  errors,
  touched,
  setFieldValue,
}: {
  screen: ReturnType<typeof useEventForm>;
  values: EventFormValues;
  errors: FormikErrors<EventFormValues>;
  touched: FormikTouched<EventFormValues>;
  setFieldValue: FormikProps<EventFormValues>["setFieldValue"];
}) {
  const {
    t,
    sponsorsLoading,
    sponsorsFetching,
    handleMenuScroll,
    sponsorOptions,
    setSponsorSearch,
    rememberSponsor,
    sponsorLabelFor,
  } = screen;

  /*
   * This row's options: the current search results, minus sponsors other rows
   * already took, plus this row's own choice when the results no longer
   * include it — otherwise the select would show it blank.
   */
  const optionsForRow = (index: number) => {
    const taken = values.sponsors
      .filter((_, i) => i !== index)
      .map((s) => s.sponsorId);
    const options = sponsorOptions.filter((option) => !taken.includes(option.value));
    const current = values.sponsors[index]?.sponsorId;
    if (current && !options.some((option) => option.value === current)) {
      const label = sponsorLabelFor(current);
      if (label) options.unshift({ value: current, label });
    }
    return options;
  };

  return (
  <FieldArray name="sponsors">
    {({ push, remove }) => (
      <div>
        {values.sponsors.map((sponsor, index) => (
          <div
            key={index}
            className="flex mobilescreen:flex-col mobilescreen:gap-4 gap-6 mb-4 mobilescreen:mb-0 items-center"
          >
            <SelectInput
              key={sponsor.sponsorId}
              className="w-full mb-0"
              name={`sponsors[${index}].sponsorId`}
              label={t("COMMON.SELECT_SPONSOR")}
              options={optionsForRow(index)}
              onMenuScrollToBottom={handleMenuScroll}
              isLoading={sponsorsLoading || sponsorsFetching}
              isSearchable
              // Sponsors are optional (p.22): the first row has no «−», so
              // clearing is the only way to remove its sponsor.
              isClearable
              serverFiltered
              onInputChange={setSponsorSearch}
              onChange={(selectedOption) => {
                rememberSponsor(selectedOption ?? null);
                setFieldValue(
                  `sponsors[${index}].sponsorId`,
                  selectedOption?.value || ""
                );
              }}
            />
            <div className="flex items-center gap-2 mobilescreen:mb-4">
              {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>
  );
}
