import React, { useEffect, useRef, useState } from 'react';
import InputAutoComplete from '@/components/form/InputAutoComplete';

interface InputSelectAndSearchDropdownProps {
  options: Array<{ value: number | string; label: React.ReactNode }>;
  onSelect?: (value: number | string) => void;
  onChange?: (
    value: string | number,
    item:
      | { value: number | string; label: React.ReactNode }
      | Array<{ value: number | string; label: React.ReactNode }>,
  ) => void;
  filter?: {
    status?: string;
  };
  name: string;
  label: string;
  mode?: 'multiple' | undefined;
  placeholder: string;
  onClear?: () => void;
  /** When provided, search is handled server-side and local filtering is skipped */
  onSearchServer?: (search: string) => void;
  /** Scroll-to-bottom callback for server-side pagination */
  handleLoadMore?: () => void;
  [key: string]: unknown;
}

const InputSelectAndSearch: React.FC<InputSelectAndSearchDropdownProps> = ({
  onSelect,
  onClear,
  name,
  label,
  options,
  mode,
  placeholder,
  onChange,
  onSearchServer,
  handleLoadMore,
  ...rest
}) => {
  const [dropdownOptions, setDropdownOptions] = useState<Array<{ value: number | string; label: React.ReactNode }>>([]);
  const [isDropdownOpen, setIsDropdownOpen] = useState(false);
  const serverSearchInitialized = useRef(false);
  const isFetchingRef = useRef(false);
  useEffect(() => {
    setDropdownOptions(options);
    isFetchingRef.current = false;
  }, [options]);

  const getProjectOptions = (search?: string): void => {
    if (onSearchServer) {
      if (!serverSearchInitialized.current && !search) {
        serverSearchInitialized.current = true;
        return;
      }
      serverSearchInitialized.current = true;
      // Mark fetch in-flight before calling the server
      isFetchingRef.current = true;
      onSearchServer(search || '');
      return;
    }
    if (!search) {
      setDropdownOptions(options);
    } else {
      const suggestions = search.trim().toLowerCase();
      setDropdownOptions(
        options.filter(opt =>
          typeof opt.label === 'string' && opt.label.toLowerCase().includes(suggestions)
        )
      );
    }
  };

  // Wrap handleLoadMore to mark fetch in-flight before triggering pagination
  const handleLoadMoreWrapped = handleLoadMore
    ? () => {
        isFetchingRef.current = true;
        handleLoadMore();
      }
    : undefined;

  return (
    <InputAutoComplete
      name={name}
      label={label}
      mode={mode}
      placeholder={placeholder}
      onChange={(value, item) => {
        if (onChange) {
          onChange(value, item);
        }
      }}
      options={dropdownOptions}
      onSelect={(value) => {
        if (onSelect) {
          onSelect(value);
        }
      }}
      isSearchable={true}
      onSearch={getProjectOptions}
      searchOnEnter={!!onSearchServer}
      filterOption={onSearchServer ? false : undefined}
      handleLoadMore={handleLoadMoreWrapped}
        open={isDropdownOpen}
        onDropdownVisibleChange={(visible) => {
          if (!visible && isFetchingRef.current) {
            return;
          }
          setIsDropdownOpen(visible);
        }}
      onClear={() => {
        if (onClear !== undefined) {
          onClear();
        }
      }}
      {...rest}
    />
  );
};

export default InputSelectAndSearch;
