import { useCallback, useState, useEffect, useRef } from 'react';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { resolveApiBase } from '../lib/api-base';

const API_BASE = resolveApiBase();

// ============================================================================
// TYPES
// ============================================================================

export interface SmartFinderSchool {
  code: string;
  name: string;
  region: string;
}

export interface SmartFinderSupplier {
  id: number;
  name: string;
  business_name: string;
  email: string;
  supplier_id?: number;
  supplier_name?: string;
  contract_number?: string;
  contract_status?: string;
  total_qty?: number;
  total_value?: number;
}

export interface SmartFinderCacheStatus {
  valid: boolean;
  last_sync: number | null;
  last_sync_formatted: string | null;
  record_count: number;
  school_count: number;
  commodity_count: number;
  supplier_count: number;
  build_time_ms: number | null;
  ttl_seconds: number;
  expires_in: number;
}

export interface SmartFinderSearchResult {
  type: 'school_commodity_supplier' | 'school_details' | 'commodity_suppliers' | 'region_suppliers' | 'summary';
  school?: SmartFinderSchool;
  commodity?: string;
  commodities?: string[];
  suppliers?: SmartFinderSupplier[];
  query_time_ms: number;
}

// ============================================================================
// HELPERS
// ============================================================================

const getAuthHeaders = (): HeadersInit => {
  const headers: HeadersInit = {
    'Content-Type': 'application/json',
    'Accept': 'application/json',
  };
  if (typeof window !== 'undefined') {
    const token = localStorage.getItem('gcx_fshs_token');
    if (token) headers['Authorization'] = `Bearer ${token}`;
  }
  return headers;
};

// ============================================================================
// API HOOKS
// ============================================================================

/**
 * Hook to get Smart Finder cache status
 */
export function useSmartFinderStatus() {
  return useQuery<SmartFinderCacheStatus>({
    queryKey: ['smart-finder-status'],
    queryFn: async () => {
      const res = await fetch(`${API_BASE}/smart-finder/status`, {
        headers: getAuthHeaders(),
      });
      if (!res.ok) throw new Error('Failed to get cache status');
      const data = await res.json();
      return data.cache;
    },
    staleTime: 30 * 1000, // 30 seconds
    refetchInterval: 60 * 1000, // Refetch every minute
  });
}

/**
 * Hook to sync/rebuild the Smart Finder cache
 */
export function useSmartFinderSync() {
  const queryClient = useQueryClient();
  
  return useMutation({
    mutationFn: async () => {
      const res = await fetch(`${API_BASE}/smart-finder/sync`, {
        method: 'POST',
        headers: getAuthHeaders(),
      });
      if (!res.ok) {
        const error = await res.json().catch(() => ({ message: 'Sync failed' }));
        throw new Error(error.message || 'Sync failed');
      }
      return res.json();
    },
    onSuccess: () => {
      // Invalidate all smart finder related queries
      queryClient.invalidateQueries({ queryKey: ['smart-finder'] });
      queryClient.invalidateQueries({ queryKey: ['smart-schools'] });
      queryClient.invalidateQueries({ queryKey: ['smart-commodities'] });
    },
  });
}

/**
 * Hook to search schools with instant autocomplete
 */
export function useSmartSchoolSearch(query: string, enabled: boolean = true) {
  return useQuery<SmartFinderSchool[]>({
    queryKey: ['smart-schools', query],
    queryFn: async () => {
      const res = await fetch(`${API_BASE}/smart-finder/schools?q=${encodeURIComponent(query)}&limit=30`, {
        headers: getAuthHeaders(),
      });
      if (!res.ok) throw new Error('Failed to search schools');
      const data = await res.json();
      return data.data || [];
    },
    enabled,
    staleTime: 60 * 1000, // 1 minute
  });
}

/**
 * Hook to get all commodities
 */
export function useSmartCommodities(enabled: boolean = true) {
  return useQuery<string[]>({
    queryKey: ['smart-commodities'],
    queryFn: async () => {
      const res = await fetch(`${API_BASE}/smart-finder/commodities`, {
        headers: getAuthHeaders(),
      });
      if (!res.ok) throw new Error('Failed to get commodities');
      const data = await res.json();
      return data.data || [];
    },
    enabled,
    staleTime: 5 * 60 * 1000, // 5 minutes
  });
}

/**
 * Hook to get commodities for a specific school
 */
export function useSmartCommoditiesForSchool(schoolCode: string | null) {
  return useQuery<string[]>({
    queryKey: ['smart-commodities-school', schoolCode],
    queryFn: async () => {
      if (!schoolCode) return [];
      const res = await fetch(`${API_BASE}/smart-finder/commodities-for-school/${schoolCode}`, {
        headers: getAuthHeaders(),
      });
      if (!res.ok) throw new Error('Failed to get commodities');
      const data = await res.json();
      return data.commodities || [];
    },
    enabled: !!schoolCode,
    staleTime: 60 * 1000,
  });
}

/**
 * Hook to get school details (commodities + suppliers)
 */
export function useSmartSchoolDetails(schoolCode: string | null) {
  return useQuery<{
    school: SmartFinderSchool;
    commodities: string[];
    suppliers: SmartFinderSupplier[];
    query_time_ms: number;
  }>({
    queryKey: ['smart-school-details', schoolCode],
    queryFn: async () => {
      if (!schoolCode) throw new Error('School code required');
      const res = await fetch(`${API_BASE}/smart-finder/school/${schoolCode}`, {
        headers: getAuthHeaders(),
      });
      if (!res.ok) throw new Error('Failed to get school details');
      return res.json();
    },
    enabled: !!schoolCode,
    staleTime: 60 * 1000,
  });
}

/**
 * Hook to get the supplier for a school+commodity combination (THE KEY LOOKUP)
 */
export function useSmartSupplierLookup(schoolCode: string | null, commodity: string | null) {
  return useQuery<{
    school: SmartFinderSchool;
    commodity: string;
    suppliers: SmartFinderSupplier[];
    found: boolean;
    query_time_ms: number;
  }>({
    queryKey: ['smart-supplier-lookup', schoolCode, commodity],
    queryFn: async () => {
      if (!schoolCode || !commodity) throw new Error('School and commodity required');
      const res = await fetch(
        `${API_BASE}/smart-finder/school/${schoolCode}/commodity/${encodeURIComponent(commodity)}`,
        { headers: getAuthHeaders() }
      );
      if (!res.ok) throw new Error('Failed to lookup supplier');
      return res.json();
    },
    enabled: !!schoolCode && !!commodity,
    staleTime: 60 * 1000,
  });
}

/**
 * Universal search hook
 */
export function useSmartSearch(params: {
  school?: string;
  commodity?: string;
  region?: string;
}) {
  const queryString = new URLSearchParams();
  if (params.school) queryString.set('school', params.school);
  if (params.commodity) queryString.set('commodity', params.commodity);
  if (params.region) queryString.set('region', params.region);
  
  const hasParams = !!(params.school || params.commodity || params.region);
  
  return useQuery<SmartFinderSearchResult>({
    queryKey: ['smart-search', params],
    queryFn: async () => {
      const res = await fetch(`${API_BASE}/smart-finder/search?${queryString.toString()}`, {
        headers: getAuthHeaders(),
      });
      if (!res.ok) throw new Error('Search failed');
      return res.json();
    },
    enabled: hasParams,
    staleTime: 30 * 1000,
  });
}

// ============================================================================
// MAIN HOOK - Smart Finder with complete state management
// ============================================================================

export function useSmartFinder() {
  const queryClient = useQueryClient();
  
  // State
  const [schoolQuery, setSchoolQuery] = useState('');
  const [selectedSchool, setSelectedSchool] = useState<SmartFinderSchool | null>(null);
  const [selectedCommodity, setSelectedCommodity] = useState<string | null>(null);
  const [showSchoolDropdown, setShowSchoolDropdown] = useState(false);
  const [showCommodityDropdown, setShowCommodityDropdown] = useState(false);
  
  // Debounced school query
  const [debouncedSchoolQuery, setDebouncedSchoolQuery] = useState('');
  useEffect(() => {
    const timer = setTimeout(() => setDebouncedSchoolQuery(schoolQuery), 200);
    return () => clearTimeout(timer);
  }, [schoolQuery]);
  
  // Queries
  const statusQuery = useSmartFinderStatus();
  const syncMutation = useSmartFinderSync();
  
  const schoolsQuery = useSmartSchoolSearch(
    debouncedSchoolQuery,
    !selectedSchool && showSchoolDropdown
  );
  
  const commoditiesQuery = useSmartCommoditiesForSchool(selectedSchool?.code ?? null);
  
  const supplierQuery = useSmartSupplierLookup(
    selectedSchool?.code ?? null,
    selectedCommodity
  );
  
  // Actions
  const selectSchool = useCallback((school: SmartFinderSchool) => {
    setSelectedSchool(school);
    setSchoolQuery(school.name);
    setShowSchoolDropdown(false);
    setSelectedCommodity(null); // Reset commodity when school changes
  }, []);
  
  const clearSchool = useCallback(() => {
    setSelectedSchool(null);
    setSchoolQuery('');
    setSelectedCommodity(null);
  }, []);
  
  const selectCommodity = useCallback((commodity: string) => {
    setSelectedCommodity(commodity);
    setShowCommodityDropdown(false);
  }, []);
  
  const clearCommodity = useCallback(() => {
    setSelectedCommodity(null);
  }, []);
  
  const clearAll = useCallback(() => {
    clearSchool();
    clearCommodity();
  }, [clearSchool, clearCommodity]);
  
  const syncCache = useCallback(async () => {
    return syncMutation.mutateAsync();
  }, [syncMutation]);
  
  // Computed
  const hasResult = !!(selectedSchool && selectedCommodity && supplierQuery.data?.found);
  const isSearching = schoolsQuery.isLoading || commoditiesQuery.isLoading || supplierQuery.isLoading;
  
  return {
    // Cache status
    cacheStatus: statusQuery.data,
    cacheLoading: statusQuery.isLoading,
    cacheValid: statusQuery.data?.valid ?? false,
    
    // Sync
    syncCache,
    isSyncing: syncMutation.isPending,
    syncError: syncMutation.error?.message,
    
    // School search
    schoolQuery,
    setSchoolQuery,
    schools: schoolsQuery.data ?? [],
    schoolsLoading: schoolsQuery.isLoading,
    selectedSchool,
    selectSchool,
    clearSchool,
    showSchoolDropdown,
    setShowSchoolDropdown,
    
    // Commodity selection
    commodities: commoditiesQuery.data ?? [],
    commoditiesLoading: commoditiesQuery.isLoading,
    selectedCommodity,
    selectCommodity,
    clearCommodity,
    showCommodityDropdown,
    setShowCommodityDropdown,
    
    // Result
    supplierResult: supplierQuery.data,
    supplierLoading: supplierQuery.isLoading,
    hasResult,
    
    // Query times
    queryTime: supplierQuery.data?.query_time_ms ?? null,
    
    // Helpers
    isSearching,
    clearAll,
    hasActiveFilters: !!(selectedSchool || selectedCommodity),
  };
}

export type SmartFinder = ReturnType<typeof useSmartFinder>;
