/* eslint-disable @typescript-eslint/no-explicit-any */
/* eslint-disable react/no-unescaped-entities */
/* eslint-disable @typescript-eslint/no-unused-vars */
import React, { useState, useEffect } from "react";
import { Field, ErrorMessage, FieldProps } from "formik";
import ThreeDotsLoader from "../Loader/ThreeDotsLoader";

// Define the types for the options
interface SelectOption {
  id: string | number;
  name: string;
}

interface CustomSelectProps {
  name: string;
  options: SelectOption[];
  label: string;
  icon: string;
  page?: string;
  isLoading?: boolean;
  allowNewOption?: boolean;
  isCreatable?: boolean;
  className?: string;
  width?: string;
  defaultValue?: string;
  onChange?: (value: any) => void;
  disabled?: boolean;
}

const CustomSelect: React.FC<CustomSelectProps> = ({
  name,
  options,
  label,
  icon,
  page = "",
  isLoading = false,
  allowNewOption = false,
  isCreatable = false,
  className = "",
  width = "",
  defaultValue = "",
  onChange,
  disabled = false,
}) => {
  const [showDropdown, setShowDropdown] = useState(false);
  const [inputValue, setInputValue] = useState("");
  const [isInitialMount, setIsInitialMount] = useState(true);

  // Add useEffect to set initial value only on mount
  useEffect(() => {
    if (isInitialMount && defaultValue && options.length > 0) {
      const option = options.find((opt) => opt.id == defaultValue);
      if (option) {
        setInputValue(option.name);
      }
      setIsInitialMount(false);
    }
  }, [defaultValue, options, isInitialMount]);

  // Add effect to clear input value when field becomes disabled
  useEffect(() => {
    if (disabled) {
      setInputValue("");
    }
  }, [disabled]);

  const filteredOptions =
    options?.length > 0
      ? options.filter((opt: SelectOption) => {
          try {
            const searchValue = inputValue.toLowerCase();
            const optionName = opt.name.toLowerCase();
            return optionName.includes(searchValue);
          } catch {
            return false;
          }
        })
      : [];

  const handleOptionSelect = (option: SelectOption, form: any) => {
    setInputValue(option.name);
    form.setFieldValue(name, option.id);
    if (onChange) {
      onChange({ value: option.id, label: option.name });
    }
    setShowDropdown(false);
  };

  const handleInputChange = (
    e: React.ChangeEvent<HTMLInputElement>,
    form: any
  ) => {
    if (disabled) return;
    const newValue = e.target.value;
    setInputValue(newValue);
    
    // If input is cleared (backspace or delete), trigger onChange with null
    if (!newValue.trim()) {
      if (onChange) {
        onChange(null);
      }
      form.setFieldValue(name, "");
    } else if (allowNewOption) {
      form.setFieldValue(name, newValue);
    }
    setShowDropdown(true);
  };

  const handleAddNewOption = (form: any) => {
    if (disabled) return;
    if (inputValue.trim()) {
      const newOption: SelectOption = {
        id: inputValue.trim(),
        name: inputValue.trim(),
      };
      setInputValue(newOption.name);
      form.setFieldValue(name, newOption.id);
      setShowDropdown(false);
    }
  };

  const handleInputFocus = () => {
    if (disabled) return;
    setShowDropdown(true);
  };

  const handleInputBlur = (form: any) => {
    setTimeout(() => {
      setShowDropdown(false);
      if (!inputValue.trim()) {
        form.setFieldValue(name, "");
        if (onChange) {
          onChange(null);
        }
      }
    }, 200);
  };

  return (
    <>
      <style>
        {`
          .autocomplete-dot-loader {
            display: flex;
            gap: 2px;
          }
          .autocomplete-dot-loader span {
            display: block;
            width: 4px;
            height: 4px;
            background: lime;
            border-radius: 50%;
            animation: dot-bounce 1s infinite both;
          }
          .autocomplete-dot-loader span:nth-child(2) {
            animation-delay: 0.2s;
          }
          .autocomplete-dot-loader span:nth-child(3) {
            animation-delay: 0.4s;
          }
          @keyframes dot-bounce {
            0%, 80%, 100% { transform: scale(1);}
            40% { transform: scale(1.6);}
          }
          .disabled-input {
            background-color: #e9ecef;
            cursor: not-allowed;
            opacity: 0.7;
          }
        `}
      </style>
      {page === "register" ? (
        <div className="input-outer-box mb-3">
          <div
            className={`input-style no-borders has-icon validate-field mb-0 ${className}`}
            style={{ width }}
          >
            {/* <i className={icon} /> */}
            <Field name={name}>
              {({ field, form }: FieldProps) => (
                <>
                  <input
                    type="text"
                    className={`form-control ${disabled ? 'disabled-input' : ''}`}
                    value={inputValue}
                    onChange={(e) => handleInputChange(e, form)}
                    placeholder={label}
                    style={{
                      minHeight: "28px",
                      fontSize: "12px",
                      padding: "0px 5px 0px 30px",
                    }}
                    onFocus={handleInputFocus}
                    onBlur={() => handleInputBlur(form)}
                    autoComplete="off"
                    disabled={disabled}
                  />

                  {isLoading && (
                    <div
                      style={{
                        position: "absolute",
                        right: "0",
                        top: "50%",
                        transform: "translateY(-50%)",
                      }}
                    >
                      <ThreeDotsLoader />
                    </div>
                  )}

                  {showDropdown && (
                    <div
                      style={{
                        position: "absolute",
                        zIndex: 10,
                        background: "#fff",
                        width: "100%",
                        border: "1px solid #eee",
                        boxShadow: "0 2px 8px rgba(0,0,0,0.08)",
                        maxHeight: "150px",
                        overflowY: "auto",
                      }}
                    >
                      {filteredOptions.length > 0 && (
                        <>
                          {filteredOptions.map((option) => (
                            <div
                              key={option.id}
                              style={{
                                padding: "8px 12px",
                                cursor: "pointer",
                                borderBottom: "1px solid #f0f0f0",
                              }}
                              onMouseDown={() =>
                                handleOptionSelect(option, form)
                              }
                              onMouseEnter={(e) => {
                                e.currentTarget.style.backgroundColor =
                                  "#f5f5f5";
                              }}
                              onMouseLeave={(e) => {
                                e.currentTarget.style.backgroundColor = "#fff";
                              }}
                            >
                              {option.name}
                            </div>
                          ))}
                        </>
                      )}
                      {isCreatable && (
                        <div
                          style={{
                            padding: "8px 12px",
                            cursor: "pointer",
                            borderBottom: "1px solid #f0f0f0",
                            color: "#0066cc",
                            backgroundColor: "#f8f9fa",
                          }}
                          onMouseDown={() => handleAddNewOption(form)}
                          onMouseEnter={(e) => {
                            e.currentTarget.style.backgroundColor = "#e9ecef";
                          }}
                          onMouseLeave={(e) => {
                            e.currentTarget.style.backgroundColor = "#f8f9fa";
                          }}
                        >
                          + Add "{inputValue}"
                        </div>
                      )}
                      {!allowNewOption && filteredOptions.length === 0 && (
                        <div
                          style={{
                            padding: "8px 12px",
                            color: "#666",
                            fontStyle: "italic",
                          }}
                        >
                          No options available
                        </div>
                      )}
                    </div>
                  )}
                </>
              )}
            </Field>
            <label className="color-highlight">{label}</label>
          </div>
          <ErrorMessage name={name} component="div" className="error-message" />
        </div>
      ) : (
        <div
          className={`input-style no-borders has-icon validate-field mb-3 ${className}`}
          style={{ width }}
        >
          {/* <i className={icon} /> */}
          <Field name={name}>
            {({ field, form }: FieldProps) => (
              <>
                <input
                  type="text"
                  className={`form-control ${disabled ? 'disabled-input' : ''}`}
                  value={inputValue}
                  onChange={(e) => handleInputChange(e, form)}
                  placeholder={label}
                  style={{
                    minHeight: "28px",
                    fontSize: "12px",
                    padding: "0px 5px 0px 30px",
                  }}
                  onFocus={handleInputFocus}
                  onBlur={() => handleInputBlur(form)}
                  autoComplete="off"
                  disabled={disabled}
                />

                {isLoading && (
                  <div
                    style={{
                      position: "absolute",
                      right: "0",
                      top: "50%",
                      transform: "translateY(-50%)",
                    }}
                  >
                    <ThreeDotsLoader />
                  </div>
                )}

                {showDropdown && (
                  <div
                    style={{
                      position: "absolute",
                      zIndex: 10,
                      background: "#fff",
                      width: "100%",
                      border: "1px solid #eee",
                      boxShadow: "0 2px 8px rgba(0,0,0,0.08)",
                      maxHeight: "150px",
                      overflowY: "auto",
                    }}
                  >
                    {filteredOptions.length > 0 && (
                      <>
                        {filteredOptions.map((option) => (
                          <div
                            key={option.id}
                            style={{
                              padding: "8px 12px",
                              cursor: "pointer",
                              borderBottom: "1px solid #f0f0f0",
                            }}
                            onMouseDown={() => handleOptionSelect(option, form)}
                            onMouseEnter={(e) => {
                              e.currentTarget.style.backgroundColor = "#f5f5f5";
                            }}
                            onMouseLeave={(e) => {
                              e.currentTarget.style.backgroundColor = "#fff";
                            }}
                          >
                            {option.name}
                          </div>
                        ))}
                      </>
                    )}
                    {isCreatable && (
                      <div
                        style={{
                          padding: "8px 12px",
                          cursor: "pointer",
                          borderBottom: "1px solid #f0f0f0",
                          color: "#0066cc",
                          backgroundColor: "#f8f9fa",
                        }}
                        onMouseDown={() => handleAddNewOption(form)}
                        onMouseEnter={(e) => {
                          e.currentTarget.style.backgroundColor = "#e9ecef";
                        }}
                        onMouseLeave={(e) => {
                          e.currentTarget.style.backgroundColor = "#f8f9fa";
                        }}
                      >
                        + Add "{inputValue}"
                      </div>
                    )}
                    {!allowNewOption && filteredOptions.length === 0 && (
                      <div
                        style={{
                          padding: "8px 12px",
                          color: "#666",
                          fontStyle: "italic",
                        }}
                      >
                        No options available
                      </div>
                    )}
                  </div>
                )}
              </>
            )}
          </Field>
          <label className="color-highlight">{label}</label>
          <ErrorMessage name={name} component="div" className="error-message" />
        </div>
      )}
    </>
  );
};

export default CustomSelect;
