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

const normalizeOptions = (options) => {
  console.log("Input to 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 || "",
      };
      console.log("Normalized option:", normalized);
      return normalized;
    }

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

const CustomSelect = ({
  options,
  label = "Dropdown Button",
  register, // Optional register prop
  name, // Name prop for register/onChange
  defaultValue = "",
  className = "h-[36px]",
  value, // New prop for controlled components
  onChange, // New prop for onChange handler
  position = "down",
  dropdownRef = null,
  onChange2 = null,
}) => {
  console.log(value, "value");
  console.log(options, "options");
  const [isOpen, setIsOpen] = useState(false);

  console.log(options, "skksi");
  const normalizedOptions = normalizeOptions(options);
  console.log(normalizedOptions, "normalizedOptions");
  const [selectedOption, setSelectedOption] = useState(null);
  const displayLabel = selectedOption ? selectedOption.label : label;
  console.log(normalizedOptions, "sjjs");
  console.log(selectedOption, "selectedOption");

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

    if (!register) {
      // For onChange pattern
      console.log("dnnd");
      console.log(option.value, "option.value");
      onChange(option.value);
    } else if (register) {
      // For React Hook Form pattern
      const event = new Event("change", { bubbles: true });
      const select = document.querySelector(`select[name="${name}"]`);
      console.log(select, "select");
      onChange2 && onChange2(option.value);
      select.value = option.value;
      select.dispatchEvent(event);
    }
    setIsOpen(false);
  };
  useEffect(() => {
    const handleClickOutside = (event) => {
      if (dropdownRef.current && !dropdownRef.current.contains(event.target)) {
        setIsOpen(false);
      }
    };

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

  // Create a hidden select element for form handling
  return (
    <div className="relative w-full" ref={dropdownRef}>
      <button
        type="button" // Important: prevent form submission
        className={`flex w-full items-center justify-between gap-2 rounded border border-form-strokedark bg-form-input px-4 py-2 text-sm text-white ${className}`}
        onClick={() => setIsOpen(!isOpen)}
      >
        <span
          className={` truncate whitespace-nowrap text-sm font-medium ${
            label == displayLabel ? "text-bodydark2" : "text-white"
          }`}
        >
          {value ? selectedOption?.label : displayLabel}
        </span>
        <span
          className={`transition-transform duration-200 ${
            isOpen ? "rotate-180" : ""
          }`}
        >
          <FontAwesomeIcon icon={faChevronDown} />
        </span>
      </button>

      {/* Hidden select element for React Hook Form */}
      {register && (
        <select
          {...register(name)}
          className="sr-only" // Hide the actual select element
          defaultValue={defaultValue}
        >
          <option value="">Select {label}</option>
          {normalizedOptions.map((option, index) => (
            <option key={index} value={option.value}>
              {option.label}
            </option>
          ))}
        </select>
      )}

      {isOpen && (
        <div
          className={`absolute ${
            position === "down" ? "top-full" : "bottom-full"
          } custom-overflow left-0 right-0 z-50 mt-1  max-h-[300px] overflow-hidden overflow-y-auto rounded rounded-md border border-form-strokedark bg-form-input shadow-lg`}
        >
          {normalizedOptions.map((option, index) => (
            <div
              key={index}
              className="cursor-pointer px-4 py-2 text-bodydark2 transition-colors duration-200 hover:bg-primary/5 hover:text-white"
              onClick={() => {
                handleOptionClick(option);

                setIsOpen(false);
              }}
            >
              {option.label}
            </div>
          ))}
        </div>
      )}
    </div>
  );
};

export default CustomSelect;
