import { useState, useEffect, useCallback, useRef } from 'react';
import assetService from '../services/assetService';
import type { Asset, AssetFilters, AssetFilterOptions, AssetStats, CreateAssetData } from '../services/assetService';

/**
 * Merge user filters with permission filters
 * Permission filters take precedence for security
 */
const mergeFilters = (
  userFilters: AssetFilters | undefined,
  permissionFilters: Record<string, any>
): AssetFilters => {
  const merged: AssetFilters = { ...(userFilters || {}) };

  // Apply permission filters (they take precedence for security)
  for (const [field, value] of Object.entries(permissionFilters)) {
    if (!merged[field as keyof AssetFilters]) {
      // No user filter on this field, apply permission filter directly
      (merged as any)[field] = value;
    } else if (Array.isArray(value) && value[0] === 'in') {
      // Permission filter is ["in", [...values]]
      const permittedValues = value[1] as string[];
      const userValue = merged[field as keyof AssetFilters];

      if (typeof userValue === 'string') {
        // User selected a specific value, check if it's permitted
        if (!permittedValues.includes(userValue)) {
          // User selected a value they don't have permission for
          // Set to empty array to return no results
          (merged as any)[field] = ['in', []];
        }
        // If permitted, keep the user's specific selection
      } else if (Array.isArray(userValue) && userValue[0] === 'in') {
        // Both are ["in", [...]] format, intersect them
        const userValues = userValue[1] as string[];
        const intersection = userValues.filter(v => permittedValues.includes(v));
        (merged as any)[field] = ['in', intersection];
      } else {
        // Other filter types, apply permission filter
        (merged as any)[field] = value;
      }
    }
  }

  return merged;
};

/**
 * Hook to fetch list of assets with filters, pagination, and permission-based filtering
 */
export function useAssets(
  filters?: AssetFilters,
  limit: number = 20,
  offset: number = 0,
  orderBy?: string,
  permissionFilters: Record<string, any> = {} // ← NEW: Permission filters parameter
) {
  const [assets, setAssets] = useState<Asset[]>([]);
  const [totalCount, setTotalCount] = useState(0);
  const [hasMore, setHasMore] = useState(false);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [refetchTrigger, setRefetchTrigger] = useState(0);
  const hasAttemptedRef = useRef(false);

  // Stringify filters to prevent object reference changes from causing re-renders
  const filtersJson = JSON.stringify(filters);
  const permissionFiltersJson = JSON.stringify(permissionFilters); // ← NEW

  useEffect(() => {
    // Prevent fetching if already attempted and has error
    if (hasAttemptedRef.current && error) {
      return;
    }

    let isCancelled = false;
    hasAttemptedRef.current = true;
    
    const fetchAssets = async () => {
      try {
        setLoading(true);
        
        // ✅ NEW: Merge user filters with permission filters
        const mergedFilters = mergeFilters(filters, permissionFilters);
        
        console.log('[useAssets] User filters:', filters);
        console.log('[useAssets] Permission filters:', permissionFilters);
        console.log('[useAssets] Merged filters:', mergedFilters);
        
        const response = await assetService.getAssets(mergedFilters, undefined, limit, offset, orderBy);
        
        if (!isCancelled) {
          setAssets(response.assets);
          setTotalCount(response.total_count);
          setHasMore(response.has_more);
          setError(null);
        }
      } catch (err) {
        if (!isCancelled) {
          const errorMessage = err instanceof Error ? err.message : 'Failed to fetch assets';
          
          // Check if it's a 417 error (API not deployed)
          if (errorMessage.includes('417') || errorMessage.includes('Expectation Failed') || errorMessage.includes('has no attribute')) {
            setError('API endpoint not deployed or misconfigured. Please check FIX_417_ERROR.md for solutions.');
          } else {
            setError(errorMessage);
          }
          
          // Set empty arrays
          setAssets([]);
          setTotalCount(0);
          setHasMore(false);
        }
      } finally {
        if (!isCancelled) {
          setLoading(false);
        }
      }
    };
    
    fetchAssets();
    
    return () => {
      isCancelled = true;
    };
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [filtersJson, permissionFiltersJson, limit, offset, orderBy, refetchTrigger]); // ← Added permissionFiltersJson

  const refetch = useCallback(() => {
    hasAttemptedRef.current = false; // Reset to allow refetch
    setRefetchTrigger(prev => prev + 1);
  }, []);

  return { assets, totalCount, hasMore, loading, error, refetch };
}

/**
 * Hook to fetch a single asset by name
 */
export function useAssetDetails(assetName: string | null) {
  const [asset, setAsset] = useState<Asset | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  const fetchAsset = useCallback(async () => {
    if (!assetName) {
      setAsset(null);
      setLoading(false);
      return;
    }

    try {
      setLoading(true);
      setError(null);
      
      const data = await assetService.getAssetDetails(assetName);
      setAsset(data);
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Failed to fetch asset details');
    } finally {
      setLoading(false);
    }
  }, [assetName]);

  useEffect(() => {
    fetchAsset();
  }, [fetchAsset]);

  const refetch = useCallback(() => {
    fetchAsset();
  }, [fetchAsset]);

  return { asset, loading, error, refetch };
}

/**
 * Hook to manage asset operations (create, update, delete)
 */
export function useAssetMutations() {
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);

  const createAsset = async (assetData: CreateAssetData) => {
    try {
      setLoading(true);
      setError(null);
      
      console.log('[useAssetMutations] Creating asset with data:', assetData);
      const response = await assetService.createAsset(assetData);
      console.log('[useAssetMutations] Create asset response:', response);
      
      if (response.success) {
        return response.asset;
      } else {
        // Include the backend error message if available
        const backendError = (response as any).error || 'Failed to create asset';
        throw new Error(backendError);
      }
    } catch (err) {
      console.error('[useAssetMutations] Create asset error:', err);
      const errorMessage = err instanceof Error ? err.message : 'Failed to create asset';
      setError(errorMessage);
      throw err;
    } finally {
      setLoading(false);
    }
  };

  const updateAsset = async (assetName: string, assetData: Partial<CreateAssetData>) => {
    try {
      setLoading(true);
      setError(null);
      
      console.log('[useAssetMutations] Updating asset:', assetName, 'with data:', assetData);
      const response = await assetService.updateAsset(assetName, assetData);
      console.log('[useAssetMutations] Update asset response:', response);
      
      if (response.success) {
        return response.asset;
      } else {
        // Include the backend error message if available
        const backendError = (response as any).error || 'Failed to update asset';
        throw new Error(backendError);
      }
    } catch (err) {
      console.error('[useAssetMutations] Update asset error:', err);
      const errorMessage = err instanceof Error ? err.message : 'Failed to update asset';
      setError(errorMessage);
      throw err;
    } finally {
      setLoading(false);
    }
  };

  const deleteAsset = async (assetName: string) => {
    try {
      setLoading(true);
      setError(null);
      
      const response = await assetService.deleteAsset(assetName);
      
      if (!response.success) {
        throw new Error('Failed to delete asset');
      }
      
      return response;
    } catch (err) {
      const errorMessage = err instanceof Error ? err.message : 'Failed to delete asset';
      setError(errorMessage);
      throw err;
    } finally {
      setLoading(false);
    }
  };

  const submitAsset = async (assetName: string) => {
    try {
      setLoading(true);
      setError(null);
      
      console.log('[useAssetMutations] Submitting asset:', assetName);
      const response = await assetService.submitAsset(assetName);
      console.log('[useAssetMutations] Submit asset response:', response);
      
      return response;
    } catch (err) {
      console.error('[useAssetMutations] Submit asset error:', err);
      const errorMessage = err instanceof Error ? err.message : 'Failed to submit asset';
      setError(errorMessage);
      throw err;
    } finally {
      setLoading(false);
    }
  };

  return { createAsset, updateAsset, deleteAsset, submitAsset, loading, error };
}

/**
 * Hook to fetch asset filter options
 */
export function useAssetFilters() {
  const [filters, setFilters] = useState<AssetFilterOptions | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  const fetchFilters = useCallback(async () => {
    try {
      setLoading(true);
      setError(null);
      
      const data = await assetService.getAssetFilters();
      setFilters(data);
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Failed to fetch filters');
    } finally {
      setLoading(false);
    }
  }, []);

  useEffect(() => {
    fetchFilters();
  }, [fetchFilters]);

  const refetch = useCallback(() => {
    fetchFilters();
  }, [fetchFilters]);

  return { filters, loading, error, refetch };
}

/**
 * Hook to fetch asset statistics
 */
export function useAssetStats() {
  const [stats, setStats] = useState<AssetStats | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  const fetchStats = useCallback(async () => {
    try {
      setLoading(true);
      setError(null);
      
      const data = await assetService.getAssetStats();
      setStats(data);
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Failed to fetch statistics');
    } finally {
      setLoading(false);
    }
  }, []);

  useEffect(() => {
    fetchStats();
  }, [fetchStats]);

  const refetch = useCallback(() => {
    fetchStats();
  }, [fetchStats]);

  return { stats, loading, error, refetch };
}

/**
 * Hook for asset search
 */
export function useAssetSearch() {
  const [results, setResults] = useState<Asset[]>([]);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);

  const search = useCallback(async (searchTerm: string, limit: number = 10) => {
    if (!searchTerm.trim()) {
      setResults([]);
      return;
    }

    try {
      setLoading(true);
      setError(null);
      
      const data = await assetService.searchAssets(searchTerm, limit);
      setResults(data);
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Search failed');
      setResults([]);
    } finally {
      setLoading(false);
    }
  }, []);

  const clearResults = useCallback(() => {
    setResults([]);
    setError(null);
  }, []);

  return { results, loading, error, search, clearResults };
}