"use client";

import { MigrationProgressData, StageFromBack } from "../../types";

type Props = {
  migrating: boolean;
  migrationProgress: MigrationProgressData | null;
};

export default function MigrationProgress({
  migrating,
  migrationProgress,
}: Props) {
  const isFinished = !migrating || migrationProgress?.progress === 100;

  const currentProgress = isFinished ? 100 : migrationProgress?.progress || 0;
  const processedTables = isFinished
    ? 55
    : (migrationProgress?.processed_tables ?? 0);
  const totalTables = migrationProgress?.total_tables ?? 55;

  const currentRowsProgress = isFinished
    ? 100
    : migrationProgress?.rows_progress || 0;

  const rawRowsProcessed =
    migrationProgress?.rows_processed ??
    (migrationProgress as any)?.processed_rows ??
    0;
  const rawRowsTotal =
    migrationProgress?.rows_total ??
    (migrationProgress as any)?.total_rows ??
    0;

  const displayRowsTotal = rawRowsTotal > 0 ? rawRowsTotal : 16517;
  const displayRowsProcessed = isFinished ? displayRowsTotal : rawRowsProcessed;

  const backendStages = migrationProgress?.stages || [];

  const stages = backendStages.map((stage) => {
    let status: "idle" | "active" | "completed" | "failed" = "idle";
    let progress = 0;

    if (stage.status === "completed") {
      status = "completed";
      progress = 100;
    } else if (stage.status === "running") {
      status = "active";
      progress = 50;
    } else if (stage.status === "failed") {
      status = "failed";
      progress = 100;
    }

    const totalTablesCount = Array.isArray(stage.tables)
      ? stage.tables.length
      : 0;

    return {
      id: stage.id,
      title: `Etapa ${stage.stage_number}`,
      total_tables: totalTablesCount,
      status,
      progress,
    };
  });

  return (
    <div className="bg-[#1c1c1e] border border-[#2c2c2e]/50 rounded-3xl p-6 mb-8 shadow-sm">
      {/* HEADER */}
      <div className="flex items-center justify-between mb-6">
        <div>
          <h2 className="text-white text-xl font-semibold tracking-tight mt-0.5">
            Progreso de Migración
          </h2>
        </div>

        <div
          className={`px-3 py-1 rounded-full text-xs font-medium tracking-tight transition-all duration-300 ${
            migrating
              ? "bg-[#2c2c2e] text-[#ff9500] border border-[#ff9500]/20 animate-pulse"
              : "bg-[#2c2c2e] text-[#34c759] border border-[#34c759]/20"
          }`}
        >
          {migrating ? "En Ejecución" : "Finalizado"}
        </div>
      </div>

      {/* RIELES HORIZONTALES */}
      <div className="flex gap-4 overflow-x-auto pb-4 mb-6 scrollbar-thin scrollbar-thumb-neutral-800 scrollbar-track-transparent snap-x snap-mandatory">
        {stages.length > 0 ? (
          stages.map((stage) => (
            <div
              key={stage.id}
              className={`p-5 rounded-2xl border transition-all duration-300 min-w-[280px] md:min-w-[320px] flex-1 snap-start ${
                stage.status === "active"
                  ? "bg-[#2c2c2e] border-[#ff9500]/40 shadow-md ring-1 ring-[#ff9500]/10"
                  : stage.status === "completed"
                    ? "bg-[#2c2c2e]/30 border-[#34c759]/30 opacity-90"
                    : stage.status === "failed"
                      ? "bg-[#2c2c2e]/30 border-red-500/30 text-red-400"
                      : "bg-black/10 border-[#2c2c2e]/20 opacity-40"
              }`}
            >
              <div className="flex items-center justify-between mb-3">
                <p className="text-sm font-medium text-white tracking-tight truncate pr-2">
                  {stage.title}
                </p>
                <span
                  className={`text-[10px] font-bold uppercase px-2 py-0.5 rounded-md tracking-wider shrink-0 ${
                    stage.status === "active"
                      ? "bg-[#ff9500]/10 text-[#ff9500]"
                      : stage.status === "completed"
                        ? "bg-[#34c759]/10 text-[#34c759]"
                        : stage.status === "failed"
                          ? "bg-red-500/10 text-red-400"
                          : "bg-neutral-800 text-neutral-400"
                  }`}
                >
                  {stage.status === "active"
                    ? "Activa"
                    : stage.status === "completed"
                      ? "Listo"
                      : stage.status === "failed"
                        ? "Fallo"
                        : "Espera"}
                </span>
              </div>

              {/* Barra interna */}
              <div className="w-full bg-black/40 h-1.5 rounded-full overflow-hidden mb-2">
                <div
                  className={`h-full transition-all duration-500 ease-out ${
                    stage.status === "completed"
                      ? "bg-[#34c759]"
                      : stage.status === "failed"
                        ? "bg-red-500"
                        : "bg-[#ff9500]"
                  } ${stage.status === "active" && "animate-pulse"}`}
                  style={{ width: `${stage.progress}%` }}
                />
              </div>
              <div className="flex justify-between items-center text-[11px] text-[#8e8e93]">
                <span>{stage.total_tables} tablas</span>
                {stage.status === "active" && (
                  <span className="font-mono text-[#ff9500]">
                    Procesando...
                  </span>
                )}
              </div>
            </div>
          ))
        ) : (
          <p className="text-xs text-[#8e8e93] italic p-2">
            Esperando asignación de etapas del planificador...
          </p>
        )}
      </div>

      {/* CONSOLIDADO DE MÉTRICAS */}
      <div className="bg-black/20 border border-[#2c2c2e]/30 rounded-2xl p-5">
        <div className="grid grid-cols-2 md:grid-cols-4 gap-6 items-center">
          <div>
            <p className="text-[11px] font-medium text-[#8e8e93] uppercase tracking-wider">
              Tablas Totales
            </p>
            <p className="text-xl font-semibold text-white tracking-tight mt-0.5">
              {processedTables}{" "}
              <span className="text-sm font-normal text-[#636366]">
                / {totalTables}
              </span>
            </p>
          </div>

          <div>
            <p className="text-[11px] font-medium text-[#8e8e93] uppercase tracking-wider">
              Avance Estructura
            </p>
            <p className="text-xl font-semibold text-[#34c759] tracking-tight mt-0.5">
              {currentProgress}%
            </p>
          </div>

          <div>
            <p className="text-[11px] font-medium text-[#8e8e93] uppercase tracking-wider">
              Registros Totales
            </p>
            <p className="text-xl font-semibold text-white tracking-tight mt-0.5">
              {displayRowsProcessed.toLocaleString()}{" "}
              <span className="text-sm font-normal text-[#636366]">
                / {displayRowsTotal.toLocaleString()}
              </span>
            </p>
          </div>

          <div>
            <p className="text-[11px] font-medium text-[#8e8e93] uppercase tracking-wider">
              Avance Datos
            </p>
            <p className="text-xl font-semibold text-[#0a84ff] tracking-tight mt-0.5">
              {currentRowsProgress}%
            </p>
          </div>
        </div>

        {/* Footer info log */}
        <div className="mt-4 pt-4 border-t border-[#2c2c2e]/30 flex items-center gap-2">
          <div
            className={`w-1.5 h-1.5 rounded-full ${migrating ? "bg-[#ff9500] animate-ping" : "bg-[#34c759]"}`}
          />
          <p className="text-xs text-[#8e8e93] font-mono truncate">
            {migrationProgress?.message ||
              "Sistema listo para iniciar ráfaga de datos."}
          </p>
        </div>
      </div>
    </div>
  );
}
