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

const CSelect: React.FC<CSelectProps> = ({
  options,
  value,
  onChange,
  disabled,
  variant,
  style,
  className,
  placeholder = "Select...",
}) => {
  const [open, setOpen] = useState(false);
  const ref = useRef<HTMLDivElement>(null);

  const selected = options.find((opt) => opt.value === value);

  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={`cselect-container ${variant ? `cselect-${variant}` : ""} ${
        className || ""
      } ${disabled ? "cselect-disabled" : ""}`}
      style={style}
      onClick={() => !disabled && setOpen(!open)}
    >
      <div className="cselect-selected">
        {selected?.image && <div className="cselect-img">{selected.image}</div>}
        <span>{selected?.label || placeholder}</span>
        <span className="cselect-arrow">
          {open ? <FaChevronUp /> : <FaChevronDown />}
        </span>
      </div>

      {open && (
        <div className="cselect-dropdown">
          {options.map((opt) => (
            <div
              key={opt.value}
              className={`cselect-option ${
                opt.value === value ? "selected" : ""
              }`}
              onClick={(e) => {
                e.stopPropagation();
                onChange?.(opt.value);
                setOpen(false);
              }}
            >
              {opt.image && <div className="cselect-img">{opt.image}</div>}
              <span>{opt.label}</span>
            </div>
          ))}
        </div>
      )}
    </div>
  );
};

export default CSelect;
