/**
 * Hook for user search functionality (initiator/approver)
 */

import { useState, useCallback, useRef, useEffect } from 'react';
import type { User } from '../types/requests.types';

interface UseUserSearchOptions {
  allUsers: User[];
  filterValue: string;
  onFilterChange: (userId: string) => void;
}

export function useUserSearch({ allUsers, filterValue, onFilterChange }: UseUserSearchOptions) {
  const [searchQuery, setSearchQuery] = useState('');
  const [searchResults, setSearchResults] = useState<User[]>([]);
  const [showResults, setShowResults] = useState(false);
  const [selectedUser, setSelectedUser] = useState<User | null>(null);
  const searchTimer = useRef<NodeJS.Timeout | null>(null);

  // Initialize selected user from filter value
  useEffect(() => {
    if (filterValue !== 'all' && allUsers.length > 0) {
      const user = allUsers.find(u => u.userId === filterValue);
      if (user) {
        setSelectedUser(user);
        setSearchQuery(user.displayName || user.email);
      }
    }
  }, [filterValue, allUsers]);

  // Cleanup timer
  useEffect(() => {
    return () => {
      if (searchTimer.current) {
        clearTimeout(searchTimer.current);
      }
    };
  }, []);

  const handleSearch = useCallback((query: string) => {
    setSearchQuery(query);

    if (searchTimer.current) {
      clearTimeout(searchTimer.current);
    }

    if (!query || query.trim().length < 2) {
      setSearchResults([]);
      setShowResults(false);
      return;
    }

    searchTimer.current = setTimeout(() => {
      const searchLower = query.toLowerCase().trim();
      const filtered = allUsers.filter((user) => {
        const email = (user.email || '').toLowerCase();
        const displayName = (user.displayName || '').toLowerCase();
        return email.includes(searchLower) || displayName.includes(searchLower);
      });
      setSearchResults(filtered.slice(0, 10));
      setShowResults(filtered.length > 0);
    }, 300);
  }, [allUsers]);

  const handleSelect = useCallback((user: User) => {
    setSelectedUser(user);
    onFilterChange(user.userId);
    setSearchQuery(user.displayName || user.email);
    setShowResults(false);
    setSearchResults([]);
  }, [onFilterChange]);

  const handleClear = useCallback(() => {
    setSelectedUser(null);
    onFilterChange('all');
    setSearchQuery('');
    setShowResults(false);
    setSearchResults([]);
  }, [onFilterChange]);

  return {
    searchQuery,
    searchResults,
    showResults,
    selectedUser,
    handleSearch,
    handleSelect,
    handleClear,
    setShowResults
  };
}

