import { useState, useMemo } from 'react';

export function useHomeownerRequestFiltering(requests = []) {
  const [filterClientId, setFilterClientId] = useState('all');
  const [searchQuery, setSearchQuery] = useState('');
  const [sortConfig, setSortConfig] = useState({ key: 'created_at', direction: 'desc' });

  const filteredRequests = useMemo(() => {
    let result = [...requests];

    if (filterClientId && filterClientId !== 'all') {
      result = result.filter(req => req.association_id === filterClientId);
    }

    if (searchQuery) {
      const query = searchQuery.toLowerCase();
      result = result.filter(req => 
        (req.title && req.title.toLowerCase().includes(query)) ||
        (req.description && req.description.toLowerCase().includes(query))
      );
    }

    if (sortConfig.key) {
      result.sort((a, b) => {
        let aValue = a[sortConfig.key];
        let bValue = b[sortConfig.key];
        if (sortConfig.key === 'created_at' || sortConfig.key === 'updated_at') {
          aValue = new Date(aValue).getTime();
          bValue = new Date(bValue).getTime();
        }
        if (aValue < bValue) return sortConfig.direction === 'asc' ? -1 : 1;
        if (aValue > bValue) return sortConfig.direction === 'asc' ? 1 : -1;
        return 0;
      });
    }

    return result;
  }, [requests, filterClientId, searchQuery, sortConfig]);

  const requestSort = (key) => {
    let direction = 'asc';
    if (sortConfig.key === key && sortConfig.direction === 'asc') direction = 'desc';
    setSortConfig({ key, direction });
  };

  const clearFilters = () => {
    setFilterClientId('all');
    setSearchQuery('');
    setSortConfig({ key: 'created_at', direction: 'desc' });
  };

  return {
    filterClientId, setFilterClientId,
    searchQuery, setSearchQuery,
    sortConfig, requestSort,
    filteredRequests, clearFilters,
    totalCount: requests.length,
    filteredCount: filteredRequests.length
  };
}
