"use client";

import { FieldArray } from "formik";
import { useTranslation } from "react-i18next";
import { FaPlus } from "react-icons/fa6";
import Input from "@/components/ui/Input";
import SelectInput from "@/components/ui/SelectInput";
import { socialMediaOptions } from "@/data/Constants";
import { useLanguageStore } from "@/store/languageStore";
import {
  socialRowError,
  socialRowTouched,
} from "@/features/profile/socialMediaRows";
import type { FormikErrors, FormikProps, FormikTouched } from "formik";
import { type CombinedFormValues } from "./volunteerAccountTypes";

interface VolunteerSocialLinksFieldProps {
  values: CombinedFormValues;
  errors: FormikErrors<CombinedFormValues>;
  touched: FormikTouched<CombinedFormValues>;
  setFieldValue: FormikProps<CombinedFormValues>["setFieldValue"];
  setFieldTouched: FormikProps<CombinedFormValues>["setFieldTouched"];
  isSocialMediaTouched: boolean;
}

/**
 * The repeatable social-link rows.
 *
 * A platform already used on another row is filtered out of the remaining
 * dropdowns, so the same network cannot be added twice — which is why the option
 * list is computed per row rather than once.
 */
export default function VolunteerSocialLinksField({
  values,
  errors,
  touched,
  setFieldValue,
  setFieldTouched,
  isSocialMediaTouched,
}: VolunteerSocialLinksFieldProps) {
  const { t } = useTranslation();
  const selectedLanguage = useLanguageStore((s) => s.language);

  return (
                    <FieldArray name="socialMedia">
                      {({ push, remove }) => (
                        <>
                          {values.socialMedia?.map((_: unknown, index: number) => {
                            const rowError = socialRowError(
                              errors.socialMedia,
                              index
                            );
                            const rowTouched = socialRowTouched(
                              touched.socialMedia,
                              index
                            );
                            const hasRowError =
                              !!(rowError?.platform || rowError?.link);

                            return (
                              <div
                                key={`social-media-${index}`}
                                className={`flex mobilescreen:flex-col gap-4 mobilescreen:gap-[0px] selectfiled items-center ${
                                  hasRowError ? "mb-1" : ""
                                }`}
                              >
                                <div className="w-full relative">
                                  <SelectInput
                                    name={`socialMedia[${index}].platform`}
                                    label={t("COMMON.SOCIAL.MEDIA")}
                                    isClearable
                                    options={socialMediaOptions
                                      .filter(
                                        (option) =>
                                          !(values.socialMedia ?? []).some(
                                            (sm: { platform?: string }, i: number) =>
                                              i !== index &&
                                              sm.platform === option.value
                                          )
                                      )
                                      .map((option) => ({
                                        label:
                                          selectedLanguage === "ar"
                                            ? option.name_ar
                                            : option.name_en,
                                        value: option.value,
                                      }))}
                                    onChange={(selectedOption) => {
                                      const newPlatform =
                                        selectedOption?.value || "";
                                      setFieldValue(
                                        `socialMedia[${index}].platform`,
                                        newPlatform
                                      );
                                      setFieldTouched(
                                        `socialMedia[${index}].platform`,
                                        true
                                      );

                                      if (!newPlatform) {
                                        if (
                                          values.socialMedia &&
                                          values.socialMedia.length > 1
                                        ) {
                                          remove(index);
                                        } else {
                                          setFieldValue(
                                            `socialMedia[${index}]`,
                                            { platform: "", link: "" }
                                          );
                                        }
                                      }
                                    }}
                                  />
                                  {rowTouched?.platform && rowError?.platform && (
                                      <div className="text-red-500 text-sm absolute -bottom-5 start-0">
                                        {rowError.platform}
                                      </div>
                                    )}
                                </div>

                                <div className="w-full relative">
                                  <Input
                                    name={`socialMedia[${index}].link`}
                                    type="text"
                                    label={t("COMMON.ENTER.LINK")}
                                    hideError
                                    onChange={(e) => {
                                      setFieldValue(
                                        `socialMedia[${index}].link`,
                                        e.target.value
                                      );
                                      setFieldTouched(
                                        `socialMedia[${index}].link`,
                                        true
                                      );
                                    }}
                                    onBlur={() =>
                                      setFieldTouched(
                                        `socialMedia[${index}].link`,
                                        true
                                      )
                                    }
                                    className="h-[48px]"
                                  />
                                  {rowTouched?.link && rowError?.link && (
                                      <div className="text-red-500 text-sm absolute -bottom-1 start-1">
                                        {rowError.link}
                                      </div>
                                    )}
                                </div>

                                {index ===
                                  (values.socialMedia?.length ?? 0) - 1 &&
                                (values.socialMedia?.length ?? 0) <
                                  socialMediaOptions.length ? (
                                  <div className="flex justify-center items-center h-[48px] mt-0 mobilescreen:mt-0 w-[40px] pb-[13px]">
                                    <FaPlus
                                      size={20}
                                      onClick={() =>
                                        push({ platform: "", link: "" })
                                      }
                                      className="text-[#29246d] hover:cursor-pointer"
                                    />
                                  </div>
                                ) : (
                                  <div className="w-[40px]" />
                                )}
                              </div>
                            );
                          })}
                          {isSocialMediaTouched &&
                            typeof errors.socialMedia === "string" && (
                              <div className="text-red-500 text-sm mt-2">
                                {errors.socialMedia}
                              </div>
                            )}
                        </>
                      )}
                    </FieldArray>
  );
}
