"use client";

import type { Table, SyncData } from "../types";
import TableCard from "./TableCard";

type Props = {
  table: Table | null;
  open: boolean;
  onClose: () => void;
  onUpdate: () => void;
  syncData?: Record<string, SyncData>;
};

export default function TableDetailModal({
  table,
  open,
  onClose,
  onUpdate,
  syncData,
}: Props) {
  if (!open || !table) {
    return null;
  }

  const getCriterioAmigable = (criterio?: string) => {
    const safe = (criterio || "").toUpperCase();

    switch (safe) {
      case "ROW_COUNT":
        return "Conteo de Volúmen Global (Filas)";
      case "DAY":
        return "Validación Cronológica por Día";
      case "WEEK":
        return "Validación Cronológica por Semana";
      case "MONTH":
        return "Validación Cronológica por Mes";
      default:
        return criterio || "No especificado";
    }
  };

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/70 backdrop-blur-sm p-4">
      <div className="bg-[#111] border border-gray-800 rounded-2xl w-[95%] max-w-4xl max-h-[95vh] overflow-y-auto p-6 relative">
        {/* CLOSE BUTTON */}
        <button
          onClick={onClose}
          className="absolute top-4 right-4 text-gray-400 hover:text-white hover:bg-white/10 rounded-full w-8 h-8 flex items-center justify-center transition-all"
        >
          ✕
        </button>

        {/* HEADER */}
        <div className="mb-6">
          <div className="flex items-center gap-3">
            <h2 className="text-2xl font-bold text-white">
              Tabla: {table.table}
            </h2>
            {table.isCritical && (
              <span className="px-2 py-0.5 rounded text-xs font-bold bg-red-500/20 text-red-400 border border-red-500/30">
                TABLA CRÍTICA
              </span>
            )}
          </div>
        </div>

        {/* COMPONENT CARD */}
        <TableCard
          table={table}
          sync={syncData?.[table.table]}
          onUpdate={onUpdate}
        />

        {/* SECCIONES OPTIMIZADAS */}
        <div className="mt-6 grid grid-cols-1 lg:grid-cols-2 gap-6">
          {/* CRITERIOS DE AUDITORÍA */}
          <div className="bg-black/40 border border-gray-800 rounded-2xl p-5">
            <h3 className="text-white font-bold mb-4 text-sm tracking-wide uppercase text-gray-400">
              Estrategia de Validación
            </h3>

            <div className="space-y-4 text-sm">
              <div className="flex justify-between border-b border-gray-900 pb-2">
                <span className="text-gray-500">Criterio aplicado</span>
                <span className="text-white font-medium">
                  {getCriterioAmigable(table.compareBy)}
                </span>
              </div>

              <div className="flex justify-between border-b border-gray-900 pb-2">
                <span className="text-gray-500">Módulo/Tag</span>
                <span className="text-blue-400 font-semibold">
                  {table.tag || "GENERAL"}
                </span>
              </div>

              <div className="flex justify-between pb-2">
                <span className="text-gray-500">Estado de integridad</span>
                <span
                  className={`font-bold ${table.status === "OK" ? "text-green-400" : "text-red-400"}`}
                >
                  {table.status === "OK"
                    ? "✓ CONSISTENTE"
                    : "⚠ CON DIFERENCIAS"}
                </span>
              </div>
            </div>
          </div>

          {/* INTEGRIDAD DE REGISTROS Y SECUENCIAS */}
          <div className="bg-black/40 border border-gray-800 rounded-2xl p-5">
            <h3 className="text-white font-bold mb-4 text-sm tracking-wide uppercase text-gray-400">
              Puntos de Control e Índices
            </h3>

            <div className="space-y-4 text-sm">
              <div className="flex justify-between border-b border-gray-900 pb-2">
                <span className="text-gray-500">Estructura (Columnas)</span>
                <span className="text-white">
                  {table.metrics.columns.source} origen vs{" "}
                  {table.metrics.columns.target} destino
                </span>
              </div>

              <div className="flex justify-between border-b border-gray-900 pb-2">
                <span className="text-gray-500">
                  Último ID Sincronizado (Max)
                </span>
                <span className="text-white font-mono font-bold bg-white/5 px-2 py-0.5 rounded text-xs">
                  ID: {table.maxId}
                </span>
              </div>

              {/* Si existen montos financieros en las métricas (Requerimiento del Doc) */}
              <div className="flex justify-between pb-2">
                <span className="text-gray-500">
                  Cuadrante Financiero (Importes/Cantidades)
                </span>
                <span
                  className={`font-semibold ${table.metrics.amounts ? "text-white" : "text-gray-600 italic text-xs"}`}
                >
                  {table.metrics.amounts
                    ? `$${table.metrics.amounts.source} vs $${table.metrics.amounts.target}`
                    : "No aplica a esta tabla"}
                </span>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}
