/**
 * Live Allocations Hook
 * 
 * Connects directly to the GCX Allocation API for real-time allocation data.
 * This replaces the cached Smart Finder for allocation lookups.
 * 
 * API Endpoint: /api/allocations (Next.js proxy)
 */

import { useCallback, useState, useEffect } from 'react';
import { useQuery, useQueryClient } from '@tanstack/react-query';

// =============================================================================
// CONFIGURATION
// =============================================================================

const ALLOCATION_API_BASE = '/api';

// =============================================================================
// TYPES
// =============================================================================

export interface AllocationSchool {
  id: number;
  name: string;
  code: string;
  region: {
    id: number;
    code: string;
    name: string;
  };
}

export interface AllocationCommodity {
  id: number;
  name: string;
  description: string;
  unit_of_measure: string;
  is_processed_food: boolean;
  is_active: boolean;
}

export interface AllocationPurchaseOrder {
  id: number;
  po_id: string;
  status: string;
  currency: string;
  region: {
    id: number;
    code: string;
    name: string;
  };
}

export interface AllocationContract {
  id: number;
  contract_number: string;
  title: string;
  status: string;
  start_date: string;
  end_date: string;
}

export interface AllocationApplication {
  id: number;
  business_name: string;
  tracking_code: string;
  status: string;
  region: {
    id: number;
    code: string;
    name: string;
  };
}

export interface AllocationSupplier {
  id: number;
  full_name: string;
  email: string;
}

export interface Allocation {
  id: number;
  allocated_quantity: string;
  unit_price: string;
  line_value: string;
  school: AllocationSchool;
  commodity: AllocationCommodity;
  purchase_order: AllocationPurchaseOrder;
  contract: AllocationContract;
  application: AllocationApplication;
  supplier: AllocationSupplier;
}

export interface AllocationResponse {
  count: number;
  next: string | null;
  previous: string | null;
  results: Allocation[];
}

export interface LiveFinderSchool {
  code: string;
  name: string;
  region: string;
  regionCode: string;
}

export interface LiveFinderSupplier {
  id: number;
  supplier_id: number;
  supplier_name: string;
  business_name: string;
  email: string;
  contract_number: string;
  contract_status: string;
  total_qty: number;
  total_value: number;
  po_id: string;
}

// =============================================================================
// API HELPERS
// =============================================================================

const getAllocationHeaders = (): HeadersInit => ({
  'Accept': 'application/json',
});

/**
 * Fetch allocations from the live API
 */
async function fetchAllocations(params: Record<string, string>): Promise<AllocationResponse> {
  const queryString = new URLSearchParams(params).toString();
  const url = `${ALLOCATION_API_BASE}/allocations?${queryString}`;
  
  const response = await fetch(url, {
    headers: getAllocationHeaders(),
  });
  
  if (!response.ok) {
    throw new Error(`Allocation API error: ${response.status}`);
  }
  
  return response.json();
}

// =============================================================================
// HOOKS
// =============================================================================

/**
 * Hook to search for allocations by school code
 */
export function useLiveSchoolAllocations(schoolCode: string | null) {
  return useQuery<AllocationResponse>({
    queryKey: ['live-allocations', 'school', schoolCode],
    queryFn: () => fetchAllocations({ search: schoolCode! }),
    enabled: !!schoolCode && schoolCode.length >= 3,
    staleTime: 30 * 1000, // 30 seconds
    gcTime: 5 * 60 * 1000, // 5 minutes
  });
}

/**
 * Hook to search for allocations by supplier name
 */
export function useLiveSupplierAllocations(supplierName: string | null) {
  return useQuery<AllocationResponse>({
    queryKey: ['live-allocations', 'supplier', supplierName],
    queryFn: () => fetchAllocations({ supplier_name: supplierName! }),
    enabled: !!supplierName && supplierName.length >= 3,
    staleTime: 30 * 1000,
    gcTime: 5 * 60 * 1000,
  });
}

/**
 * Hook to get all allocations with pagination
 */
export function useLiveAllAllocations(page: number = 1) {
  return useQuery<AllocationResponse>({
    queryKey: ['live-allocations', 'all', page],
    queryFn: () => fetchAllocations({ page: String(page) }),
    staleTime: 60 * 1000, // 1 minute
    gcTime: 10 * 60 * 1000, // 10 minutes
  });
}

// =============================================================================
// MAIN HOOK - Live Allocation Finder with state management
// =============================================================================

export function useLiveAllocationFinder() {
  const queryClient = useQueryClient();
  
  // State
  const [schoolQuery, setSchoolQuery] = useState('');
  const [selectedSchool, setSelectedSchool] = useState<LiveFinderSchool | 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), 300);
    return () => clearTimeout(timer);
  }, [schoolQuery]);
  
  // Fetch allocations for the debounced search query (for school autocomplete)
  const schoolSearchQuery = useQuery<AllocationResponse>({
    queryKey: ['live-allocations', 'school-search', debouncedSchoolQuery],
    queryFn: () => fetchAllocations({ search: debouncedSchoolQuery }),
    enabled: !selectedSchool && showSchoolDropdown && debouncedSchoolQuery.length >= 2,
    staleTime: 30 * 1000,
  });
  
  // Fetch allocations for the selected school
  const schoolAllocationsQuery = useQuery<AllocationResponse>({
    queryKey: ['live-allocations', 'school', selectedSchool?.code],
    queryFn: () => fetchAllocations({ search: selectedSchool!.code }),
    enabled: !!selectedSchool?.code,
    staleTime: 30 * 1000,
  });
  
  // Extract unique schools from search results
  const schools: LiveFinderSchool[] = (schoolSearchQuery.data?.results || [])
    .reduce((acc: LiveFinderSchool[], allocation) => {
      const exists = acc.find(s => s.code === allocation.school.code);
      if (!exists) {
        acc.push({
          code: allocation.school.code,
          name: allocation.school.name,
          region: allocation.school.region.name,
          regionCode: allocation.school.region.code,
        });
      }
      return acc;
    }, [])
    .slice(0, 30); // Limit to 30 schools
  
  // Extract unique commodities from school allocations
  const commodities: string[] = (schoolAllocationsQuery.data?.results || [])
    .map(a => a.commodity.name)
    .filter((value, index, self) => self.indexOf(value) === index);
  
  // Get supplier for selected school + commodity
  const supplierResult = selectedSchool && selectedCommodity
    ? (schoolAllocationsQuery.data?.results || [])
        .filter(a => a.commodity.name === selectedCommodity)
        .map(a => ({
          id: a.application.id,
          supplier_id: a.supplier.id,
          supplier_name: a.supplier.full_name,
          business_name: a.application.business_name,
          email: a.supplier.email,
          contract_number: a.contract.contract_number,
          contract_status: a.contract.status,
          total_qty: parseFloat(a.allocated_quantity),
          total_value: parseFloat(a.line_value),
          po_id: a.purchase_order.po_id,
        } as LiveFinderSupplier))
    : [];
  
  // Actions
  const selectSchool = useCallback((school: LiveFinderSchool) => {
    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]);
  
  // Computed
  const hasResult = !!(selectedSchool && selectedCommodity && supplierResult.length > 0);
  const isSearching = schoolSearchQuery.isLoading || schoolAllocationsQuery.isLoading;
  
  return {
    // School search
    schoolQuery,
    setSchoolQuery,
    schools,
    schoolsLoading: schoolSearchQuery.isLoading,
    selectedSchool,
    selectSchool,
    clearSchool,
    showSchoolDropdown,
    setShowSchoolDropdown,
    
    // Commodity selection
    commodities,
    commoditiesLoading: schoolAllocationsQuery.isLoading,
    selectedCommodity,
    selectCommodity,
    clearCommodity,
    showCommodityDropdown,
    setShowCommodityDropdown,
    
    // Result
    supplierResult: {
      found: supplierResult.length > 0,
      suppliers: supplierResult,
      school: selectedSchool,
      commodity: selectedCommodity,
    },
    supplierLoading: schoolAllocationsQuery.isLoading,
    hasResult,
    
    // Query times
    queryTime: null, // Live API doesn't return query time
    
    // Helpers
    isSearching,
    clearAll,
    hasActiveFilters: !!(selectedSchool || selectedCommodity),
    
    // Raw data access
    rawAllocations: schoolAllocationsQuery.data?.results || [],
    totalAllocations: schoolAllocationsQuery.data?.count || 0,
  };
}

export default useLiveAllocationFinder;
