import React, { useState, useRef, useEffect } from "react";

export default function CustomSelect({
  value,
  name,
  options = [],
  onChange,
  placeholder = "Select",
  isGrouped = false,
}) {
  const [open, setOpen] = useState(false);
  const [search, setSearch] = useState("");
  const [hoverIndex, setHoverIndex] = useState(null);
  const wrapperRef = useRef(null);

  const selectedLabel = isGrouped
    ? options
      .flatMap((group) => group.options || [])
      .find((opt) => opt.value === value)?.label || placeholder
    : options.find((opt) => opt.value === value)?.label || placeholder;

  const filteredOptions = isGrouped
    ? options
      .map((group) => ({
        ...group,
        options: (group.options || []).filter((opt) =>
          (opt.label || "")
            .toLowerCase()
            .includes(search.toLowerCase())
        ),
      }))
      .filter((group) => group.options.length > 0)
    : options.filter((opt) =>
      (opt.label || "")
        .toLowerCase()
        .includes(search.toLowerCase())
    );

  const handleSelect = (val) => {
    onChange({ target: { name, value: val } });
    setOpen(false);
    setSearch("");
  };

  useEffect(() => {
    const handleClickOutside = (e) => {
      if (wrapperRef.current && !wrapperRef.current.contains(e.target)) {
        setOpen(false);
      }
    };

    document.addEventListener("mousedown", handleClickOutside);

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

  return (
    <div
      ref={wrapperRef}
      style={{
        position: "relative",
        fontFamily: "inherit",
      }}
    >
      <div
        onClick={() => setOpen((prev) => !prev)}
        style={{
          padding: "12px 16px",
          borderRadius: "25px",
          background: "#eef2f7",
          border: "none",
          cursor: "pointer",
          fontSize: "14px",
          color: "#333",
          display: "flex",
          alignItems: "center",
          justifyContent: "space-between",
        }}
      >
        <span>{selectedLabel}</span>

        <span
          style={{
            marginLeft: "10px",
            fontSize: "12px",
            color: "#666",
            transform: open ? "rotate(180deg)" : "rotate(0deg)",
            transition: "transform 0.2s ease",
          }}
        >
          ▼
        </span>
      </div>

      {open && (
        <div
          style={{
            position: "absolute",
            width: "100%",
            background: "#fff",
            borderRadius: "12px",
            marginTop: "6px",
            zIndex: 9999,
            maxHeight: "260px",
            overflowY: "auto",
            boxShadow: "0 6px 20px rgba(0,0,0,0.08)",
          }}
        >
          <input
            ref={(el) => {
              if (el) {
                el.style.setProperty("border", "none", "important");
                el.style.setProperty(
                  "border-bottom",
                  "1px solid #cccbcb",
                  "important"
                );
                el.style.setProperty("border-radius", "0", "important");
                el.style.setProperty("box-shadow", "none", "important");
                el.style.setProperty("outline", "none", "important");
              }
            }}
            type="text"
            placeholder="Search..."
            value={search}
            onChange={(e) => setSearch(e.target.value)}
            onClick={(e) => e.stopPropagation()}
            autoFocus
            style={{
              width: "100%",
              padding: "12px 14px",
              fontSize: "14px",
              background: "#f8fafc",
            }}
          />

          {filteredOptions.length > 0 ? (
            isGrouped ? (
              filteredOptions.map((group) => (
                <div key={group.label}>
                  <div
                    style={{
                      padding: "10px 16px",
                      fontSize: "14px",
                      fontWeight: "600",
                      color: "#64748b",
                      background: "#f8fafc",
                      borderBottom: "1px solid #e2e8f0",
                      textAlign: "center",
                    }}
                  >
                    {group.label}
                  </div>

                  {group.options.map((opt, index) => {
                    const hoverKey = `${group.label}-${index}`;

                    return (
                      <div
                        key={opt.value}
                        onClick={() => handleSelect(opt.value)}
                        onMouseEnter={() => setHoverIndex(hoverKey)}
                        onMouseLeave={() => setHoverIndex(null)}
                        style={{
                          padding: "12px 16px",
                          cursor: "pointer",
                          fontSize: "14px",
                          background:
                            hoverIndex === hoverKey
                              ? "#f1f5f9"
                              : "#fff",
                          color: "#333",
                          transition: "all 0.2s ease",
                        }}
                      >
                        {opt.label}
                      </div>
                    );
                  })}
                </div>
              ))
            ) : (
              filteredOptions.map((opt, index) => (
                <div
                  key={opt.value}
                  onClick={() => handleSelect(opt.value)}
                  onMouseEnter={() => setHoverIndex(index)}
                  onMouseLeave={() => setHoverIndex(null)}
                  style={{
                    padding: "12px 16px",
                    cursor: "pointer",
                    fontSize: "14px",
                    background:
                      hoverIndex === index
                        ? "#f1f5f9"
                        : "#fff",
                    color: "#333",
                    transition: "all 0.2s ease",
                  }}
                >
                  {opt.label}
                </div>
              ))
            )
          ) : (
            <div
              style={{
                padding: "12px",
                color: "#999",
                fontSize: "13px",
              }}
            >
              No results found
            </div>
          )}
        </div>
      )}
    </div>
  );
}