"use client";

import { useState, useEffect } from "react";
import { API_BASE_URL } from "../../lib/api";

interface ArchiveConfigModalProps {
  isOpen: boolean;
  onClose: () => void;
  tableName: string;
  tagType: "HISTORICA" | "HIBRIDA";
  onUpdateTag: (data: any) => Promise<any>;
  onRefresh: () => void;
  onDraftConfirm?: (data: {
    rule: string;
    tagType: "HISTORICA" | "HIBRIDA";
    months: number;
    description: string;
  }) => void;
}

export default function ArchiveConfigModal({
  isOpen,
  onClose,
  tableName,
  tagType,
  onUpdateTag,
  onRefresh,
  onDraftConfirm,
}: ArchiveConfigModalProps) {
  const [availableDateColumns, setAvailableDateColumns] = useState<string[]>([]);
  const [loadingMetadata, setLoadingMetadata] = useState(true);
  const [dateCriteria, setDateCriteria] = useState("");
  const [months, setMonths] = useState("6");
  const [description, setDescription] = useState("");
  const [loading, setLoading] = useState(false);

  const isDraftMode = typeof onDraftConfirm === "function";

  useEffect(() => {
    if (!isOpen) return;

    const fetchTableMetadata = async () => {
      setLoadingMetadata(true);
      try {
        const response = await fetch(
          `${API_BASE_URL}/api-v2/archive-rules/tables/${tableName}/metadata`,
        );
        if (response.ok) {
          const data = await response.json();
          setAvailableDateColumns(data.date_columns || []);
          if (data.date_columns && data.date_columns.length > 0) {
            setDateCriteria(data.date_columns[0]);
          } else {
            setDateCriteria("FULL_TABLE");
          }
        } else {
          setDateCriteria("FULL_TABLE");
        }
      } catch {
        setDateCriteria("FULL_TABLE");
        setAvailableDateColumns([]);
      } finally {
        setLoadingMetadata(false);
      }
    };

    fetchTableMetadata();

    // Sincronizar descripción inicial por defecto
    setDescription(
      tagType === "HISTORICA"
        ? `Traslado integral de la tabla ${tableName} al repositorio histórico.`
        : `Segmentación por antigüedad para la tabla ${tableName}.`,
    );
  }, [isOpen, tagType, tableName]);

  const formatColumnLabel = (colName: string) => {
    const labels: Record<string, string> = {
      created_at: "Creados desde",
      updated_at: "Actualizados desde",
      last_used_at: "Último uso",
      expires_at: "Fecha de vencimiento",
    };
    return labels[colName] ?? `${colName} (Filtrado por fecha)`;
  };

  const getDynamicSummarySentence = () => {
    if (!months || Number(months) <= 0) return "Introduce un número de meses válido.";
    const monthText = months === "1" ? "1 mes" : `${months} meses`;
    const labels: Record<string, string> = {
      created_at: `Se archivarán los datos creados con una antigüedad de ${monthText}.`,
      updated_at: `Se archivarán los datos actualizados con una antigüedad de ${monthText}.`,
      last_used_at: `Se archivarán los registros sin uso durante ${monthText}.`,
      expires_at: `Se archivarán los registros vencidos desde hace ${monthText}.`,
    };
    return labels[dateCriteria] ?? `Se archivarán los registros con antigüedad de ${monthText}.`;
  };

  const handleSave = async () => {
    // Generación estandarizada de la regla SQL
    let generatedSql = "1=1";
    let retentionPeriodDays = 0;

    if (tagType === "HIBRIDA" && dateCriteria !== "FULL_TABLE") {
      generatedSql = `${dateCriteria} < DATE_SUB(NOW(), INTERVAL ${months} MONTH)`;
      retentionPeriodDays = Number(months) * 30;
    }

    if (isDraftMode) {
      const finalDescription = tagType === "HIBRIDA" ? `${description} (${getDynamicSummarySentence()})` : description;
      
      onDraftConfirm!({
        rule: generatedSql,
        tagType: tagType,
        months: tagType === "HIBRIDA" ? Number(months) : 0,
        description: finalDescription
      });
      onClose();
      return;
    }

    setLoading(true);
    try {
      const tagResult = await onUpdateTag({
        table_name: tableName,
        tag_type: tagType,
        description,
      });

      if (!tagResult || !tagResult.id) {
        throw new Error("No se pudo registrar la clasificación de la tabla.");
      }

      const payload = {
        table_name: tableName,
        rule_type: tagType === "HIBRIDA" ? "HYBRID" : "HISTORIC",
        filter_condition: generatedSql,
        retention_period_days: retentionPeriodDays,
        destination_target: "classification_tables_logs",
        description,
        is_active: true,
      };

      const response = await fetch(
        `${API_BASE_URL}/api-v2/archive-rules/${tagResult.id}`,
        {
          method: "POST",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify(payload),
        },
      );

      if (!response.ok) throw new Error("No se pudo guardar la regla de archivado.");

      onRefresh();
      onClose();
    } catch (error) {
      console.error("Error al guardar configuración de archivado:", error);
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="fixed inset-0 bg-black/70 backdrop-blur-sm flex items-center justify-center z-50 p-4">
      <div className="bg-[#0f1117] p-8 rounded-xl border border-gray-800 w-[500px] shadow-2xl">
        <div className="mb-6">
          <div className="flex items-center gap-2">
            <h2 className="text-white text-lg font-bold">
              {isDraftMode ? "Definir regla (borrador)" : "Configurar Regla de Archivado"}
            </h2>
            <span className={`text-[10px] px-2 py-0.5 rounded-full font-bold ${
              tagType === "HIBRIDA"
                ? "bg-purple-500/20 text-purple-400"
                : "bg-blue-500/20 text-blue-400"
            }`}>
              {tagType}
            </span>
          </div>
          <p className="text-gray-400 text-sm mt-1">
            Tabla: <span className="text-blue-400 font-semibold">{tableName}</span>
          </p>
          {isDraftMode && (
            <p className="text-amber-400/70 text-xs mt-1">
              ℹ️ La regla se aplicará localmente y se procesará al consolidar la configuración.
            </p>
          )}
        </div>

        {loadingMetadata ? (
          <div className="py-12 text-center text-gray-500 text-sm">
            Escaneando columnas de la tabla...
          </div>
        ) : (
          <>
            {tagType === "HISTORICA" && (
              <div className="bg-blue-500/10 border border-blue-500/30 p-4 rounded-lg mb-5 text-sm text-blue-400 leading-relaxed">
                ℹ️ <b>Traspaso Integral:</b> Se moverá el 100% de los registros al repositorio histórico.
              </div>
            )}

            {tagType === "HIBRIDA" && (
              <>
                {availableDateColumns.length === 0 ? (
                  <div className="bg-red-500/10 border border-red-500/30 p-4 rounded-lg mb-5 text-sm text-red-400 leading-relaxed">
                    ⚠️ <strong>Sin campos de fecha:</strong> Las reglas <strong>Híbridas</strong> requieren columnas de fecha.
                  </div>
                ) : (
                  <div className="grid grid-cols-2 gap-4 mb-3">
                    <div>
                      <label className="text-gray-400 text-xs mb-1 block uppercase font-semibold">
                        Criterio Cronológico
                      </label>
                      <select
                        className="w-full bg-[#1a1c24] text-white p-2 h-[40px] rounded border border-gray-700 focus:border-blue-500 outline-none cursor-pointer text-sm"
                        value={dateCriteria}
                        onChange={(e) => setDateCriteria(e.target.value)}
                      >
                        {availableDateColumns.map((col) => (
                          <option key={col} value={col}>
                            📅 {formatColumnLabel(col)}
                          </option>
                        ))}
                      </select>
                    </div>
                    <div>
                      <label className="text-gray-400 text-xs mb-1 block uppercase font-semibold">
                        Tiempo de Antigüedad
                      </label>
                      <div className="relative flex items-center">
                        <input
                          type="number"
                          min="1"
                          className="w-full bg-[#1a1c24] text-white p-2 h-[40px] rounded border border-gray-700 focus:border-blue-500 outline-none transition"
                          value={months}
                          onChange={(e) => setMonths(e.target.value)}
                        />
                        <span className="absolute right-3 text-xs text-gray-500">Meses</span>
                      </div>
                    </div>
                  </div>
                )}
              </>
            )}

            {tagType === "HIBRIDA" && availableDateColumns.length > 0 && (
              <p className="text-gray-300 text-sm font-medium my-4">
                "{getDynamicSummarySentence()}"
              </p>
            )}

            <div className="mb-6">
              <label className="text-gray-400 text-xs mb-1 block uppercase font-semibold">
                Notas / Motivo de archivado
              </label>
              <textarea
                className="w-full bg-[#1a1c24] text-white p-2 rounded border border-gray-700 h-24 focus:border-blue-500 outline-none transition text-sm resize-none"
                placeholder="Motivo por el cual se configura esta tabla..."
                value={description}
                onChange={(e) => setDescription(e.target.value)}
              />
            </div>

            <div className="flex justify-end gap-3 border-t border-gray-800/60 pt-4">
              <button type="button" onClick={onClose} disabled={loading}
                className="px-4 py-2 text-gray-400 hover:text-white transition text-sm disabled:opacity-30">
                Cancelar
              </button>
              <button type="button" onClick={handleSave}
                disabled={loading || (tagType === "HIBRIDA" && availableDateColumns.length === 0)}
                className="px-5 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-500 transition font-medium text-sm disabled:opacity-40">
                {loading ? "Procesando..." : isDraftMode ? "Aplicar al Borrador" : "Confirmar Criterio"}
              </button>
            </div>
          </>
        )}
      </div>
    </div>
  );
}
