"use client";

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


/**
 * The repeatable social-link rows.
 *
 * A platform already used on another row is filtered out of the remaining\n * dropdowns, so the same network cannot be added twice.
 */
export default function OrganizerSocialSection(props: OrganizerSectionProps) {
  const { t } = useTranslation();
  const selectedLanguage = useLanguageStore((s) => s.language);
  const {
    values,
    errors,
    touched,
    setFieldValue,
    setFieldTouched,
    isSocialMediaTouched,
  } = props;

  return (
    <>
                      {/* Social Media Fields */}
                      <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 - 1 &&
                                  values.socialMedia.length <
                                    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>
    </>
  );
}
