"use client";

import { useState } from "react";
import { useSelectMenuPortal, selectMenuPortalStyle } from "./SelectMenuPortal";
import { useField } from "formik";
import Select, { ActionMeta, SingleValue } from "react-select";
import { DropdownIndicator } from "./selectIndicators";

import { cn } from "@/lib/helpers";
import { useLanguageStore } from "@/store/languageStore";

// Define option types for flat and grouped options
export interface Option {
  label: string;
  value: string;
  value_en?: string;
}

export interface GroupedOption {
  label: string;
  options: Option[];
}

interface GroupedSelectInputProps {
  name: string;
  label: string;
  options: (Option | GroupedOption)[];
  placeholder?: string;
  className?: string;
  isClearable?: boolean;
  disabled?: boolean;
  isModal?: boolean;
  onChange?: (
    option: SingleValue<Option>,
    actionMeta: ActionMeta<Option>,
  ) => void;
  onInputChange?: (value: string) => void;
  onMenuScrollToBottom?: (e: React.UIEvent<HTMLDivElement>) => void;
  isSearchable?: boolean;
}

const GroupedSelectInput: React.FC<GroupedSelectInputProps> = ({
  name,
  label,
  options,
  disabled = false,
  isClearable = false,
  isModal = false,
  className = "",
  onChange,
  onInputChange,
  onMenuScrollToBottom,
  isSearchable = false,
}) => {
  const [field, meta, helpers] = useField(name);
  const [isFocused, setIsFocused] = useState(false);
  const menuPortalProps = useSelectMenuPortal();
  const selectedLanguage = useLanguageStore((s) => s.language);

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

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

  // Find the selected option with defensive checks
  const selectedOption =
    options
      .filter((item): item is Option | GroupedOption => !!item)
      .flatMap((item) =>
        "options" in item && Array.isArray(item.options)
          ? item.options
          : [item],
      )
      .find(
        (option): option is Option =>
          "value" in option && option.value === field.value,
      ) || null;

  const isLabelRaised = isFocused || selectedOption !== null;

  return (
    <div className={cn("relative w-full mb-4", className)}>
      {label && (
        <label
          htmlFor={name}
          className={`absolute ${
            selectedLanguage === "ar" ? "right-[12px]" : "left-[12px]"
          } text-primary-5 transition-all duration-200 placeholder-primary-5
            ${
              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<Option, false, GroupedOption>
        className={cn(
          "w-full current-status",
          meta.touched && meta.error
            ? "border-red-500"
            : "border-[#29246D1A]/10",
        )}
        {...menuPortalProps}
        options={options}
        value={selectedOption}
        onChange={handleChange}
        onInputChange={(newValue) => onInputChange?.(newValue)}
        onMenuScrollToBottom={(e) =>
          onMenuScrollToBottom?.(e as unknown as React.UIEvent<HTMLDivElement>)
        }
        onFocus={() => setIsFocused(true)}
        onBlur={handleBlur}
        isClearable={isClearable}
        isDisabled={disabled}
        placeholder=""
        name={name}
        instanceId={name}
        // Gives the search input the id the floating <label htmlFor> points at.
        inputId={name}
        isRtl={selectedLanguage === "ar"}
        components={{ DropdownIndicator }}
        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}
      />

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

export default GroupedSelectInput;
