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

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

  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);
  }, []);

  const toggleInfoModal = () => {
    setIsOpenInfoModal((prev) => !prev);
  };

  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
              className="cdeviceselect-option cdeviceselect-info"
              onClick={toggleInfoModal}
            >
              <span>{t("help.howToStart")}</span>
            </div>
          </div>
        )}
      </div>

      <CInfo isOpen={isOpenInfoModal} onToggle={toggleInfoModal} />
    </>
  );
};

export default CDeviceSelect;
