"use client";

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

type Props = {
  table: Table;
  sync?: SyncData;
  onUpdate: () => void;
};

export default function TableCard({ table, sync, onUpdate }: Props) {
  const { updateTag } = useTable();

  const handleTagChange = (newTag: string) => {
    updateTag(table.table, newTag, onUpdate);
  };

  const progress = Math.max(0, Math.min(100, table.match || 0));

  const syncNew = sync?.new ?? 0;
  const syncUpdated = sync?.updated ?? 0;
  const syncDeleted = sync?.deleted ?? 0;

  const hasActivity = syncNew > 0 || syncUpdated > 0 || syncDeleted > 0;

  const rowsSource = table.metrics?.rows?.source ?? 0;
  const rowsTarget = table.metrics?.rows?.target ?? 0;
  const colsSource = table.metrics?.columns?.source ?? 0;
  const colsTarget = table.metrics?.columns?.target ?? 0;

  const formatCompareBy = (criterion: string) => {
    switch (criterion?.toUpperCase()) {
      case "ROW_COUNT":
        return "Conteo de Volumen Global (Filas)";
      case "DAY":
        return "Consistencia Cronológica (Últimas 24 Horas)";
      case "WEEK":
        return "Consistencia Cronológica (Última Semana)";
      case "MONTH":
        return "Consistencia Cronológica (Último Mes)";
      default:
        return criterion || "No especificado";
    }
  };

  return (
    <div className="bg-[#111] border border-gray-800 rounded-2xl p-5 text-xs hover:border-blue-500/40 transition-all duration-300">
      {/* HEADER */}
      <div className="flex justify-between items-start mb-4">
        <div>
          <h3 className="font-bold text-lg text-white">{table.table}</h3>
          <div className="text-[11px] text-gray-500 mt-1 flex items-center gap-2">
            <span>Tipo:</span>
            <span className="px-2 py-0.5 rounded-md bg-blue-500/10 text-blue-400 font-semibold text-[11px]">
              {table.tag || "GENERAL"}
            </span>
          </div>
        </div>

        <span
          className={`
px-3 py-1 rounded-full text-[10px] font-bold
${
  table.status === "OK"
    ? "bg-green-500/20 text-green-400"
    : "bg-red-500/20 text-red-400"
}
`}
        >
          {table.status}
        </span>
      </div>

      {/* META */}
      <div className="grid grid-cols-1 md:grid-cols-2 gap-3 mb-3">
        <div className="bg-black/30 rounded-xl p-3 border border-gray-800">
          <p className="text-gray-500 text-[11px] mb-1">
            Estrategia de Comparación
          </p>
          <p className="text-white font-semibold text-[13px]">
            {formatCompareBy(table.compareBy)}
          </p>
        </div>

        <div className="bg-black/30 rounded-xl p-3 border border-gray-800">
          <p className="text-gray-500 text-[11px] mb-1">Máximo ID Histórico</p>
          <p className="text-white font-extrabold text-xl font-mono tracking-tight">
            {table.maxId || 0}
          </p>
        </div>
      </div>

      {/* REGISTROS */}
      <div className="bg-black/40 rounded-xl p-4 border border-gray-800 mb-4">
        <div className="flex items-center justify-between mb-3">
          <span className="text-[12px] uppercase tracking-wider text-gray-500 font-semibold">
            Registros
          </span>
        </div>

        <div className="grid grid-cols-2 gap-4">
          <div className="text-center">
            <p className="text-[12px] uppercase tracking-wider text-gray-500">
              Origen
            </p>
            <p className="text-white text-2xl font-bold mt-1">
              {rowsSource.toLocaleString()}
            </p>
          </div>

          <div className="text-center">
            <p className="text-[12px] uppercase tracking-wider text-gray-500">
              Destino
            </p>
            <p className="text-white text-2xl font-bold mt-1">
              {rowsTarget.toLocaleString()}
            </p>
          </div>
        </div>
      </div>

      {/* COLUMNAS */}
      <div className="bg-black/40 rounded-xl p-4 border border-gray-800 mb-4">
        <div className="flex items-center justify-between mb-3">
          <span className="text-[12px] uppercase tracking-wider text-gray-500 font-semibold">
            Columnas
          </span>
        </div>

        <div className="grid grid-cols-2 gap-4">
          <div className="text-center">
            <p className="text-[10px] uppercase tracking-wider text-gray-500">
              Origen
            </p>
            <p className="text-white text-2xl font-bold mt-1">{colsSource}</p>
          </div>

          <div className="text-center">
            <p className="text-[10px] uppercase tracking-wider text-gray-500">
              Destino
            </p>
            <p className="text-white text-2xl font-bold mt-1">{colsTarget}</p>
          </div>
        </div>
      </div>

      {/* SINCRONIZACIÓN */}
      <div className="border-t border-gray-800 pt-4 mb-4">
        <div className="grid grid-cols-3 gap-2 mb-3">
          <div className="bg-green-500/10 border border-green-500/20 rounded-lg p-2 text-center">
            <p className="text-green-400 text-[10px]">Nuevos</p>
            <p className="text-white font-bold text-sm">{syncNew}</p>
          </div>

          <div className="bg-blue-500/10 border border-blue-500/20 rounded-lg p-2 text-center">
            <p className="text-blue-400 text-[10px]">Actualizados</p>
            <p className="text-white font-bold text-sm">{syncUpdated}</p>
          </div>

          <div className="bg-red-500/10 border border-red-500/20 rounded-lg p-2 text-center">
            <p className="text-red-400 text-[10px]">Eliminados</p>
            <p className="text-white font-bold text-sm">{syncDeleted}</p>
          </div>
        </div>

        <div
          className={`text-[11px] font-bold ${hasActivity ? "text-yellow-400" : "text-green-400"}`}
        >
          {hasActivity
            ? "Actividad detectada en sincronización"
            : "Sincronización de transacciones estable"}
        </div>
      </div>

      {/* PROGRESO */}
      <div>
        <div className="flex justify-between text-[11px] mb-2">
          <span className="text-blue-400 font-semibold">
            Porcentaje de Coincidencia
          </span>
          <span className="text-white font-bold">{progress}%</span>
        </div>

        <div className="bg-gray-800 h-3 rounded-full overflow-hidden">
          <div
            className={`
h-full transition-all duration-500
${table.status === "OK" ? "bg-green-500" : "bg-red-500"}
`}
            style={{ width: `${progress}%` }}
          />
        </div>
      </div>
    </div>
  );
}
