import React, { useEffect, useState } from "react";

const BASE_URL = import.meta.env.VITE_API_URL || "http://localhost:8008";

const DbTable = ({ title, data, columns }) => {
  if (!data || data.length === 0) {
    return (
      <section className="debug-table">
        <h3>{title}</h3>
        <p className="empty">Aucune donnée</p>
      </section>
    );
  }

  return (
    <section className="debug-table">
      <h3>{title} ({data.length})</h3>
      <div className="table-wrapper">
        <table>
          <thead>
            <tr>
              {columns.map((col) => (
                <th key={col}>{col}</th>
              ))}
            </tr>
          </thead>
          <tbody>
            {data.map((row, idx) => (
              <tr key={row.id || idx}>
                {columns.map((col) => (
                  <td key={col} title={String(row[col] ?? "")}>
                    {formatCell(row[col])}
                  </td>
                ))}
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </section>
  );
};

// Convertit une date UTC (sans timezone) en objet Date local
const parseUTCDate = (dateStr) => {
  if (!dateStr) return null;
  const normalized = dateStr.endsWith("Z") || dateStr.includes("+") ? dateStr : dateStr + "Z";
  return new Date(normalized);
};

// Détecte si une chaîne ressemble à une date ISO
const isISODateString = (str) => {
  if (typeof str !== "string") return false;
  return /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}/.test(str);
};

const formatCell = (value) => {
  if (value === null || value === undefined) return "-";
  if (typeof value === "boolean") return value ? "Oui" : "Non";
  // Formater les dates ISO en heure locale
  if (isISODateString(value)) {
    const date = parseUTCDate(value);
    return date.toLocaleString("fr-FR", {
      day: "2-digit",
      month: "2-digit",
      year: "numeric",
      hour: "2-digit",
      minute: "2-digit",
    });
  }
  if (typeof value === "string" && value.length > 50) {
    return value.substring(0, 50) + "...";
  }
  return String(value);
};

const LogViewer = ({ logs }) => {
  if (!logs || logs.length === 0) {
    return (
      <section className="debug-logs">
        <h3>Logs Scraping</h3>
        <p className="empty">Aucun log disponible</p>
      </section>
    );
  }

  return (
    <section className="debug-logs">
      <h3>Logs Scraping ({logs.length} lignes)</h3>
      <div className="logs-wrapper">
        {logs.map((log, idx) => (
          <pre key={idx} className={`log-entry ${log.level || "info"}`}>
            {JSON.stringify(log, null, 2)}
          </pre>
        ))}
      </div>
    </section>
  );
};

const DebugPage = () => {
  const [tables, setTables] = useState({ products: [], snapshots: [], scrape_runs: [] });
  const [logs, setLogs] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);

  const fetchDebugData = async () => {
    setLoading(true);
    setError(null);
    try {
      const [tablesRes, logsRes] = await Promise.all([
        fetch(`${BASE_URL}/debug/tables`),
        fetch(`${BASE_URL}/debug/logs`),
      ]);

      if (!tablesRes.ok || !logsRes.ok) {
        throw new Error("Erreur lors du chargement des données debug");
      }

      const tablesData = await tablesRes.json();
      const logsData = await logsRes.json();

      setTables(tablesData);
      setLogs(logsData.logs || []);
    } catch (err) {
      setError(err.message);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchDebugData();
  }, []);

  if (loading) {
    return (
      <main className="debug-page">
        <h2>Debug</h2>
        <p>Chargement...</p>
      </main>
    );
  }

  if (error) {
    return (
      <main className="debug-page">
        <h2>Debug</h2>
        <p className="error">{error}</p>
        <button onClick={fetchDebugData} className="btn">Réessayer</button>
      </main>
    );
  }

  return (
    <main className="debug-page">
      <div className="debug-header">
        <h2>Debug</h2>
        <button onClick={fetchDebugData} className="btn">
          <i className="fa-solid fa-refresh"></i> Rafraîchir
        </button>
      </div>

      <DbTable
        title="Products"
        data={tables.products}
        columns={["id", "boutique", "asin", "titre", "categorie", "actif", "cree_le"]}
      />

      <DbTable
        title="Snapshots"
        data={tables.snapshots}
        columns={["id", "produit_id", "scrape_le", "prix_actuel", "en_stock", "note", "statut_scrap"]}
      />

      <DbTable
        title="Scrape Runs"
        data={tables.scrape_runs}
        columns={["id", "demarre_le", "termine_le", "statut", "nb_total", "nb_ok", "nb_echec"]}
      />

      <LogViewer logs={logs} />
    </main>
  );
};

export default DebugPage;
