"use client";
import { LuFile, LuLoader, LuCheck, LuLightbulb, LuImage } from "react-icons/lu";
import { ManagedFile } from "../page";

interface Props {
  files: ManagedFile[];
  onCancel?: () => void;
}

const formatFileSize = (bytes: number): string => {
  if (bytes < 1024) return bytes + ' B';
  if (bytes < 1024 * 1024) return (bytes / 1024).toFixed(1) + ' KB';
  return (bytes / (1024 * 1024)).toFixed(1) + ' MB';
};

const getFileFormat = (mimeType: string): string => {
  if (mimeType.startsWith('image/')) {
    return mimeType.split('/')[1].toUpperCase();
  }
  if (mimeType === 'application/pdf') return 'PDF';
  return 'FILE';
};

export default function Step3Processing({ files, onCancel }: Props) {
  const processingSteps = [
    { name: "Detectando texto", description: "Motor OCR activado con éxito", progressThreshold: 25 },
    { name: "Extrayendo campos", description: "Identificación de claves y valores finalizada", progressThreshold: 50 },
    { name: "Validando y guardando", description: "Verificando integridad de datos en base de datos", progressThreshold: 75 },
  ];

  // Calcular tiempo estimado basado en el progreso promedio
  const avgProgress = files.reduce((acc, f) => acc + f.progress, 0) / files.length;
  const estimatedTime = Math.max(5, Math.round((100 - avgProgress) * 0.3));

  return (
    <>
      {/* Header */}
      <div className="text-center mb-8">
        <h2 className="text-2xl font-bold text-text">Procesando Documento</h2>
        <p className="text-text-muted text-sm mt-2">
          Analizando el documento y extrayendo información mediante IA...
        </p>
      </div>

      {/* Card principal */}
      <div className="bg-background-alt rounded-xl border border-border-subtle p-6">
        {files.map(file => (
          <div key={file.id} className="space-y-6">
            {/* Info del archivo */}
            <div className="flex items-center gap-4">
              <div className="w-12 h-12 rounded-lg bg-primary-faint flex items-center justify-center flex-shrink-0">
                <LuImage className="h-6 w-6 text-primary" />
              </div>
              <div>
                <p className="font-bold text-text text-sm">
                  {file.file.name}
                </p>
                <p className="text-xs text-text-muted mt-0.5">
                  Tamaño: {formatFileSize(file.file.size)} • Formato: {getFileFormat(file.file.type)}
                </p>
              </div>
            </div>

            {/* Barra de progreso general */}
            <div>
              <div className="flex items-center justify-between mb-2">
                <span className="text-sm font-semibold text-text">Progreso general</span>
                <span className="text-sm font-bold text-primary">{file.progress}%</span>
              </div>
              <div className="relative w-full bg-border-subtle rounded-full h-2.5 overflow-hidden">
                <div
                  className="bg-primary h-full rounded-full transition-all duration-500 ease-out"
                  style={{ width: `${file.progress}%` }}
                />
              </div>
            </div>

            {/* Lista de pasos */}
            <div className="space-y-3">
              {processingSteps.map((step, idx) => {
                const isCompleted = file.progress >= step.progressThreshold;
                const isInProgress = !isCompleted && file.progress >= step.progressThreshold - 25;

                return (
                  <div
                    key={step.name}
                    className="flex items-center justify-between bg-background border border-border-subtle rounded-lg p-4"
                  >
                    <div className="flex items-center gap-4">
                      {/* Icono de estado */}
                      <div className={`w-8 h-8 rounded-full flex items-center justify-center ${isCompleted
                        ? "bg-success-background"
                        : isInProgress
                          ? "bg-primary-faint"
                          : "bg-background-alt"
                        }`}>
                        {isCompleted ? (
                          <LuCheck className="h-4 w-4 text-success" />
                        ) : isInProgress ? (
                          <LuLoader className="h-4 w-4 text-primary animate-spin" />
                        ) : (
                          <span className="w-2 h-2 rounded-full bg-border-subtle" />
                        )}
                      </div>
                      <div>
                        <p className="font-semibold text-text text-sm">{step.name}</p>
                        <p className="text-xs text-text-muted">{step.description}</p>
                      </div>
                    </div>
                    {/* Estado */}
                    <span className={`text-xs font-bold uppercase ${isCompleted
                      ? "text-success"
                      : isInProgress
                        ? "text-primary"
                        : "text-text-subtle"
                      }`}>
                      {isCompleted ? "Completado" : isInProgress ? "En curso" : "Pendiente"}
                    </span>
                  </div>
                );
              })}
            </div>

            {/* Footer con tiempo y cancelar */}
            <div className="flex items-center justify-between pt-4 border-t border-border-subtle">
              <p className="text-sm text-text-muted">
                Tiempo estimado restante: <span className="font-semibold text-text">{estimatedTime} segundos</span>
              </p>
              {onCancel && (
                <button
                  onClick={onCancel}
                  className="text-sm font-medium text-destructive hover:text-destructive-hover transition-colors"
                >
                  Cancelar proceso
                </button>
              )}
            </div>
          </div>
        ))}
      </div>

      {/* Consejo */}
      <div className="mt-6 bg-warning-background border border-warning-border rounded-xl p-4 flex items-start gap-3">
        <LuLightbulb className="h-5 w-5 text-warning-foreground flex-shrink-0 mt-0.5" />
        <p className="text-sm text-warning-foreground">
          <span className="font-semibold">Consejo:</span> Una vez finalizado, podrás editar los campos extraídos antes de confirmar el registro definitivo.
        </p>
      </div>
    </>
  );
}