import { useState, useEffect, useCallback } from 'react';
import { useAuth } from '@/contexts/AuthContext';
import { supabase } from '@/integrations/supabase/client';

export interface BuildProgress {
  id: string;
  app_name: string;
  platform: 'android' | 'ios';
  progress: number;
  message: string;
  status: 'building' | 'completed' | 'failed';
  download_url?: string;
  file_size_bytes?: number;
  error_message?: string;
}

interface UseBuildProgressOptions {
  onComplete?: (build: BuildProgress) => void;
  onError?: (build: BuildProgress) => void;
}

export function useBuildProgress(options: UseBuildProgressOptions = {}) {
  const { user } = useAuth();
  const [activeBuilds, setActiveBuilds] = useState<Map<string, BuildProgress>>(new Map());
  const [isConnected, setIsConnected] = useState(false);

  // Subscribe to build updates via Supabase Realtime
  useEffect(() => {
    if (!user) return;

    const channel = supabase
      .channel('build-progress')
      .on(
        'postgres_changes',
        {
          event: 'UPDATE',
          schema: 'public',
          table: 'app_builds',
          filter: `user_id=eq.${user.id}`,
        },
        (payload) => {
          const build = payload.new as unknown as BuildProgress;
          
          setActiveBuilds((prev) => {
            const updated = new Map(prev);
            
            if (build.status === 'completed') {
              updated.delete(build.id);
              options.onComplete?.(build);
            } else if (build.status === 'failed') {
              updated.delete(build.id);
              options.onError?.(build);
            } else {
              updated.set(build.id, build);
            }
            
            return updated;
          });
        }
      )
      .subscribe((status) => {
        setIsConnected(status === 'SUBSCRIBED');
      });

    return () => {
      supabase.removeChannel(channel);
    };
  }, [user, options.onComplete, options.onError]);

  // Add a new build to track
  const trackBuild = useCallback((buildId: string, appName: string, platform: 'android' | 'ios') => {
    const build: BuildProgress = {
      id: buildId,
      app_name: appName,
      platform,
      progress: 0,
      message: 'Starting build...',
      status: 'building',
    };
    
    setActiveBuilds((prev) => {
      const updated = new Map(prev);
      updated.set(buildId, build);
      return updated;
    });
  }, []);

  // Remove a build from tracking
  const untrackBuild = useCallback((buildId: string) => {
    setActiveBuilds((prev) => {
      const updated = new Map(prev);
      updated.delete(buildId);
      return updated;
    });
  }, []);

  // Get all active builds as array
  const getActiveBuilds = useCallback(() => {
    return Array.from(activeBuilds.values());
  }, [activeBuilds]);

  return {
    activeBuilds: getActiveBuilds(),
    isConnected,
    trackBuild,
    untrackBuild,
    hasActiveBuilds: activeBuilds.size > 0,
  };
}

export default useBuildProgress;
