'use client';

import { useEffect, useRef } from 'react';
import { X, Loader2, CheckCircle2, XCircle } from 'lucide-react';
import { Button } from '@/components/ui/Button';

export interface ProgressLogEntry {
  label: string;
  status: 'success' | 'error';
  detail?: string;
}

interface ProgressModalProps {
  open: boolean;
  title: string;
  current: number;
  total: number; // 0 = indeterminate
  currentLabel: string;
  logs: ProgressLogEntry[];
  onCancel: () => void;
}

export function ProgressModal({ open, title, current, total, currentLabel, logs, onCancel }: ProgressModalProps) {
  const logsEndRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    logsEndRef.current?.scrollIntoView({ behavior: 'smooth' });
  }, [logs.length]);

  if (!open) return null;

  const isIndeterminate = total === 0;
  const progress = total > 0 ? (current / total) * 100 : 0;
  const isDone = !isIndeterminate && current >= total;

  return (
    <>
      <style>{`
        @keyframes progress-indeterminate {
          0% { margin-left: -30%; }
          50% { margin-left: 80%; }
          100% { margin-left: -30%; }
        }
      `}</style>
      <div className="fixed inset-0 z-50 flex items-center justify-center">
        <div
          className="absolute inset-0 bg-black/40 backdrop-blur-sm"
          onClick={isDone ? onCancel : undefined}
        />
        <div className="relative bg-white rounded-xl shadow-2xl border border-stone-200 w-full max-w-lg mx-4 overflow-hidden">
          {/* Header */}
          <div className="px-5 py-4 border-b border-stone-100 flex items-center justify-between">
            <h3 className="text-sm font-semibold text-stone-900">{title}</h3>
            {isDone && (
              <button onClick={onCancel} className="text-stone-400 hover:text-stone-600 transition-colors">
                <X className="w-4 h-4" />
              </button>
            )}
          </div>

          {/* Progress */}
          <div className="px-5 py-4 space-y-3">
            {isIndeterminate ? (
              <div className="w-full h-1.5 bg-stone-100 rounded-full overflow-hidden">
                <div
                  className="h-full w-[30%] bg-indigo-500 rounded-full"
                  style={{ animation: 'progress-indeterminate 1.5s ease-in-out infinite' }}
                />
              </div>
            ) : (
              <>
                <div className="flex items-center justify-between text-xs">
                  <span className="font-medium text-stone-500">
                    {isDone ? 'Completado' : `${current} de ${total}`}
                  </span>
                  <span className="text-stone-400">{Math.round(progress)}%</span>
                </div>
                <div className="w-full h-1.5 bg-stone-100 rounded-full overflow-hidden">
                  <div
                    className={`h-full rounded-full transition-all duration-500 ${isDone ? 'bg-emerald-500' : 'bg-indigo-500'}`}
                    style={{ width: `${progress}%` }}
                  />
                </div>
              </>
            )}

            {!isDone && (
              <div className="flex items-center gap-2">
                <Loader2 className="w-3.5 h-3.5 text-indigo-500 animate-spin flex-shrink-0" />
                <span className="text-sm text-stone-600 truncate">{currentLabel}</span>
              </div>
            )}

            {isDone && logs.length > 0 && (() => {
              const errors = logs.filter(l => l.status === 'error').length;
              const successes = logs.filter(l => l.status === 'success').length;
              return (
                <div className="flex items-center gap-2">
                  {errors > 0 ? (
                    <XCircle className="w-3.5 h-3.5 text-amber-500 flex-shrink-0" />
                  ) : (
                    <CheckCircle2 className="w-3.5 h-3.5 text-emerald-500 flex-shrink-0" />
                  )}
                  <span className="text-sm text-stone-700">
                    {errors > 0 ? `${successes} completados, ${errors} con error` : 'Proceso completado'}
                  </span>
                </div>
              );
            })()}
          </div>

          {/* Logs */}
          {logs.length > 0 && (
            <div className="px-5 pb-3 max-h-48 overflow-y-auto border-t border-stone-50">
              <div className="space-y-1 pt-3">
                {logs.map((log, i) => (
                  <div key={i} className="flex items-start gap-2 text-xs">
                    {log.status === 'success' ? (
                      <CheckCircle2 className="w-3 h-3 text-emerald-500 flex-shrink-0 mt-0.5" />
                    ) : (
                      <XCircle className="w-3 h-3 text-red-500 flex-shrink-0 mt-0.5" />
                    )}
                    <span className={log.status === 'error' ? 'text-red-600' : 'text-stone-500'}>{log.label}</span>
                    {log.detail && (
                      <span className="text-stone-300 ml-auto truncate flex-shrink-0 max-w-[200px]">— {log.detail}</span>
                    )}
                  </div>
                ))}
                <div ref={logsEndRef} />
              </div>
            </div>
          )}

          {/* Actions */}
          <div className="px-5 py-3 border-t border-stone-100 flex justify-end">
            {isDone ? (
              <Button size="sm" onClick={onCancel}>Cerrar</Button>
            ) : (
              <Button size="sm" variant="danger" onClick={onCancel}>
                Cancelar
              </Button>
            )}
          </div>
        </div>
      </div>
    </>
  );
}
