import Link from "next/link";
import { redirect } from "next/navigation";
import { DashboardHeader } from "@/components/dashboard/DashboardHeader";
import { isAuthenticated } from "@/lib/auth";
import { loadAppsFlyerMediaReport } from "@/lib/appsflyer-media-report";

export const dynamic = "force-dynamic";

const PROJECT_START_DATE = "2026-07-01";

function formatDate(date: Date) {
  return date.toISOString().slice(0, 10);
}

function validDate(value?: string) {
  return value && /^\d{4}-\d{2}-\d{2}$/.test(value) ? value : null;
}

function number(value: number | null) {
  return value === null ? "—" : new Intl.NumberFormat("fr-FR").format(value);
}

function rate(numerator: number | null, denominator: number | null) {
  if (numerator === null || denominator === null || denominator <= 0) return "—";
  return `${(numerator / denominator * 100).toFixed(1)} %`;
}

function dateTime(value: Date | null | undefined) {
  if (!value) return "—";
  return new Intl.DateTimeFormat("fr-FR", {
    dateStyle: "short",
    timeStyle: "medium",
    timeZone: "Africa/Casablanca",
  }).format(value);
}

function statusLabel(status?: string) {
  return ({ idle: "En attente", running: "En cours", stopped: "Arrêté", completed: "Terminé", success: "Succès", failed: "Échec" } as Record<string, string>)[status ?? ""] ?? "Non initialisé";
}

export default async function AppsFlyerPage({
  searchParams,
}: {
  searchParams: Promise<{ since?: string; until?: string }>;
}) {
  if (!await isAuthenticated()) redirect("/login");

  const params = await searchParams;
  const cutoff = new Date();
  cutoff.setUTCDate(cutoff.getUTCDate() - 2);
  const maxDate = formatDate(cutoff);
  const requestedUntil = validDate(params.until) ?? maxDate;
  const until = requestedUntil > maxDate ? maxDate : requestedUntil;
  const requestedSince = validDate(params.since) ?? PROJECT_START_DATE;
  const since = requestedSince < PROJECT_START_DATE ? PROJECT_START_DATE : requestedSince > until ? until : requestedSince;
  const report = await loadAppsFlyerMediaReport(10, since, until);
  const hasAlerts = report.missingDates.length > 0 || report.metricIssueCount > 0 || report.errors.length > 0 || report.state?.status === "stopped";

  return (
    <>
      <DashboardHeader title="Contrôle AppsFlyer Media Stats" />
      <main className="dashboard appsflyerPage">
        <nav className="dashboardModes" aria-label="Navigation du tableau de bord">
          <Link className="active" href="/appsflyer" aria-current="page">AppsFlyer database</Link>
        </nav>

        <section className="appsflyerIntro">
          <div>
            <p>Qualité et disponibilité des données</p>
            <h2>Suivi de la synchronisation AppsFlyer</h2>
            <span>Client 10 · données disponibles jusqu’à J-2 · source affichée : {report.source === "production" ? "table principale" : "préparation en cours"}</span>
          </div>
          <form className="appsflyerFilters">
            <label><span>Depuis</span><input type="date" name="since" min={PROJECT_START_DATE} max={until} defaultValue={since} /></label>
            <label><span>Jusqu’au</span><input type="date" name="until" min={PROJECT_START_DATE} max={maxDate} defaultValue={until} /></label>
            <button type="submit">Analyser</button>
          </form>
        </section>

        {"setupError" in report && report.setupError ? <div className="appsflyerBanner danger">{report.setupError}</div> : null}
        <section className="appsflyerStatusGrid" aria-label="État de la synchronisation">
          <article><span>État du cron</span><strong className={`status-${report.state?.status ?? "unknown"}`}>{statusLabel(report.state?.status)}</strong><small>Mis à jour : {dateTime(report.state?.updatedAt)}</small></article>
          <article><span>Couverture affichée</span><strong>{report.rows.length} jours</strong><small>{since} → {until}</small></article>
          <article><span>Prochaine période</span><strong>{report.state?.nextSince ?? "—"}</strong><small>Dernier succès : {report.state?.lastSuccessUntil ?? "—"}</small></article>
          <article className={hasAlerts ? "hasAlert" : "isHealthy"}><span>Anomalies détectées</span><strong>{report.missingDates.length + report.metricIssueCount + report.errors.length}</strong><small>{hasAlerts ? "Analyse requise" : "Aucune anomalie détectée"}</small></article>
        </section>

        {report.state?.status === "stopped" ? (
          <div className="appsflyerBanner danger"><strong>Synchronisation arrêtée</strong><span>Période : {report.state.failedSince ?? "—"} → {report.state.failedUntil ?? "—"}</span><span>{report.state.lastError ?? "Erreur inconnue"}</span></div>
        ) : null}

        <section className="appsflyerAnalysisGrid">
          <article className="appsflyerPanel">
            <header><div><p>Continuité</p><h3>Dates manquantes</h3></div><span className={report.missingDates.length ? "pill bad" : "pill ok"}>{report.missingDates.length}</span></header>
            {report.missingDates.length ? <div className="appsflyerTagList">{report.missingDates.map((date) => <span key={date}>{date}</span>)}</div> : <p className="appsflyerEmpty">Toutes les dates de la période sont présentes.</p>}
          </article>

          <article className="appsflyerPanel">
            <header><div><p>Qualité des métriques</p><h3>Jours avec valeurs manquantes</h3></div><span className={report.metricIssueCount ? "pill warn" : "pill ok"}>{report.metricIssueCount}</span></header>
            {report.metricIssueCount ? <div className="appsflyerAlertList">{report.rows.filter((row) => row.issues.length).map((row) => <div key={row.date}><strong>{row.date}</strong>{row.issues.map((message) => <span key={message}>{message}</span>)}</div>)}</div> : <p className="appsflyerEmpty">Toutes les métriques attendues sont disponibles.</p>}
          </article>
        </section>

        <section className="appsflyerPanel appsflyerDataPanel">
          <header><div><p>Données quotidiennes</p><h3>AppsFlyer · installs et onboarding</h3><span>{report.productionCount} jours en production · {report.stagingCount} jours en préparation</span></div><span className="pill ok">{report.rows.length} lignes</span></header>
          <div className="appsflyerTableScroll">
            <table className="appsflyerTable">
              <thead><tr><th>Date</th><th>Qualité</th><th>Installs</th><th>Onboarding démarrés</th><th>Onboarding réussis</th><th>Install → démarrage</th><th>Démarrage → réussite</th><th>Install → réussite</th></tr></thead>
              <tbody>{report.rows.map((row) => <tr key={row.date} className={row.issues.length ? "rowIssue" : ""}><td>{row.date}</td><td>{row.issues.length ? <span className="pill bad" title={row.issues.join(", ")}>À vérifier</span> : <span className="pill ok">OK</span>}</td><td>{number(row.installs)}</td><td>{number(row.onboardingStart)}</td><td>{number(row.onboardingSuccess)}</td><td>{rate(row.onboardingStart, row.installs)}</td><td>{rate(row.onboardingSuccess, row.onboardingStart)}</td><td>{rate(row.onboardingSuccess, row.installs)}</td></tr>)}</tbody>
            </table>
            {!report.rows.length ? <p className="appsflyerEmpty tableEmpty">Aucune donnée disponible pour cette période.</p> : null}
          </div>
        </section>

        <section className="appsflyerAnalysisGrid">
          <article className="appsflyerPanel">
            <header><div><p>Historique</p><h3>Dernières exécutions</h3></div></header>
            <div className="appsflyerMiniTable"><table><thead><tr><th>Période</th><th>Statut</th><th>Démarrage</th></tr></thead><tbody>{report.runs.map((run) => <tr key={run.id}><td>{run.since} → {run.until}</td><td><span className={`pill ${run.status === "success" ? "ok" : run.status === "failed" ? "bad" : "warn"}`}>{statusLabel(run.status)}</span></td><td>{dateTime(run.startedAt)}</td></tr>)}</tbody></table>{!report.runs.length ? <p className="appsflyerEmpty">Aucune exécution enregistrée.</p> : null}</div>
          </article>

          <article className="appsflyerPanel">
            <header><div><p>Journal</p><h3>Dernières erreurs</h3></div><span className={report.errors.length ? "pill bad" : "pill ok"}>{report.errors.length}</span></header>
            {report.errors.length ? <div className="appsflyerErrorList">{report.errors.map((error) => <div key={error.id}><time>{dateTime(error.created_at)}</time><strong>{error.message}</strong><span>{error.event}</span></div>)}</div> : <p className="appsflyerEmpty">Aucune erreur enregistrée.</p>}
          </article>
        </section>
      </main>
    </>
  );
}
