'use client';

import { useEffect, useRef, useState, useMemo } from 'react';
import {
  AlertTriangle, Loader2, Clock, WifiOff,
  Upload, Search, Languages, Wrench, CheckCircle2,
  FileText, Timer, Gauge, Activity,
  RotateCcw,
} from 'lucide-react';
import { cn } from '@/lib/utils';
import { useI18n } from '@/lib/i18n';

/* ── Types ──────────────────────────────────────────────────────── */
interface TranslationProgressProps {
  progress: number;
  currentStep: string;
  estimatedRemaining: number | null;
  error: string | null;
  isPolling?: boolean;
  isUploading?: boolean;
  isCompleted?: boolean;
  /** Extra info for the monitor panel */
  fileName?: string | null;
  sourceLang?: string;
  targetLang?: string;
  providerLabel?: string | null;
  onCancel?: () => void;
}

/* ── Pipeline step definition ───────────────────────────────────── */
interface PipelineStep {
  id: string;
  label: string;
  icon: React.ElementType;
  /** Progress range where this step is active */
  startsAt: number;
}

const PIPELINE_STEPS: PipelineStep[] = [
  { id: 'upload', label: 'Upload', icon: Upload, startsAt: 0 },
  { id: 'analyze', label: 'Analyse', icon: Search, startsAt: 10 },
  { id: 'translate', label: 'Traduction', icon: Languages, startsAt: 25 },
  { id: 'rebuild', label: 'Reconstruction', icon: Wrench, startsAt: 75 },
  { id: 'finalize', label: 'Finalisation', icon: CheckCircle2, startsAt: 92 },
];

/* ── Simulated activity messages ────────────────────────────────── */
const ACTIVITY_MESSAGES: Record<string, string[]> = {
  upload: [
    'Fichier reçu avec succès',
    'Vérification du format...',
  ],
  analyze: [
    'Analyse de la structure du document',
    'Extraction des segments de texte',
    'Détection de la langue source',
  ],
  translate: [
    'Connexion au moteur de traduction',
    'Traduction des segments en cours...',
    'Traitement des tableaux et graphiques',
    'Conservation de la mise en forme',
    'Validation des traductions',
  ],
  rebuild: [
    'Reconstruction du document traduit',
    'Application de la mise en forme originale',
    'Vérification de l\'intégrité',
  ],
  finalize: [
    'Contrôle qualité final',
    'Préparation du téléchargement',
  ],
};

/* ── Helpers ────────────────────────────────────────────────────── */
function getActiveStepIndex(progress: number): number {
  let idx = 0;
  for (let i = PIPELINE_STEPS.length - 1; i >= 0; i--) {
    if (progress >= PIPELINE_STEPS[i].startsAt) { idx = i; break; }
  }
  return idx;
}

function formatTime(seconds: number | null): string {
  if (seconds === null || seconds <= 0) return '';
  if (seconds < 60) return `~${seconds}s`;
  const m = Math.floor(seconds / 60);
  const s = seconds % 60;
  return `~${m}m${s > 0 ? ` ${s}s` : ''}`;
}

function formatElapsed(totalSeconds: number): string {
  const m = Math.floor(totalSeconds / 60);
  const s = totalSeconds % 60;
  return `${m}:${s.toString().padStart(2, '0')}`;
}

/* ── Component ──────────────────────────────────────────────────── */
export function TranslationProgress({
  progress,
  currentStep,
  estimatedRemaining,
  error,
  isPolling = true,
  isUploading = false,
  isCompleted = false,
  fileName,
  sourceLang,
  targetLang,
  providerLabel,
  onCancel,
}: TranslationProgressProps) {
  const { t } = useI18n();
  const [animate, setAnimate] = useState(false);
  const [elapsed, setElapsed] = useState(0);
  const [activities, setActivities] = useState<{ text: string; time: string }[]>([]);
  const prevStepIdx = useRef(-1);
  const elapsedRef = useRef<ReturnType<typeof setInterval> | null>(null);

  // Animate progress bar on first progress
  useEffect(() => {
    if (progress > 0) setAnimate(true);
    else {
      setAnimate(false);
      const tid = setTimeout(() => setAnimate(true), 50);
      return () => clearTimeout(tid);
    }
  }, [progress]);

  // Elapsed timer
  useEffect(() => {
    if (isCompleted || error) {
      if (elapsedRef.current) clearInterval(elapsedRef.current);
      return;
    }
    elapsedRef.current = setInterval(() => setElapsed(e => e + 1), 1000);
    return () => { if (elapsedRef.current) clearInterval(elapsedRef.current); };
  }, [isCompleted, error]);

  // Activity log — push messages when step changes
  const activeIdx = getActiveStepIndex(progress);
  useEffect(() => {
    if (activeIdx !== prevStepIdx.current) {
      prevStepIdx.current = activeIdx;
      const step = PIPELINE_STEPS[activeIdx];
      if (!step) return;
      const msgs = ACTIVITY_MESSAGES[step.id] || [];
      msgs.forEach((msg, i) => {
        setTimeout(() => {
          setActivities(prev => {
            const next = [{ text: msg, time: formatElapsed(elapsed) }, ...prev];
            return next.slice(0, 10);
          });
        }, i * 600);
      });
    }
  }, [activeIdx, elapsed]);

  // Simulated stats
  const totalSegments = 142;
  const totalChars = 12847;
  const doneSeg = Math.round(totalSegments * progress / 100);
  const doneChars = Math.round(totalChars * progress / 100);
  const speed = elapsed > 3 ? (doneSeg / (elapsed / 60)).toFixed(1) : '—';

  /* ── Error state ──────────────────────────────────────────────── */
  if (error) {
    return (
      <div className="flex flex-col gap-6">
        <div className="rounded-xl bg-destructive/10 border border-destructive/20 p-5" role="alert" aria-live="assertive">
          <div className="flex items-start gap-3">
            <AlertTriangle className="size-5 text-destructive shrink-0 mt-0.5" />
            <div>
              <p className="text-sm font-semibold text-destructive mb-1">{t('dashboard.translate.progress.failedTitle')}</p>
              <p className="text-sm text-destructive/80">{error}</p>
            </div>
          </div>
        </div>
        {onCancel && (
          <button onClick={onCancel} className="mx-auto flex items-center gap-2 rounded-lg border border-border px-4 py-2 text-sm font-medium text-muted-foreground transition hover:bg-muted hover:text-foreground">
            <RotateCcw className="size-4" />{t('dashboard.translate.actions.tryAgain')}
          </button>
        )}
      </div>
    );
  }

  const showConnectionLost = !isPolling && !isCompleted && !isUploading;

  return (
    <div className="flex flex-col gap-0 overflow-hidden rounded-2xl border border-border bg-card shadow-sm">

      {/* ═══ Header band ═══ */}
      <div className="relative overflow-hidden border-b border-border bg-gradient-to-r from-primary/5 via-primary/8 to-primary/3 px-6 py-4">
        <div className="flex items-center justify-between gap-4">
          <div className="flex items-center gap-3">
            <div className="flex size-9 items-center justify-center rounded-lg bg-primary/10">
              <Loader2 className="size-5 animate-spin text-primary" />
            </div>
            <div>
              <h2 className="text-base font-bold text-foreground leading-tight">Traduction en cours</h2>
              {fileName && (
                <p className="text-xs text-muted-foreground mt-0.5 truncate max-w-[260px]">{fileName}</p>
              )}
            </div>
          </div>
          {estimatedRemaining != null && estimatedRemaining > 0 && (
            <div className="flex items-center gap-1.5 rounded-full bg-primary/10 px-3 py-1.5 text-xs font-semibold text-primary">
              <Clock className="size-3.5" />
              {formatTime(estimatedRemaining)}
            </div>
          )}
        </div>
      </div>

      <div className="flex flex-col gap-6 p-6">

        {/* ═══ Pipeline Stepper ═══ */}
        <div className="flex items-start justify-between">
          {PIPELINE_STEPS.map((step, i) => {
            const isActive = i === activeIdx;
            const isDone = i < activeIdx;
            const Icon = step.icon;

            return (
              <div key={step.id} className="flex flex-col items-center gap-1.5 relative" style={{ flex: i < PIPELINE_STEPS.length - 1 ? 1 : 'none' }}>
                {/* Step circle + connector */}
                <div className="flex items-center w-full">
                  <div className={cn(
                    'flex size-9 shrink-0 items-center justify-center rounded-full transition-all duration-500',
                    isDone
                      ? 'bg-primary text-primary-foreground shadow-md shadow-primary/20'
                      : isActive
                      ? 'bg-primary text-primary-foreground shadow-lg shadow-primary/25 ring-[3px] ring-primary/20'
                      : 'bg-muted text-muted-foreground',
                  )}>
                    {isDone ? (
                      <CheckCircle2 className="size-4" />
                    ) : (
                      <Icon className={cn('size-4', isActive && 'animate-pulse')} />
                    )}
                  </div>
                  {i < PIPELINE_STEPS.length - 1 && (
                    <div className={cn(
                      'mx-1 h-[2px] flex-1 rounded-full transition-colors duration-500',
                      i < activeIdx ? 'bg-primary' : 'bg-border',
                    )} />
                  )}
                </div>
                <span className={cn(
                  'text-[11px] font-medium transition-colors duration-300',
                  isDone || isActive ? 'text-primary' : 'text-muted-foreground',
                )}>
                  {step.label}
                </span>
              </div>
            );
          })}
        </div>

        {/* ═══ Progress bar ═══ */}
        <div className="space-y-2">
          <div className="flex items-center justify-between gap-4">
            <p className="text-sm font-medium text-foreground animate-pulse truncate">
              {currentStep || t('dashboard.translate.progress.processingFallback')}
            </p>
            <p className="text-2xl font-black tabular-nums tracking-tight text-primary shrink-0">
              {Math.round(progress)}%
            </p>
          </div>
          <div className="h-3 w-full overflow-hidden rounded-full bg-primary/10">
            <div
              className={cn(
                'h-full rounded-full transition-all duration-700 ease-out',
                animate && 'bg-gradient-to-r from-primary via-primary/80 to-primary',
              )}
              style={{ width: `${Math.max(0, progress)}%` }}
            />
          </div>
        </div>

        {/* ═══ Live Stats Grid ═══ */}
        <div className="grid grid-cols-4 gap-2.5">
          <StatCard
            icon={<FileText className="size-4" />}
            value={`${doneSeg}/${totalSegments}`}
            label="Segments"
          />
          <StatCard
            icon={<Activity className="size-4" />}
            value={doneChars.toLocaleString()}
            label="Caractères"
          />
          <StatCard
            icon={<Gauge className="size-4" />}
            value={speed}
            label="Seg/min"
          />
          <StatCard
            icon={<Timer className="size-4" />}
            value={formatElapsed(elapsed)}
            label="Écoulé"
          />
        </div>

        {/* ═══ Activity Feed ═══ */}
        {activities.length > 0 && (
          <div>
            <p className="mb-2 flex items-center gap-1.5 text-[10px] font-semibold uppercase tracking-wider text-muted-foreground">
              <Activity className="size-3" /> Journal d&apos;activité
            </p>
            <div className="max-h-[100px] overflow-y-auto rounded-xl border border-border bg-muted/30">
              {activities.map((act, i) => (
                <div key={i} className="flex items-center gap-2.5 border-b border-border/50 px-3 py-1.5 last:border-0">
                  <div className="size-1.5 shrink-0 rounded-full bg-primary" />
                  <span className="flex-1 text-xs text-foreground">{act.text}</span>
                  <span className="text-[10px] tabular-nums text-muted-foreground">{act.time}</span>
                </div>
              ))}
            </div>
          </div>
        )}

        {/* ═══ Connection lost ═══ */}
        {showConnectionLost && (
          <div className="flex items-center gap-2 text-xs text-amber-600 dark:text-amber-400">
            <WifiOff className="size-3.5" />
            <span>{t('dashboard.translate.progress.connectionLost')}</span>
          </div>
        )}

        {/* ═══ Cancel button ═══ */}
        {onCancel && (
          <div className="flex justify-center pt-1">
            <button
              onClick={onCancel}
              className="flex items-center gap-2 rounded-lg border border-destructive/20 px-4 py-2 text-sm font-medium text-destructive transition hover:bg-destructive hover:text-white hover:border-destructive"
            >
              <RotateCcw className="size-4" />Annuler
            </button>
          </div>
        )}
      </div>
    </div>
  );
}

/* ── Stat card sub-component ────────────────────────────────────── */
function StatCard({ icon, value, label }: { icon: React.ReactNode; value: string; label: string }) {
  return (
    <div className="flex flex-col items-center gap-1 rounded-xl border border-border bg-muted/20 p-2.5 text-center">
      <div className="text-primary">{icon}</div>
      <p className="text-sm font-bold tabular-nums text-foreground leading-none">{value}</p>
      <p className="text-[10px] uppercase tracking-wider text-muted-foreground font-medium">{label}</p>
    </div>
  );
}
