"use client";

import { useConfigPanel } from "../hooks/useConfigPanel";
import type { ConfigTable } from "../types/config";
import ArchiveConfigModal from "./dashboard/ArchiveConfigModal";
import {
    formatStructureTooltip,
    isColumnStructurallyProtected,
} from "../utils/configHelpers";

type ConfigPanelProps = {
  configState: ReturnType<typeof useConfigPanel>;
};

export default function ConfigPanel({ configState }: ConfigPanelProps) {
  const {
    currentTables,
    columns,
    expandedTable,
    loadingTable,
    saving,
    message,
    dataTypes,
    searchTerm,
    currentPage,
    totalPages,
    hasPendingChanges,
    drafts,
    tagRuleModal,
    handleSearchChange,
    setCurrentPage,
    toggleTable,
    toggleColumn,
    changeType,
    toggleTableMigrationStatus,
    toggleTableCritical,
    requestTagChange,
    setExclusionComment,
    confirmTagRule,
    cancelTagRule,
    saveAllAndGeneratePdf,
  } = configState;

  return (
    <div className="bg-[#1c1c1e] border border-[#2c2c2e]/50 rounded-3xl p-6 mb-8 shadow-sm">
      <div className="flex flex-col md:flex-row md:items-center md:justify-between gap-4 mb-6">
        <div>
          <h2 className="text-white font-bold text-lg">
            Configuración de Tablas
          </h2>
          <p className="text-sm text-gray-500 mt-1">
            Configure el esquema de migración. Los cambios son locales hasta
            presionar "Guardar".
          </p>
        </div>

        <div className="w-full md:w-72">
          <input
            type="text"
            placeholder="Buscar tabla..."
            value={searchTerm}
            onChange={(e) => handleSearchChange(e.target.value)}
            className="w-full bg-black border border-gray-800 rounded-lg px-4 py-2 text-sm text-gray-200 placeholder-gray-600 focus:outline-none focus:border-gray-600 transition-colors"
          />
        </div>
      </div>

      {hasPendingChanges && (
        <div className="mb-4 px-4 py-2 bg-amber-500/10 border border-amber-500/30 rounded-lg text-xs text-amber-400 flex items-center gap-2">
          <span>⚠</span>
          <span>
            Tienes cambios pendientes en el borrador local. Presiona "Guardar y
            Generar PDF" para aplicarlos.
          </span>
        </div>
      )}

      <div className="space-y-3 min-h-[300px]">
        {currentTables.length > 0 ? (
          currentTables.map((table: ConfigTable) => {
            const tableName = table.table_name;
            const isRequiredByFk = table.required_by_fk ?? false;
            const isTableSelected = isRequiredByFk
              ? true
              : (table.is_selected ?? true);
            const isCritical = table.is_critical ?? false;
            const tagType = table.tag_type ?? "GENERAL";
            const tableColumns = columns[tableName] || [];
            const selectedCount = tableColumns.filter((c) => c.selected).length;
            const draft = drafts[tableName] || {};
            const exclusionComment = draft.exclusion_comment ?? "";
            const isDirty = tableName in drafts;

            return (
              <div
                key={tableName}
                className={`border rounded-xl overflow-hidden transition-all
                  ${!isTableSelected ? "border-gray-900 bg-[#070707]" : "bg-black border-gray-800"}
                  ${isRequiredByFk ? "border-amber-500/20 bg-[#0a0905]/40" : ""}
                  ${isDirty ? "ring-1 ring-blue-500/30" : ""}
                `}
              >
                <div
                  onClick={() => toggleTable(tableName)}
                  className="flex items-center justify-between cursor-pointer p-4 hover:bg-[#181818] transition-all"
                >
                  <div className="flex items-start gap-4">
                    <div
                      className="pt-1"
                      onClick={(e) => {
                        e.stopPropagation();
                        if (isRequiredByFk) {
                          alert(
                            `La tabla "${tableName}" tiene índices o relaciones activas (FK) en la base de datos y no puede ser deseleccionada.`,
                          );
                        }
                      }}
                    >
                      <input
                        type="checkbox"
                        checked={isTableSelected}
                        disabled={isRequiredByFk}
                        onChange={(e) => {
                          if (!isRequiredByFk) {
                            toggleTableMigrationStatus(
                              tableName,
                              e.target.checked,
                            );
                          }
                        }}
                        className={`h-4 w-4 rounded bg-black border-gray-700 transition-all ${
                          isRequiredByFk
                            ? "accent-emerald-600 opacity-60 cursor-not-allowed text-emerald-500"
                            : "accent-green-500 cursor-pointer"
                        }`}
                        title={
                          isRequiredByFk
                            ? "Requerida por llave foránea"
                            : isTableSelected
                              ? "Excluir tabla de la migración"
                              : "Incluir tabla en la migración"
                        }
                      />
                    </div>

                    {/* Info */}
                    <div className={`${!isTableSelected ? "opacity-50" : ""}`}>
                      <div className="flex items-center gap-2 flex-wrap">
                        <p
                          className={`font-semibold ${!isTableSelected ? "text-gray-500 line-through" : "text-white"}`}
                        >
                          {tableName}
                        </p>
                        {isRequiredByFk && (
                          <span className="text-[10px] bg-amber-500/10 text-amber-400 border border-amber-500/20 px-1.5 py-0.5 rounded font-mono uppercase tracking-wide">
                            Relacionada (FK)
                          </span>
                        )}
                        {isDirty && (
                          <span className="text-[10px] bg-blue-500/10 text-blue-400 border border-blue-500/20 px-1.5 py-0.5 rounded font-medium">
                            Modificada
                          </span>
                        )}
                      </div>
                      <p className="text-xs text-gray-500 mt-1">
                        {!isTableSelected
                          ? "Tabla excluida del proceso de migración"
                          : tableColumns.length > 0
                            ? `${tableColumns.length} columnas — ${selectedCount} seleccionadas`
                            : "Clic para cargar columnas"}
                      </p>
                    </div>
                  </div>

                  {/* Controles derecha */}
                  <div className="flex items-center gap-3 h-10">
                    <select
                      value={tagType}
                      disabled={!isTableSelected}
                      onClick={(e) => e.stopPropagation()}
                      onChange={(e) => {
                        e.stopPropagation();
                        requestTagChange(
                          tableName,
                          e.target.value as "GENERAL" | "HIBRIDA" | "HISTORICA",
                        );
                      }}
                      className="h-8 bg-[#111] border border-blue-500/20 rounded-md px-2 text-[10px] text-blue-400 uppercase flex items-center disabled:opacity-30 disabled:cursor-not-allowed"
                    >
                      <option value="GENERAL">GENERAL</option>
                      <option value="HIBRIDA">HÍBRIDA</option>
                      <option value="HISTORICA">HISTÓRICA</option>
                    </select>

                    <button
                      type="button"
                      disabled={!isTableSelected}
                      onClick={(e) => {
                        e.stopPropagation();
                        toggleTableCritical(tableName, isCritical);
                      }}
                      className={`h-8 flex items-center text-[10px] px-2.5 rounded-md border font-medium uppercase tracking-wider transition-colors disabled:opacity-30 disabled:cursor-not-allowed ${
                        isCritical
                          ? "bg-red-500/10 text-red-400 border-red-500/30 hover:bg-red-500/20"
                          : "bg-gray-800/30 text-gray-500 border-gray-700/50 hover:bg-gray-800 hover:text-gray-300"
                      }`}
                    >
                      {isCritical ? "Crítica" : "Estándar"}
                    </button>

                    <div className="text-gray-400 text-xl font-mono w-4 h-8 flex items-center justify-center select-none">
                      {expandedTable === tableName ? "−" : "+"}
                    </div>
                  </div>
                </div>

                {/* ── COMENTARIO DE EXCLUSIÓN ── */}
                {!isTableSelected && !isRequiredByFk && (
                  <div
                    className="border-t border-gray-900 px-4 py-3 bg-[#0a0505]"
                    onClick={(e) => e.stopPropagation()}
                  >
                    <label className="block text-[10px] text-red-400 font-bold uppercase tracking-wider mb-1">
                      Justificación técnica de exclusión (obligatorio)
                    </label>
                    <textarea
                      rows={2}
                      placeholder="Describe por qué esta tabla fue excluida de la migración..."
                      value={exclusionComment}
                      onChange={(e) =>
                        setExclusionComment(tableName, e.target.value)
                      }
                      className="w-full bg-black border border-red-900/50 rounded-lg px-3 py-2 text-xs text-gray-300 placeholder-gray-700 focus:outline-none focus:border-red-500/50 transition-colors resize-none"
                    />
                    {exclusionComment.trim().length > 0 &&
                      exclusionComment.trim().length < 10 && (
                        <p className="text-[10px] text-red-500 mt-1">
                          Mínimo 10 caracteres requeridos.
                        </p>
                      )}
                  </div>
                )}

                {/* ── COLUMNAS ── */}
                {expandedTable === tableName && (
                  <div
                    className={`border-t border-gray-800 p-4 ${!isTableSelected ? "opacity-30 pointer-events-none bg-[#050505]" : ""}`}
                    onClick={(e) => e.stopPropagation()}
                  >
                    {loadingTable === tableName ? (
                      <p className="text-xs text-gray-400">
                        Cargando columnas...
                      </p>
                    ) : tableColumns.length === 0 ? (
                      <p className="text-xs text-gray-500">
                        No se encontraron columnas.
                      </p>
                    ) : (
                      <div className="space-y-2">
                        {tableColumns.map((col, index) => {
                          const isProtected = isColumnStructurallyProtected(col);
                          const isCheckboxDisabled =
                            isProtected && col.selected;

                          return (
                          <div
                            key={col.column}
                            className="bg-[#111] border border-gray-800 rounded-lg p-3"
                          >
                            <div className="flex items-center justify-between gap-4">
                              <div className="flex items-center gap-3">
                                <input
                                  type="checkbox"
                                  checked={col.selected}
                                  disabled={isCheckboxDisabled}
                                  title={
                                    isProtected
                                      ? formatStructureTooltip(
                                          col.structure_reasons,
                                        )
                                      : undefined
                                  }
                                  onChange={() =>
                                    toggleColumn(tableName, index)
                                  }
                                  className={`h-4 w-4 rounded ${
                                    isCheckboxDisabled
                                      ? "accent-emerald-600 opacity-60 cursor-not-allowed"
                                      : "accent-green-500 cursor-pointer"
                                  }`}
                                />
                                <p
                                  className={`text-sm ${col.selected ? "text-white" : "text-gray-500 line-through"}`}
                                >
                                  {col.column}
                                  {isProtected && (
                                    <span className="ml-2 text-[10px] text-amber-400">
                                      (estructural)
                                    </span>
                                  )}
                                </p>
                              </div>
                              <select
                                value={col.type}
                                onChange={(e) =>
                                  changeType(tableName, index, e.target.value)
                                }
                                className="bg-black border border-gray-700 rounded p-2 text-xs text-gray-300 focus:outline-none focus:border-gray-500"
                              >
                                <option value="">Seleccionar tipo</option>
                                {dataTypes.map((type) => (
                                  <option key={type.code} value={type.code}>
                                    {type.label}
                                  </option>
                                ))}
                              </select>
                            </div>
                          </div>
                          );
                        })}
                      </div>
                    )}
                  </div>
                )}
              </div>
            );
          })
        ) : (
          <div className="text-center py-12 text-gray-600 text-sm border border-dashed border-gray-800 rounded-xl">
            No se encontraron tablas que coincidan con la búsqueda.
          </div>
        )}
      </div>

      {totalPages > 1 && (
        <div className="flex items-center justify-between border-t border-gray-900 mt-6 pt-4 text-xs text-gray-400">
          <button
            disabled={currentPage === 1}
            onClick={() => setCurrentPage((p) => p - 1)}
            className="px-4 py-2 bg-black border border-gray-800 rounded-lg disabled:opacity-30 disabled:cursor-not-allowed hover:bg-[#181818] transition-colors"
          >
            Anterior
          </button>
          <span className="font-medium">
            Página {currentPage} de {totalPages}
          </span>
          <button
            disabled={currentPage === totalPages}
            onClick={() => setCurrentPage((p) => p + 1)}
            className="px-4 py-2 bg-black border border-gray-800 rounded-lg disabled:opacity-30 disabled:cursor-not-allowed hover:bg-[#181818] transition-colors"
          >
            Siguiente
          </button>
        </div>
      )}

      <div className="mt-6 pt-6 border-t border-gray-800">
        <button
          onClick={saveAllAndGeneratePdf}
          disabled={saving}
          className={`w-full py-3 rounded-xl text-sm font-bold tracking-wide transition-all ${
            saving
              ? "bg-gray-800 text-gray-500 cursor-not-allowed"
              : "bg-emerald-600 hover:bg-emerald-500 text-white shadow-lg shadow-emerald-900/30"
          }`}
        >
          {saving
            ? "⏳ Guardando y generando PDF..."
            : "📄 Guardar Configuración Completa y Generar PDF"}
        </button>
      </div>

      {message && (
        <div
          className={`mt-4 p-3 border rounded-lg text-xs ${message.startsWith("✓") ? "bg-emerald-900/20 border-emerald-800 text-emerald-400" : "bg-red-900/20 border-red-800 text-red-400"}`}
        >
          {message}
        </div>
      )}

      {tagRuleModal.open &&
        (tagRuleModal.tagType === "HIBRIDA" ||
          tagRuleModal.tagType === "HISTORICA") && (
          <ArchiveConfigModal
            isOpen={tagRuleModal.open}
            tableName={tagRuleModal.tableName}
            tagType={tagRuleModal.tagType}
            onClose={cancelTagRule}
            onUpdateTag={async () => ({ id: 0 })}
            onRefresh={() => {}}
            onDraftConfirm={(data) => confirmTagRule(data)}
          />
        )}
    </div>
  );
}
