import { faChevronDown } from "@fortawesome/free-solid-svg-icons";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import React, { useState, useRef, useEffect } from "react";
import { createPopper } from "@popperjs/core";

const normalizeOptions = (options) => {
  if (!Array.isArray(options)) return [];

  return options.map((option) => {
    // If option already has correct format, return as is
    if (option.value !== undefined && option.label !== undefined) {
      return option;
    }

    // If option is an object with id and name, map them specifically
    if (typeof option === "object" && option !== null) {
      const normalized = {
        value: option.id?.toString() || "",
        label: option.name || "",
      };

      return normalized;
    }

    // If option is primitive (string/number)
    return {
      value: option?.toString() || "",
      label: option?.toString() || "",
    };
  });
};

const CustomSelect2 = ({
  options = [],
  label = "Dropdown Button",
  register,
  name,
  defaultValue,
  className = "",
  value,
  onChange,
  position = "down",
  dropdownRef = null,
  onChange2 = null,
  children,
  disabled = false,
  textClass = "",
}) => {
  const buttonRef = useRef(null);
  const dropdownListRef = useRef(null);
  const [isOpen, setIsOpen] = useState(false);
  const [selectedOption, setSelectedOption] = useState(null);

  useEffect(() => {
    if (isOpen && buttonRef.current && dropdownListRef.current) {
      const popper = createPopper(buttonRef.current, dropdownListRef.current, {
        placement: position === "down" ? "bottom-start" : "top-start",
        modifiers: [
          {
            name: "offset",
            options: {
              offset: [0, 4], // [x-offset, y-offset]
            },
          },
          {
            name: "preventOverflow",
            options: {
              padding: 8,
              boundary: "viewport",
            },
          },
          {
            name: "flip",
            options: {
              fallbackPlacements: ["top-start", "bottom-start"],
            },
          },
        ],
      });

      return () => {
        popper.destroy();
      };
    }
  }, [isOpen, position]);

  useEffect(() => {
    const handleClickOutside = (event) => {
      if (
        buttonRef.current &&
        !buttonRef.current.contains(event.target) &&
        dropdownListRef.current &&
        !dropdownListRef.current.contains(event.target)
      ) {
        setIsOpen(false);
      }
    };

    document.addEventListener("mousedown", handleClickOutside);
    return () => document.removeEventListener("mousedown", handleClickOutside);
  }, []);

  const handleOptionClick = (option) => {
    setSelectedOption(option);

    if (!register) {
      onChange(option.value);
    } else if (register) {
      const event = new Event("change", { bubbles: true });
      const select = document.querySelector(`select[name="${name}"]`);

      select.value = option.value;
      onChange2 && onChange2(option.value);
      select.dispatchEvent(event);
    }
    setIsOpen(false);
  };

  const parseOptionsFromChildren = () => {
    if (!children) return [];

    return React.Children.map(children, (child) => {
      if (child?.type === "option") {
        return {
          value: child.props.value,
          label: child.props.children,
        };
      }
      return null;
    }).filter(Boolean);
  };

  const finalOptions =
    options.length > 0 ? normalizeOptions(options) : parseOptionsFromChildren();

  const selectedLabel =
    finalOptions.find((elem) => elem.value == value)?.label ||
    finalOptions.find((elem) => elem.value == defaultValue)?.label ||
    selectedOption?.label ||
    null;

  const displayLabel = selectedLabel || label;

  return (
    <div className="relative w-full">
      <button
        ref={buttonRef}
        type="button"
        className={`flex w-full items-center justify-between gap-2 rounded border border-form-strokedark bg-form-input px-3 py-2 text-sm outline-none transition ${className}`}
        disabled={disabled}
        onClick={() => setIsOpen(!isOpen)}
      >
        <span
          className={`truncate whitespace-nowrap text-sm font-medium ${
            displayLabel === label
              ? "!text-base !font-normal text-bodydark2"
              : "text-white"
          } ${textClass}`}
        >
          {displayLabel}
        </span>
        <span
          className={`transition-transform duration-200 ${
            isOpen ? "rotate-180" : ""
          }`}
        >
          <FontAwesomeIcon icon={faChevronDown} />
        </span>
      </button>

      {register && (
        <select
          {...register(name)}
          className="sr-only"
          defaultValue={defaultValue || value}
        >
          {finalOptions.map((option, index) => (
            <option key={index} value={option.value}>
              {option.label}
            </option>
          ))}
        </select>
      )}

      {isOpen && (
        <div
          ref={dropdownListRef}
          className="z-[9999] min-w-[150px] overflow-hidden rounded border border-form-strokedark bg-form-input shadow-lg"
          style={{
            position: "fixed", // Changed from absolute to fixed
            width: buttonRef.current?.offsetWidth + "px", // Match button width
          }}
        >
          <div className="custom-overflow max-h-[300px] overflow-y-auto">
            {finalOptions.map((option, index) => (
              <div
                key={index}
                className="flex cursor-pointer gap-1 px-4 py-2 text-bodydark2 transition-colors duration-200 hover:bg-primary/5 hover:text-white"
                onClick={() => handleOptionClick(option)}
              >
                {option.label}
              </div>
            ))}
          </div>
        </div>
      )}
    </div>
  );
};

export default CustomSelect2;
