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

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

interface UseUserSearchOptions {
  filterValue: string;
  onFilterChange: (userId: string) => void;
  source?: 'local' | 'okta' | 'default';
}

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

  // Initialize selected user details if we only have the ID (filterValue)
  useEffect(() => {
    async function fetchUserDetail() {
      if (filterValue !== 'all' && !selectedUser) {
        try {
          // Fetch specific user details by ID
          const user = await userApi.getUserById(filterValue);
          if (user) {
            setSelectedUser(user);
            setSearchQuery(user.displayName || user.email);
          }
        } catch (err) {
          console.error('Failed to fetch user detail for search:', err);
        }
      } else if (filterValue === 'all') {
        setSelectedUser(null);
        setSearchQuery('');
      }
    }

    fetchUserDetail();
  }, [filterValue]);

  // 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(async () => {
      setSearching(true);
      try {
        const response = await userApi.searchUsers(query.trim(), 10, source);
        const users = response.data?.data || [];
        setSearchResults(users);
        setShowResults(users.length > 0);
      } catch (err) {
        console.error('Search API failed:', err);
        setSearchResults([]);
        setShowResults(false);
      } finally {
        setSearching(false);
      }
    }, 400); // Slightly longer debounce for API calls
  }, [source]);

  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,
    searching,
    handleSearch,
    handleSelect,
    handleClear,
    setShowResults
  };
}

