import React, { useEffect, useRef, useState } from "react";
import Label from "../Label";
import { useDebounce } from "../../../utils/appUtils";
import { useEmployeesName } from "../../../hooks/useEmployees";

const SelectEmployeeServerSide = ({
  label = "Select",
  placeholder = "Select Employee",
  required = false,
  value = null,
  onChange,
  valueKey = "id",
  isFullObject = false,
  isMultiple = false,
  projectId = null,
  isAllEmployee = false,
}) => {
  const [searchText, setSearchText] = useState("");
  const debounce = useDebounce(searchText, 300);

  const { data, isLoading } = useEmployeesName(
    projectId,
    debounce,
    isAllEmployee
  );

  const options = data?.data ?? [];
  const [open, setOpen] = useState(false);
  const dropdownRef = useRef(null);

  const getDisplayName = (emp) => {
    if (!emp) return "";
    return `${emp.firstName || ""} ${emp.lastName || ""}`.trim();
  };

  /** -----------------------------
   * SELECTED OPTION (SINGLE)
   * ----------------------------- */
  let selectedSingle = null;

  if (!isMultiple) {
    if (isFullObject && value) selectedSingle = value;
    else if (!isFullObject && value)
      selectedSingle = options.find((o) => o[valueKey] === value);
  }

  /** -----------------------------
   * SELECTED OPTION (MULTIPLE)
   * ----------------------------- */
  let selectedList = [];

  if (isMultiple && Array.isArray(value)) {
    if (isFullObject) selectedList = value;
    else {
      selectedList = options.filter((opt) => value.includes(opt[valueKey]));
    }
  }

  /** Main button label */
  const displayText = !isMultiple
    ? getDisplayName(selectedSingle) || placeholder
    : selectedList.length > 0
    ? selectedList.map((e) => getDisplayName(e)).join(", ")
    : placeholder;

  /** -----------------------------
   * HANDLE OUTSIDE CLICK
   * ----------------------------- */
  useEffect(() => {
    const handleClickOutside = (e) => {
      if (dropdownRef.current && !dropdownRef.current.contains(e.target)) {
        setOpen(false);
      }
    };

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

  /** -----------------------------
   * HANDLE SELECT
   * ----------------------------- */
  const handleSelect = (option) => {
    if (!isMultiple) {
      // SINGLE SELECT
      if (isFullObject) onChange(option);
      else onChange(option[valueKey]);
    } else {
      // MULTIPLE SELECT
      let updated = [];

      const exists = selectedList.some((e) => e[valueKey] === option[valueKey]);

      if (exists) {
        // remove
        updated = selectedList.filter((e) => e[valueKey] !== option[valueKey]);
      } else {
        // add
        updated = [...selectedList, option];
      }

      if (isFullObject) onChange(updated);
      else onChange(updated.map((x) => x[valueKey]));
    }
  };

  return (
    <div className="mb-3 position-relative" ref={dropdownRef}>
      {label && (
        <Label className="form-label" required={required}>
          {label}
        </Label>
      )}

      {/* MAIN BUTTON */}
      <button
        type="button"
        className={`select2-icons form-select d-flex align-items-center justify-content-between ${
          open ? "show" : ""
        }`}
        onClick={() => setOpen((prev) => !prev)}
      >
        <span className={`text-truncate ${!displayText ? "text-muted" : ""}`}>
          {displayText}
        </span>
      </button>

      {/* DROPDOWN */}
      {open && (
        <ul
          className="dropdown-menu w-100 shadow-sm show animate__fadeIn h-64 overflow-auto rounded"
          style={{
            position: "absolute",
            top: "100%",
            left: 0,
            zIndex: 1050,
            marginTop: "4px",
            borderRadius: "0.375rem",
            overflow: "hidden",
          }}
        >
          <div className="p-1">
            <input
              type="search"
              value={searchText}
              onChange={(e) => setSearchText(e.target.value)}
              className="form-control form-control-sm"
              placeholder="Search..."
            />
          </div>

          {isLoading && (
            <li className="dropdown-item text-muted text-center">Loading...</li>
          )}

          {!isLoading && options.length === 0 && (
            <li className="dropdown-item text-muted text-center">No results found</li>
          )}

          {!isLoading &&
            options.map((option) => {
              const isActive = isMultiple
                ? selectedList.some((x) => x[valueKey] === option[valueKey])
                : selectedSingle &&
                  selectedSingle[valueKey] === option[valueKey];

              return (
                <li key={option[valueKey]}>
                  <button
                    type="button"
                    className={`dropdown-item ${isActive ? "active" : ""}`}
                    onClick={() => handleSelect(option)}
                  >
                    {getDisplayName(option)}
                  </button>
                </li>
              );
            })}
        </ul>
      )}
    </div>
  );
};
export default SelectEmployeeServerSide;


export const SelectProjectField = ()=>{
   const [searchText, setSearchText] = useState("");
  const debounce = useDebounce(searchText, 300);

  const { data, isLoading } = useEmployeesName(
    projectId,
    debounce,
    isAllEmployee
  );

  const options = data?.data ?? [];
  const [open, setOpen] = useState(false);
  const dropdownRef = useRef(null);

  const getDisplayName = (emp) => {
    if (!emp) return "";
    return `${emp.firstName || ""} ${emp.lastName || ""}`.trim();
  };

  /** -----------------------------
   * SELECTED OPTION (SINGLE)
   * ----------------------------- */
  let selectedSingle = null;

  if (!isMultiple) {
    if (isFullObject && value) selectedSingle = value;
    else if (!isFullObject && value)
      selectedSingle = options.find((o) => o[valueKey] === value);
  }

  /** -----------------------------
   * SELECTED OPTION (MULTIPLE)
   * ----------------------------- */
  let selectedList = [];

  if (isMultiple && Array.isArray(value)) {
    if (isFullObject) selectedList = value;
    else {
      selectedList = options.filter((opt) => value.includes(opt[valueKey]));
    }
  }

  /** Main button label */
  const displayText = !isMultiple
    ? getDisplayName(selectedSingle) || placeholder
    : selectedList.length > 0
    ? selectedList.map((e) => getDisplayName(e)).join(", ")
    : placeholder;

  /** -----------------------------
   * HANDLE OUTSIDE CLICK
   * ----------------------------- */
  useEffect(() => {
    const handleClickOutside = (e) => {
      if (dropdownRef.current && !dropdownRef.current.contains(e.target)) {
        setOpen(false);
      }
    };

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

  /** -----------------------------
   * HANDLE SELECT
   * ----------------------------- */
  const handleSelect = (option) => {
    if (!isMultiple) {
      // SINGLE SELECT
      if (isFullObject) onChange(option);
      else onChange(option[valueKey]);
    } else {
      // MULTIPLE SELECT
      let updated = [];

      const exists = selectedList.some((e) => e[valueKey] === option[valueKey]);

      if (exists) {
        // remove
        updated = selectedList.filter((e) => e[valueKey] !== option[valueKey]);
      } else {
        // add
        updated = [...selectedList, option];
      }

      if (isFullObject) onChange(updated);
      else onChange(updated.map((x) => x[valueKey]));
    }
  };

  return (
    <div className="mb-3 position-relative" ref={dropdownRef}>
      {label && (
        <Label className="form-label" required={required}>
          {label}
        </Label>
      )}

      {/* MAIN BUTTON */}
      <button
        type="button"
        className={`select2-icons form-select d-flex align-items-center justify-content-between ${
          open ? "show" : ""
        }`}
        onClick={() => setOpen((prev) => !prev)}
      >
        <span className={`text-truncate ${!displayText ? "text-muted" : ""}`}>
          {displayText}
        </span>
      </button>

      {/* DROPDOWN */}
      {open && (
        <ul
          className="dropdown-menu w-100 shadow-sm show animate__fadeIn h-64 overflow-auto rounded"
          style={{
            position: "absolute",
            top: "100%",
            left: 0,
            zIndex: 1050,
            marginTop: "4px",
            borderRadius: "0.375rem",
            overflow: "hidden",
          }}
        >
          <div className="p-1">
            <input
              type="search"
              value={searchText}
              onChange={(e) => setSearchText(e.target.value)}
              className="form-control form-control-sm"
              placeholder="Search..."
            />
          </div>

          {isLoading && (
            <li className="dropdown-item text-muted text-center">Loading...</li>
          )}

          {!isLoading && options.length === 0 && (
            <li className="dropdown-item text-muted text-center">No results found</li>
          )}

          {!isLoading &&
            options.map((option) => {
              const isActive = isMultiple
                ? selectedList.some((x) => x[valueKey] === option[valueKey])
                : selectedSingle &&
                  selectedSingle[valueKey] === option[valueKey];

              return (
                <li key={option[valueKey]}>
                  <button
                    type="button"
                    className={`dropdown-item ${isActive ? "active" : ""}`}
                    onClick={() => handleSelect(option)}
                  >
                    {getDisplayName(option)}
                  </button>
                </li>
              );
            })}
        </ul>
      )}
    </div>
  );
};