import React, { useEffect, useRef, useState } from "react";
import "./CDeviceSelect.css";
import type { CDeviceSelectProps } from "./CDeviceSelect.types";
import { FaChevronDown, FaChevronUp } from "react-icons/fa";

const CDeviceSelect: React.FC<CDeviceSelectProps> = ({
  devices,
  selectedDevice,
  onDeviceChange,
  disabled,
  style,
  className,
  placeholder = "Select Device",
}) => {
  const [open, setOpen] = useState(false);
  const ref = useRef<HTMLDivElement>(null);

  useEffect(() => {
    const handleClickOutside = (e: MouseEvent) => {
      if (ref.current && !ref.current.contains(e.target as Node)) {
        setOpen(false);
      }
    };
    document.addEventListener("mousedown", handleClickOutside);
    return () => document.removeEventListener("mousedown", handleClickOutside);
  }, []);

  return (
    <>
      <div
        ref={ref}
        className={`cdeviceselect-container ${className || ""} ${
          disabled ? "cdeviceselect-disabled" : ""
        }`}
        style={style}
        onClick={() => !disabled && setOpen(!open)}
      >
        <div className="cdeviceselect-selected">
          <span>{selectedDevice?.name || placeholder}</span>
          <span className="cdeviceselect-arrow">
            {open ? <FaChevronUp /> : <FaChevronDown />}
          </span>
        </div>

        {open && (
          <div className="cdeviceselect-dropdown">
            {devices.map((device) => (
              <div
                key={device.id}
                className={`cdeviceselect-option ${
                  device.name === selectedDevice?.name ? "selected" : ""
                }`}
                onClick={(e) => {
                  e.stopPropagation();
                  onDeviceChange?.(device.id);
                  setOpen(false);
                }}
              >
                <span>{device.name}</span>
              </div>
            ))}
          </div>
        )}
      </div>
    </>
  );
};

export default CDeviceSelect;
