"use client";

import { useField } from "formik";
import { useId, useState } from "react";
import { useSelectMenuPortal, selectMenuPortalStyle } from "./SelectMenuPortal";
import Select, { ActionMeta, SingleValue } from "react-select";
import {
  DropdownIndicator,
  LoadingMessage,
  NoOptionsMessage,
} from "./selectIndicators";
import { useLanguageStore } from "@/store/languageStore";
import { useTranslation } from "react-i18next";
import { cn } from "@/lib/helpers";
import type { ChoiceValue } from "@/lib/choices";

/**
 * One entry of the dropdown.
 *
 * Generic over the value because both conventions are in use: the local
 * constant lists carry string values, while the `/choices/` endpoints carry
 * numeric ids that most callers forward unconverted. The default keeps every
 * existing string call site inferring exactly what it did before.
 */
export type SelectInputOption<V extends ChoiceValue = string> = {
  label: string;
  value: V;
  value_en?: string;
  rawValue?: string;
};

interface SelectInputProps<V extends ChoiceValue = string> {
  name: string;
  label: string;
  options: SelectInputOption<V>[];
  placeholder?: string;
  className?: string;
  isClearable?: boolean;
  disabled?: boolean;
  isModal?: boolean;
  isLoading?: boolean;
  onChange?: (
    option: SingleValue<SelectInputOption<V>>,
    actionMeta: ActionMeta<SelectInputOption<V>>,
  ) => void;
  onInputChange?: (value: string) => void;
  onMenuScrollToBottom?: (e: React.UIEvent<HTMLDivElement>) => void;
  isSearchable?: boolean;
  /**
   * The options are already the server's answer to what was typed, so do not
   * filter them again locally — a match on a field the label does not show
   * (a sponsor's nickname, say) would otherwise be hidden.
   */
  serverFiltered?: boolean;
}

function SelectInput<V extends ChoiceValue = string>({
  name,
  label,
  options,
  disabled = false,
  isClearable = false,
  isModal = false,
  isLoading = false,
  className = "",
  onChange,
  onInputChange,
  onMenuScrollToBottom,
  isSearchable = false,
  serverFiltered = false,
}: SelectInputProps<V>) {
  const [field, meta, helpers] = useField(name);
  const [isFocused, setIsFocused] = useState(false);
  const instanceId = useId(); // stable id: react-select's own counter differs server vs browser (hydration)
  const menuPortalProps = useSelectMenuPortal();
  const selectedLanguage = useLanguageStore((s) => s.language);
  const { t } = useTranslation();

  // Empty-string options such as "All" are still displayed selections.
  const selectedOption =
    options.find((option) => option.value === field.value) ?? null;
  const isLabelRaised = isFocused || selectedOption !== null;


  const handleChange = (
    option: SingleValue<SelectInputOption<V>>,
    actionMeta: ActionMeta<SelectInputOption<V>>,
  ) => {
    helpers.setValue(option ? option.value : "");
    setTimeout(() => {
      helpers.setTouched(true, true);
    }, 0);
    if (onChange) {
      onChange(option, actionMeta);
    }
  };

  const handleBlur = () => {
    setIsFocused(false);
    setTimeout(() => {
      helpers.setTouched(true, true);
    }, 0);
  };

  return (
    <div className={cn("relative w-full mb-4", className)}>
      {label && (
        <label
          htmlFor={name}
          className={`absolute ${
            selectedLanguage === "ar" ? "right-[12px]" : "left-[12px]"
          } pointer-events-none text-primary-5 transition-all duration-200 placeholder-primary-5 z-10
            ${
              isLabelRaised
                ? "text-[10px] leading-[12px] top-[3px] bg-white px-1 text-primary-5/70"
                : "lg:text-base md:text-sm text-sm top-3"
            }
          `}
        >
          {label}
        </label>
      )}

      <Select<SelectInputOption<V>, false>
        inputId={name}
        instanceId={instanceId}
        className={cn(
          "w-full",
          meta.touched && meta.error
            ? "border-red-500"
            : "border-[#29246D1A]/10",
        )}
        {...menuPortalProps}
        options={options}
        value={selectedOption}
        onChange={handleChange}
        onInputChange={(newValue, action) => {
          if (onInputChange && (action.action === "input-change" || action.action === "menu-close")) {
            onInputChange(newValue);
          }
        }}
        onMenuScrollToBottom={(e) => {
          const event = e as unknown as React.UIEvent<HTMLDivElement>;
          if (onMenuScrollToBottom) {
            onMenuScrollToBottom(event);
          }
        }}
        onFocus={() => setIsFocused(true)}
        onBlur={handleBlur}
        isClearable={isClearable}
        isDisabled={disabled}
        isLoading={isLoading}
        loadingMessage={() => t("COMMON.LOADING") || "Loading..."}
        noOptionsMessage={() =>
          isLoading
            ? t("COMMON.LOADING") || "Loading..."
            : t("COMMON.NO_DATA") || "No options"
        }
        placeholder={isSearchable && isFocused ? t("COMMON.SEARCH") : ""}
        name={name}
        components={{ DropdownIndicator, LoadingMessage, NoOptionsMessage }}
        styles={{
          menuPortal: selectMenuPortalStyle,
          control: (base) => ({
            ...base,
            borderRadius: "1rem",
            border: `1px solid ${
              meta.touched && meta.error ? "#ef4444" : "rgba(41, 36, 109, 0.1)"
            }`,
            backgroundColor: "rgba(41, 36, 109, 0.03)",
            height: "48px",
            paddingLeft: "0.75rem",
            paddingRight: "0.75rem",
            boxShadow: "none",
            "&:hover": {
              border: `1px solid ${
                meta.touched && meta.error
                  ? "#ef4444"
                  : "rgba(41, 36, 109, 0.1)"
              }`,
            },
            minHeight: "48px",
          }),
          valueContainer: (base) => ({
            ...base,
            padding: label && isLabelRaised ? "14px 0 6px" : "0",
            height: "100%",
          }),
          input: (base) => ({
            ...base,
            margin: 0,
            padding: 0,
            lineHeight: "20px",
          }),
          singleValue: (base) => ({
            ...base,
            lineHeight: "20px",
            color: isModal ? "#535151" : "#29246D",
          }),
          placeholder: (base) => ({
            ...base,
            color: isModal ? "#535151" : "#29246D",
          }),
          menu: (base) => ({
            ...base,
            zIndex: 9999,
          }),
        }}
        isSearchable={isSearchable}
        filterOption={serverFiltered ? () => true : undefined}
      />

      {meta.touched && meta.error && (
        <div className="text-red-500 text-sm mt-1">{meta.error}</div>
      )}
    </div>
  );
}

export default SelectInput;
export { SelectInput };
