/* eslint-disable @typescript-eslint/no-explicit-any */
// CustomizedSelect: Proper select box component styled like SelectField
import React, { useState, useRef, useEffect } from "react";
import ThreeDotsLoader from "../Loader/ThreeDotsLoader";

interface Options {
  id: string;
  name: string;
  code: string;
}

interface Option {
  id: string;
  name: string;
}
interface CustomizedSelectProps {
  options: Options[];
  value: string | Option | null;
  onChange: (value: string | Option | null) => void;
  errors?: string;
  placeholder?: string;
  className?: string;
  width?: string;
  icon?: React.ReactNode;
  label?: string;
  allowNewOption?: boolean;
  isCreatable?: boolean;
  isLoading?: boolean;
  name?: string;
  referenceData?: { road?: { id: number; name: string; code?: string; }; block?: { id: number; name: string; code?: string; } } | any;
}

export const CustomizedSelect: React.FC<CustomizedSelectProps> = ({
  options = [],
  value,
  onChange,
  errors,
  placeholder = "Select an option",
  className = "",
  width = "",
  icon,
  label,
  allowNewOption = false,
  isCreatable = false,
  isLoading = false,
  name = "",
  referenceData
}) => {
  const [showDropdown, setShowDropdown] = useState(false);
  const [searchQuery, setSearchQuery] = useState("");
  const selectRef = useRef<HTMLDivElement>(null);
  const [localOptions, setLocalOptions] = useState<Options[]>(options);

  useEffect(() => {
    setLocalOptions(options);
  }, [options]);

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

  const handleOptionSelect = (option: Option) => {
    onChange(option);
    setShowDropdown(false);
    setSearchQuery("");
  };

  const handleToggleDropdown = () => {
    if (!isLoading) {
      setShowDropdown(!showDropdown);
      if (!showDropdown) setSearchQuery("");
    }
  };

  const handleClearSelection = () => {
    onChange(null);
    setSearchQuery("");
  };

  const getDisplayValue = () => {
    if (typeof value === 'object' && value !== null) {
      return value.name;
    }
    return value || placeholder;
  };

  const isOptionSelected = typeof value === 'object' && value !== null;

  // Filter options by search query (code or name, case-insensitive)
  const filteredOptions = localOptions.filter(option => {
    const q = searchQuery.trim().toLowerCase();
    if (!q) return true;
    return (
      option.name.toLowerCase().includes(q) ||
      (option.code && option.code.toLowerCase().includes(q))
    );
  });

  const handleAddNewOption = () => {
    const trimmedQuery = searchQuery.trim();
    if (!trimmedQuery) return;
    // Prevent duplicate
    const exists = localOptions.some(
      (option) => option.name.toLowerCase() === trimmedQuery.toLowerCase()
    );
    if (exists) return;
    const newOption = {
      id: trimmedQuery,
      name: trimmedQuery,
      code: '',
    };
    const updatedOptions = [...localOptions, newOption];
    setLocalOptions(updatedOptions);
    onChange(newOption);
    setShowDropdown(false);
    setSearchQuery("");
  };
  return (
    <>
      <style>
        {`
          .select-field-container {
            position: relative;
            display: flex;
            align-items: center;
            background: #fff;
            border: 1px solid #ccc;
            border-radius: 4px;
            min-height: 38px;
            cursor: pointer;
            user-select: none;
          }
          .select-field-container:hover {
            border-color: #999;
          }
          .select-field-container.has-error {
            border-color: red;
          }
          .select-field-display {
            flex: 1;
            padding: 8px 12px;
            font-size: 14px;
            color: #333;
            background: transparent;
            border: none;
            outline: none;
            cursor: pointer;
            text-align: left;
            max-width: 100%;
            overflow: hidden;
            white-space: nowrap;
            text-overflow: ellipsis;
          }
          .select-field-display.placeholder {
            color: #999;
          }
          .select-field-clear {
            padding: 4px 8px;
            background: none;
            border: none;
            cursor: pointer;
            color: #999;
            font-size: 16px;
            line-height: 1;
          }
          .select-field-clear:hover {
            color: #666;
          }
          .select-field-arrow {
            padding: 4px 8px;
            color: #999;
            font-size: 12px;
            pointer-events: none;
            transition: transform 0.2s;
          }
          .select-field-arrow.open {
            transform: rotate(180deg);
          }
          .select-field-actions {
            display: flex;
            align-items: center;
            justify-content: flex-end;
            min-width: 60px;
            max-width: 60px;
            height: 100%;
            position: relative;
          }
          .select-dropdown {
            position: absolute;
            top: 100%;
            left: 0;
            right: 0;
            z-index: 1000;
            background: #fff;
            border: 1px solid #ccc;
            border-top: none;
            border-radius: 0 0 4px 4px;
            box-shadow: 0 2px 8px rgba(0,0,0,0.1);
            max-height: 200px;
            overflow-y: auto;
          }
          .select-option {
            padding: 8px 12px;
            cursor: pointer;
            border-bottom: 1px solid #f0f0f0;
          }
          .select-option:hover {
            background-color: #f5f5f5;
          }
          .select-option:last-child {
            border-bottom: none;
          }
          .select-option.selected {
            background-color: #e3f2fd;
            color: #1976d2;
          }
          .select-create-option .select-create-context {
            padding: 8px 12px;
            cursor: pointer;
            border-bottom: 1px solid #f0f0f0;
            color: #0066cc;
            background-color: #cccccc !important;
          }
          .select-create-option .select-create-context:hover {
            background-color: #e9ecef;
          }
          .select-no-options {
            padding: 8px 12px;
            color: #666;
            font-style: italic;
          }
          .input-style-select .select-field-container {
            min-height: 52px;
            border-radius: 10px;
          }
          .select-create-context {
            font-size: 12px;
            color: #888;
          }
          .input-style.has-icon.has-borders input.padding-left-8 {
            padding-left: 8px !important;
          }
          .border-bottom01 {
            border-bottom: 1px solid #eee;
          }
        `}
      </style>
      <div
        ref={selectRef}
        className={`input-style01 input-style-select ${className} ${errors ? "has-error" : ""}`}
        style={{ width, position: "relative" }}
      >
        {/* Icon */}
        {icon && (
          <div
            className="input-icon"
            style={{ position: "absolute", top: "50%", transform: "translateY(-50%)", zIndex: 2, pointerEvents: "none" }}
          >
           <i className={`${icon} color-primary`} />
          </div>
        )}

        <div 
          className={`select-field-container ${errors ? "has-error" : ""}`}
          onClick={handleToggleDropdown}
        >
          <div
            className={`select-field-display ${!isOptionSelected ? "placeholder" : ""}`}
            style={{
              paddingLeft: icon ? "40px" : "12px",
              // Remove paddingRight here, handled by actions wrapper
            }}
          >
            {getDisplayValue()}
          </div>

          {/* Actions: clear, loader, arrow */}
          <div className="select-field-actions">
            {isOptionSelected && (
              <button
                type="button"
                className="select-field-clear"
                onClick={(e) => {
                  e.stopPropagation();
                  handleClearSelection();
                }}
                title="Clear selection"
              >
                ×
              </button>
            )}

            {isLoading && (
              <div style={{ padding: "4px 0", display: "flex", alignItems: "center" }}>
                <ThreeDotsLoader />
              </div>
            )}

            <div className={`select-field-arrow ${showDropdown ? "open" : ""}`}>
              ▼
            </div>
          </div>
        </div>

        {/* Dropdown */}
        {showDropdown && (
          <div className="select-dropdown">
            {/* Search input */}
            <div style={{ padding: "8px 12px", borderBottom: "1px solid #f0f0f0", background: "#fafbfc" }}>
              <input
                type="text"
                value={searchQuery}
                onChange={e => setSearchQuery(e.target.value)}
                placeholder="Search by no. or name..."
                style={{
                  width: "100%",
                  padding: "6px 8px",
                  paddingLeft: "8px",
                  border: "1px solid #ddd",
                  borderRadius: "4px",
                  fontSize: "14px",
                }}
                className="padding-left-8"
                autoFocus
                onClick={e => e.stopPropagation()}
              />
            </div>
            {isCreatable && (
              <>
                <button
                  className="select-create-option w-100"
                  onClick={e => {
                    e.stopPropagation();
                    handleAddNewOption();
                  }}
                >
                  <p className="text-center mb-0 font-700 font-16 btn btn-s border border-primary color-primary rounded-0 w-100 opacity-50">+ Add new</p>
                  {/* <p className="mb-0 px-3"><hr className="mb-0 mt-2 opacity-30"/></p> */}
                  {name === 'buildingNo' && referenceData?.road?.name && referenceData?.block?.name && (
                    <div className="select-create-context">
                      <p className="mb-0">Road - {referenceData?.road?.code}{(referenceData?.road?.name && referenceData?.road?.name !== referenceData?.road?.code) ? `, ${referenceData?.road?.name}` : ''}, Block - {referenceData?.block?.code}{(referenceData?.block?.name && referenceData?.block?.name !== referenceData?.block?.code) ? `,  ${referenceData?.block?.name}` : ''}</p>
                    </div>
                  )}
                </button>
                <hr className="mb-0 mt-0"/>
              </>
            )}
            {!allowNewOption && filteredOptions.length === 0 && (
              <div className="select-no-options text-center">
                No options available
              </div>
            )}
                       {filteredOptions.length > 0 && (
              <>
                {filteredOptions.map((option) => (
                  <div
                    key={option.id}
                    className={`select-option ${(typeof value === 'object' && value !== null && value.id === option.id) ? "selected" : ""}`}
                    onClick={() => handleOptionSelect(option)}
                  >
                    {option?.id === "add-new" ? (<>
                      <p className="text-center mb-0 font-700 font-16 color-primary">+ Add new</p>
                      {/* <hr className="mb-2 mt-2"/> */}
                    </>) : <>
                    <p className="text-center mb-0 border-bottom01">{option?.code} - {option.name}</p>
                    </>}
                    
                  </div>
                ))}
              </>
            )}
          </div>
        )}

        {/* Label */}
        {label && (
          <label className="color-theme opacity-80 text-uppercase font-700 font-10">
            {label}
          </label>
        )}
      </div>
    </>
  );
};
