/**
 * useAiProgress - AI Validation Progress Tracking
 *
 * Manages progress state and time estimation for AI validation.
 * Supports server-based time estimation and live timer updates.
 */

import { useCallback, useRef, useEffect } from 'react';
import { useValidationStore } from '../../store/validationStore';
import type { AiValidationProgress } from '../../store/types';

// Fallback estimate when server doesn't provide one
const AVG_MS_PER_PRODUCT = 150;
const MIN_ESTIMATED_TIME_MS = 2000; // Minimum 2 seconds

/**
 * Hook for managing AI validation progress
 */
export const useAiProgress = () => {
  const setAiValidationProgress = useValidationStore((state) => state.setAiValidationProgress);
  const setAiValidationRunning = useValidationStore((state) => state.setAiValidationRunning);

  const timerRef = useRef<NodeJS.Timeout | null>(null);
  const startTimeRef = useRef<number>(0);
  const estimatedSecondsRef = useRef<number | null>(null);
  const promptLengthRef = useRef<number | null>(null);

  /**
   * Calculate progress percentage based on elapsed time and estimate
   */
  const calculateProgress = useCallback((elapsedMs: number): number => {
    if (estimatedSecondsRef.current && estimatedSecondsRef.current > 0) {
      const estimatedMs = estimatedSecondsRef.current * 1000;
      // Cap at 95% until complete
      return Math.min(95, (elapsedMs / estimatedMs) * 100);
    }
    // Fallback: slow progress without estimate
    return Math.min(95, (elapsedMs / 30000) * 50);
  }, []);

  /**
   * Start the live progress timer
   */
  const startTimer = useCallback(() => {
    // Clear any existing timer
    if (timerRef.current) {
      clearInterval(timerRef.current);
    }

    timerRef.current = setInterval(() => {
      const elapsedMs = Date.now() - startTimeRef.current;
      const elapsedSeconds = Math.floor(elapsedMs / 1000);
      const progressPercent = calculateProgress(elapsedMs);

      // Calculate remaining time
      let estimatedTimeRemaining: number | undefined;
      if (estimatedSecondsRef.current && estimatedSecondsRef.current > 0) {
        const remainingSeconds = Math.max(0, estimatedSecondsRef.current - elapsedSeconds);
        estimatedTimeRemaining = remainingSeconds * 1000;
      }

      // Update progress state with new elapsed time
      setAiValidationProgress((prev) => {
        if (!prev || prev.status === 'complete' || prev.status === 'error') {
          return prev;
        }
        return {
          ...prev,
          elapsedSeconds,
          progressPercent,
          estimatedTimeRemaining,
        };
      });
    }, 1000);
  }, [calculateProgress, setAiValidationProgress]);

  /**
   * Set the server-provided time estimate
   */
  const setEstimate = useCallback(
    (estimatedSeconds: number | null, promptLength: number | null) => {
      estimatedSecondsRef.current = estimatedSeconds;
      promptLengthRef.current = promptLength;

      // Update progress state with estimate
      setAiValidationProgress((prev) => {
        if (!prev) return prev;
        return {
          ...prev,
          estimatedTotalSeconds: estimatedSeconds ?? undefined,
          promptLength: promptLength ?? undefined,
          estimatedTimeRemaining: estimatedSeconds ? estimatedSeconds * 1000 : prev.estimatedTimeRemaining,
        };
      });
    },
    [setAiValidationProgress]
  );

  /**
   * Start progress tracking
   */
  const startProgress = useCallback(
    (totalProducts: number, estimatedSeconds?: number, promptLength?: number) => {
      startTimeRef.current = Date.now();
      estimatedSecondsRef.current = estimatedSeconds ?? null;
      promptLengthRef.current = promptLength ?? null;

      // Calculate fallback estimate if server didn't provide one
      const fallbackEstimateMs = Math.max(
        totalProducts * AVG_MS_PER_PRODUCT,
        MIN_ESTIMATED_TIME_MS
      );

      const initialProgress: AiValidationProgress = {
        current: 0,
        total: totalProducts,
        status: 'preparing',
        message: 'Preparing data for AI validation...',
        startTime: startTimeRef.current,
        estimatedTimeRemaining: estimatedSeconds
          ? estimatedSeconds * 1000
          : fallbackEstimateMs,
        estimatedTotalSeconds: estimatedSeconds,
        promptLength: promptLength,
        elapsedSeconds: 0,
        progressPercent: 0,
      };

      setAiValidationRunning(true);
      setAiValidationProgress(initialProgress);

      // Start the live timer
      startTimer();
    },
    [setAiValidationProgress, setAiValidationRunning, startTimer]
  );

  /**
   * Update progress status and message
   */
  const updateProgress = useCallback(
    (current: number, total: number, status: AiValidationProgress['status'], message?: string) => {
      const elapsedMs = Date.now() - startTimeRef.current;
      const elapsedSeconds = Math.floor(elapsedMs / 1000);
      const progressPercent = calculateProgress(elapsedMs);

      // Calculate remaining time
      let estimatedTimeRemaining: number | undefined;
      if (estimatedSecondsRef.current && estimatedSecondsRef.current > 0) {
        const remainingSeconds = Math.max(0, estimatedSecondsRef.current - elapsedSeconds);
        estimatedTimeRemaining = remainingSeconds * 1000;
      }

      setAiValidationProgress((prev) => ({
        current,
        total,
        status,
        message,
        startTime: startTimeRef.current,
        estimatedTimeRemaining,
        estimatedTotalSeconds: estimatedSecondsRef.current ?? prev?.estimatedTotalSeconds,
        promptLength: promptLengthRef.current ?? prev?.promptLength,
        elapsedSeconds,
        progressPercent,
      }));
    },
    [calculateProgress, setAiValidationProgress]
  );

  /**
   * Complete progress
   */
  const completeProgress = useCallback(() => {
    // Stop the timer
    if (timerRef.current) {
      clearInterval(timerRef.current);
      timerRef.current = null;
    }

    const elapsedMs = Date.now() - startTimeRef.current;
    const elapsedSeconds = Math.floor(elapsedMs / 1000);

    setAiValidationProgress((prev) => ({
      current: prev?.total ?? 1,
      total: prev?.total ?? 1,
      status: 'complete',
      message: `Validation complete in ${(elapsedMs / 1000).toFixed(1)}s`,
      startTime: startTimeRef.current,
      estimatedTimeRemaining: 0,
      estimatedTotalSeconds: estimatedSecondsRef.current ?? undefined,
      promptLength: promptLengthRef.current ?? undefined,
      elapsedSeconds,
      progressPercent: 100,
    }));
  }, [setAiValidationProgress]);

  /**
   * Set error state
   */
  const setError = useCallback(
    (message: string) => {
      // Stop the timer
      if (timerRef.current) {
        clearInterval(timerRef.current);
        timerRef.current = null;
      }

      const elapsedMs = Date.now() - startTimeRef.current;
      const elapsedSeconds = Math.floor(elapsedMs / 1000);

      setAiValidationProgress((prev) => ({
        current: 0,
        total: prev?.total ?? 0,
        status: 'error',
        message,
        startTime: startTimeRef.current,
        estimatedTimeRemaining: 0,
        elapsedSeconds,
        progressPercent: prev?.progressPercent,
      }));
    },
    [setAiValidationProgress]
  );

  /**
   * Clear progress and stop tracking
   */
  const clearProgress = useCallback(() => {
    if (timerRef.current) {
      clearInterval(timerRef.current);
      timerRef.current = null;
    }
    estimatedSecondsRef.current = null;
    promptLengthRef.current = null;
    setAiValidationProgress(null);
    setAiValidationRunning(false);
  }, [setAiValidationProgress, setAiValidationRunning]);

  // Cleanup on unmount
  useEffect(() => {
    return () => {
      if (timerRef.current) {
        clearInterval(timerRef.current);
      }
    };
  }, []);

  return {
    startProgress,
    updateProgress,
    completeProgress,
    setError,
    clearProgress,
    setEstimate,
  };
};
