"use client";

import { LuFile, LuX, LuPlus, LuArrowLeft, LuSparkles, LuShieldCheck, LuZap, LuImage } from "react-icons/lu";
import { ManagedFile } from "../page";
import { useRef } from "react";

interface Props {
  files: ManagedFile[];
  onRemoveFile: (id: string) => void;
  onProcessFiles: () => void;
  isProcessing: boolean;
  onAddMore?: (files: FileList | null) => void;
  onBack?: () => 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 getFileType = (mimeType: string): string => {
  if (mimeType.startsWith('image/')) {
    return 'Imagen ' + mimeType.split('/')[1].toUpperCase();
  }
  if (mimeType === 'application/pdf') return 'Documento PDF';
  return 'Archivo';
};

export default function Step2ReviewSelection({
  files,
  onRemoveFile,
  onProcessFiles,
  isProcessing,
  onAddMore,
  onBack
}: Props) {
  const fileInputRef = useRef<HTMLInputElement>(null);

  return (
    <>
      {/* Header */}
      <div className="text-center mb-8">
        <h2 className="text-2xl font-bold text-text">Confirmar Archivos</h2>
        <p className="text-text-muted text-sm mt-2 max-w-lg mx-auto">
          Revisa los archivos seleccionados antes de continuar con el proceso de extracción de datos por IA.
        </p>
      </div>

      {/* Card de archivos */}
      <div className="bg-background-alt/50 rounded-2xl border border-border-subtle p-6 mb-6">
        <div className="flex items-center justify-between mb-4">
          <div className="flex items-center gap-2">
            <h3 className="font-bold text-text">Archivos seleccionados</h3>
            <span className="bg-primary text-primary-foreground text-xs font-bold px-2.5 py-1 rounded-full shadow-sm">
              {files.length}
            </span>
          </div>
          {onAddMore && (
            <button
              onClick={() => fileInputRef.current?.click()}
              className="text-sm text-primary hover:text-primary-hover font-medium flex items-center gap-1.5 transition-colors focus-ring px-3 py-1.5 rounded-lg hover:bg-primary-faint"
            >
              <LuPlus className="h-4 w-4" />
              Agregar más
            </button>
          )}
        </div>
        <p className="text-sm text-text-muted mb-4">
          Verifica que el archivo sea legible para una extracción óptima.
        </p>

        {/* Lista de archivos */}
        <div className="space-y-3 max-h-72 overflow-y-auto pr-2 custom-scrollbar">
          {files.map(({ id, file }) => (
            <div
              key={id}
              className="bg-background border border-border-subtle rounded-xl p-4 flex items-center justify-between transition-all hover:border-primary/50 hover:shadow-md group"
            >
              <div className="flex items-center gap-4 min-w-0">
                {/* Icono de tipo de archivo */}
                <div className="w-14 h-14 rounded-xl bg-gradient-to-br from-primary-faint to-background-alt flex items-center justify-center flex-shrink-0 shadow-sm">
                  <LuImage className="h-7 w-7 text-primary" />
                </div>
                <div className="min-w-0 flex-1">
                  <p className="font-semibold text-text truncate text-sm">
                    {file.name}
                  </p>
                  <div className="flex items-center gap-2 mt-1 flex-wrap">
                    <span className="text-xs text-text-subtle">
                      {formatFileSize(file.size)}
                    </span>
                    <span className="text-border">•</span>
                    <span className="text-xs text-text-subtle">
                      {getFileType(file.type)}
                    </span>
                    <span className="text-xs font-bold text-success-foreground bg-success-background px-2 py-0.5 rounded-full uppercase border border-success-border">
                      Listo
                    </span>
                  </div>
                </div>
              </div>
              <button
                onClick={() => onRemoveFile(id)}
                className="p-2.5 text-text-subtle hover:text-destructive hover:bg-destructive-background rounded-xl transition-all focus-ring opacity-0 group-hover:opacity-100"
                aria-label={`Eliminar ${file.name}`}
              >
                <LuX className="h-5 w-5" />
              </button>
            </div>
          ))}
        </div>
      </div>

      {/* Footer Actions */}
      <div className="flex items-center justify-between pt-6 border-t border-border-subtle">
        <button
          onClick={onBack}
          className="text-text-muted hover:text-text font-medium flex items-center gap-2 transition-colors focus-ring px-4 py-2 rounded-lg hover:bg-background-alt"
        >
          <LuArrowLeft className="h-4 w-4" />
          Atrás
        </button>
        <button
          onClick={onProcessFiles}
          disabled={!files.length || isProcessing}
          className="flex items-center justify-center gap-2 px-6 py-3 bg-gradient-to-r from-primary to-primary-hover text-primary-foreground font-semibold rounded-xl hover:shadow-lg hover:scale-105 disabled:bg-background-alt disabled:text-text-subtle disabled:cursor-not-allowed disabled:hover:scale-100 disabled:hover:shadow-none transition-all duration-200"
        >
          <LuSparkles className="h-5 w-5" />
          {isProcessing
            ? "Procesando..."
            : `Procesar ${files.length} archivo(s)`}
        </button>
      </div>

      {/* Info badges */}
      <div className="flex items-center justify-center gap-6 mt-6 text-xs text-text-muted">
        <div className="flex items-center gap-1.5 bg-background-alt/50 px-3 py-1.5 rounded-full">
          <LuShieldCheck className="h-4 w-4 text-success" />
          <span className="font-medium">Protección de datos</span>
        </div>
        <div className="flex items-center gap-1.5 bg-background-alt/50 px-3 py-1.5 rounded-full">
          <LuZap className="h-4 w-4 text-primary" />
          <span className="font-medium">IA ultra-rápida</span>
        </div>
      </div>

      {/* Input oculto para agregar más archivos */}
      <input
        type="file"
        accept="image/*,.pdf"
        ref={fileInputRef}
        onChange={(e) => onAddMore?.(e.target.files)}
        className="hidden"
        multiple
      />
    </>
  );
}