import { useState, useEffect, useMemo, useCallback } from 'react';
import api from '../lib/api';

// Data manager hook for handling API data with pagination and filtering
export function useDataManager({
    endpoint,
    initialFilters = {},
    initialPageSize = 10,
    transformData = null,
    dependencies = []
}) {
    const [data, setData] = useState([]);
    const [filteredData, setFilteredData] = useState([]);
    const [isLoading, setIsLoading] = useState(true);
    const [error, setError] = useState(null);
    const [filters, setFilters] = useState(initialFilters);
    const [currentPage, setCurrentPage] = useState(1);
    const [pageSize, setPageSize] = useState(initialPageSize);

    // Fetch data from API
    const fetchData = useCallback(async () => {
        if (!endpoint) return;
        
        setIsLoading(true);
        setError(null);
        
        try {
            // Build query parameters for pagination and filtering
            const params = {
                page: currentPage,
                limit: pageSize
            };
            
            // Add search parameter if provided
            if (filters.search && filters.search.trim()) {
                params.search = filters.search.trim();
            }
            
            // Add police station filter if provided
            if (filters.policeStation && filters.policeStation !== 'all') {
                params.police_station = filters.policeStation;
            }
            
            console.log('API Request:', { endpoint, params });
            const response = await api.get(endpoint, { params });
            console.log('API Response:', response.data);
            let fetchedData = response.data;
            
            // For constables endpoint, we need to keep the full response for pagination
            if (endpoint === '/constables/') {
                console.log('Setting full response data for constables:', fetchedData);
                console.log('Data structure check:', {
                    hasConstables: !!fetchedData.constables,
                    hasPagination: !!fetchedData.pagination,
                    constablesLength: fetchedData.constables?.length,
                    paginationData: fetchedData.pagination
                });
                setData(fetchedData);
            } else {
                // Transform data if transform function is provided
                if (transformData && typeof transformData === 'function') {
                    fetchedData = transformData(fetchedData);
                }
                
                console.log('Setting transformed data:', fetchedData);
                setData(fetchedData);
            }
        } catch (err) {
            console.error('Failed to fetch data:', err);
            console.error('Error details:', {
                message: err.message,
                status: err.response?.status,
                statusText: err.response?.statusText,
                data: err.response?.data,
                url: err.config?.url
            });
            setError(err.message || 'Failed to fetch data');
        } finally {
            setIsLoading(false);
        }
    }, [endpoint, transformData, currentPage, pageSize, filters, ...dependencies]);

    // Apply filters to data
    const applyFilters = useCallback((dataToFilter, currentFilters) => {
        console.log('Applying filters:', { dataToFilter, currentFilters });
        if (!dataToFilter || !Array.isArray(dataToFilter)) {
            console.log('No data to filter or not an array');
            return [];
        }
        
        return dataToFilter.filter(item => {
            // Search filter
            if (currentFilters.search && currentFilters.search.trim()) {
                const searchTerm = currentFilters.search.toLowerCase();
                const searchableFields = Object.values(item).filter(value => 
                    typeof value === 'string' || typeof value === 'number'
                );
                
                if (!searchableFields.some(value => 
                    String(value).toLowerCase().includes(searchTerm)
                )) {
                    return false;
                }
            }
            
            // Status filter
            if (currentFilters.status && currentFilters.status !== 'all') {
                if (item.status?.toLowerCase() !== currentFilters.status.toLowerCase()) {
                    return false;
                }
            }
            
            // Police Station filter
            if (currentFilters.policeStation && currentFilters.policeStation !== 'all') {
                if (item.police_station !== currentFilters.policeStation) {
                    return false;
                }
            }
            
            // Violation Type filter
            if (currentFilters.violationType && currentFilters.violationType !== 'all') {
                if (item.violation_type !== currentFilters.violationType) {
                    return false;
                }
            }
            
            // Date Range filter
            if (currentFilters.dateRange?.from && currentFilters.dateRange?.to) {
                const itemDate = new Date(item.timestamp || item.created_at);
                const fromDate = new Date(currentFilters.dateRange.from);
                const toDate = new Date(currentFilters.dateRange.to);
                
                if (itemDate < fromDate || itemDate > toDate) {
                    return false;
                }
            }
            
            return true;
        });
    }, []);

    // Update filters
    const updateFilters = useCallback((newFilters) => {
        console.log('Updating filters:', { prev: filters, new: newFilters });
        setFilters(prev => ({ ...prev, ...newFilters }));
        setCurrentPage(1); // Reset to first page when filters change
    }, [filters]);

    // Update page size
    const updatePageSize = useCallback((newPageSize) => {
        console.log('Updating page size:', newPageSize);
        setPageSize(newPageSize);
        setCurrentPage(1); // Reset to first page when page size changes
    }, []);

    // Go to specific page
    const goToPage = useCallback((page) => {
        console.log('Going to page:', page);
        setCurrentPage(page);
    }, []);

    // Go to next page
    const nextPage = useCallback(() => {
        console.log('Next page called:', { endpoint, hasPagination: !!data.pagination });
        if (endpoint === '/constables/' && data.pagination) {
            // For server-side pagination, just increment the page
            console.log('Using server-side pagination, incrementing page');
            setCurrentPage(prev => prev + 1);
        } else {
            // For client-side pagination, check against total pages
            console.log('Using client-side pagination');
            setCurrentPage(prev => Math.min(prev + 1, Math.ceil(filteredData.length / pageSize)));
        }
    }, [endpoint, data.pagination, filteredData.length, pageSize]);

    // Go to previous page
    const previousPage = useCallback(() => {
        console.log('Previous page called');
        setCurrentPage(prev => Math.max(prev - 1, 1));
    }, []);

    // Refresh data
    const refreshData = useCallback(() => {
        console.log('Refreshing data');
        fetchData();
    }, [fetchData]);

    // Apply filters whenever data or filters change
    useEffect(() => {
        console.log('Applying filters to data:', { data, filters });
        const filtered = applyFilters(data, filters);
        console.log('Filtered data result:', filtered);
        setFilteredData(filtered);
    }, [data, filters, applyFilters]);

    // Fetch data on mount and when dependencies change
    useEffect(() => {
        console.log('Fetching data for endpoint:', endpoint);
        fetchData();
    }, [fetchData]);

    // Calculate pagination info
    const paginationInfo = useMemo(() => {
        console.log('Calculating pagination info:', { endpoint, data, filteredData, currentPage, pageSize });
        
        // For constables endpoint, use server-side pagination
        if (endpoint === '/constables/' && data.pagination) {
            console.log('Using server-side pagination for constables:', data.pagination);
            const paginationData = {
                totalItems: data.pagination.total_constables,
                totalPages: data.pagination.total_pages,
                currentPage: data.pagination.current_page,
                pageSize: data.pagination.limit,
                startIndex: (data.pagination.current_page - 1) * data.pagination.limit,
                endIndex: Math.min((data.pagination.current_page - 1) * data.pagination.limit + data.pagination.limit, data.pagination.total_constables),
                currentData: data.constables || [],
                hasNext: data.pagination.has_next,
                hasPrev: data.pagination.has_prev
            };
            console.log('Calculated pagination data:', paginationData);
            return paginationData;
        }
        
        // Fallback to client-side pagination for other endpoints
        console.log('Using client-side pagination fallback');
        const totalItems = filteredData.length;
        const totalPages = Math.ceil(totalItems / pageSize);
        const startIndex = (currentPage - 1) * pageSize;
        const endIndex = Math.min(startIndex + pageSize, totalItems);
        const currentData = filteredData.slice(startIndex, endIndex);
        
        return {
            totalItems,
            totalPages,
            currentPage,
            pageSize,
            startIndex,
            endIndex,
            currentData,
            hasNext: currentPage < totalPages,
            hasPrev: currentPage > 1
        };
    }, [endpoint, data, filteredData, currentPage, pageSize]);

    const result = {
        // Data
        data,
        filteredData,
        currentData: paginationInfo.currentData,
        
        // Loading and error states
        isLoading,
        error,
        
        // Filters
        filters,
        updateFilters,
        
        // Pagination
        paginationInfo,
        goToPage,
        nextPage,
        previousPage,
        updatePageSize,
        
        // Actions
        refreshData,
        fetchData
    };
    
    console.log('useDataManager returning:', result);
    return result;
}

// Predefined configurations for common use cases
export const dataManagerConfigs = {
    violations: {
        endpoint: '/violations',
        initialFilters: {
            search: '',
            status: 'all',
            violationType: 'all',
            dateRange: {
                from: new Date(Date.now() - 30 * 24 * 60 * 60 * 1000),
                to: new Date()
            }
        },
        transformData: (data) => {
            // Transform API response to match component expectations
            if (data.violations) {
                return data.violations;
            }
            return Array.isArray(data) ? data : [];
        }
    },
    
    constables: {
        endpoint: '/constables/',
        initialFilters: {
            search: '',
            policeStation: 'all'
        },
        transformData: (data) => {
            // For constables, we don't transform the data since we need the full response
            // This function is not used for constables endpoint
            console.log('Transform data input (not used for constables):', data);
            return data;
        }
    }
};
