'use client';

import { useState, useEffect, useCallback, useRef } from 'react';
import { io, Socket } from 'socket.io-client';

const WS_URL = process.env.NEXT_PUBLIC_WS_URL || 'http://localhost:3000';

export interface RenderProgressState {
  isConnected: boolean;
  progress: number;
  stage: string;
  stageLabel: string;
  currentScene: number;
  totalScenes: number;
  eta: number;
  status: 'idle' | 'rendering' | 'completed' | 'failed';
  finalVideoUrl?: string;
  thumbnailUrl?: string;
  error?: string;
}

const STAGE_LABELS: Record<string, string> = {
  tts: '🔊 Seslendirme',
  image_generation: '🎨 Görsel Üretim',
  music_generation: '🎵 Müzik Üretim',
  compositing: '🎬 Video Birleştirme',
  encoding: '📦 Kodlama',
  uploading: '☁️ Yükleme',
};

/**
 * WebSocket hook — proje bazlı render ilerleme takibi.
 * Sadece proje detay sayfasında aktif olmalı.
 */
export function useRenderProgress(projectId: string | undefined): RenderProgressState {
  const [state, setState] = useState<RenderProgressState>({
    isConnected: false,
    progress: 0,
    stage: '',
    stageLabel: '',
    currentScene: 0,
    totalScenes: 0,
    eta: 0,
    status: 'idle',
  });

  const socketRef = useRef<Socket | null>(null);

  const cleanup = useCallback(() => {
    if (socketRef.current) {
      if (projectId) {
        socketRef.current.emit('leave:project', { projectId });
      }
      socketRef.current.disconnect();
      socketRef.current = null;
    }
  }, [projectId]);

  useEffect(() => {
    if (!projectId) return;

    const socket = io(`${WS_URL}/ws`, {
      transports: ['websocket', 'polling'],
      reconnection: true,
      reconnectionAttempts: 5,
      reconnectionDelay: 2000,
    });

    socketRef.current = socket;

    socket.on('connect', () => {
      setState((prev) => ({ ...prev, isConnected: true }));
      socket.emit('join:project', { projectId });
    });

    socket.on('disconnect', () => {
      setState((prev) => ({ ...prev, isConnected: false }));
    });

    // Render ilerleme
    socket.on('render:progress', (data) => {
      if (data.projectId === projectId) {
        setState((prev) => ({
          ...prev,
          progress: data.progress,
          stage: data.stage,
          stageLabel: STAGE_LABELS[data.stage] || data.stageLabel || data.stage,
          currentScene: data.currentScene || prev.currentScene,
          totalScenes: data.totalScenes || prev.totalScenes,
          eta: data.eta || 0,
          status: 'rendering',
        }));
      }
    });

    // Render tamamlandı
    socket.on('render:completed', (data) => {
      if (data.projectId === projectId) {
        setState((prev) => ({
          ...prev,
          progress: 100,
          status: 'completed',
          finalVideoUrl: data.finalVideoUrl,
          thumbnailUrl: data.thumbnailUrl,
          stage: 'completed',
          stageLabel: '✅ Tamamlandı',
        }));
      }
    });

    // Render hatası
    socket.on('render:failed', (data) => {
      if (data.projectId === projectId) {
        setState((prev) => ({
          ...prev,
          status: 'failed',
          error: data.error,
          stage: 'failed',
          stageLabel: '❌ Hata',
        }));
      }
    });

    // Proje status change
    socket.on('project:status', (data) => {
      if (data.projectId === projectId) {
        if (data.status === 'COMPLETED') {
          setState((prev) => ({ ...prev, status: 'completed', progress: 100 }));
        } else if (data.status === 'FAILED') {
          setState((prev) => ({ ...prev, status: 'failed' }));
        }
      }
    });

    return cleanup;
  }, [projectId, cleanup]);

  return state;
}
