import Link from "next/link";
import { redirect } from "next/navigation";
import { format, formatDistanceToNow } from "date-fns";
import { fr } from "date-fns/locale";
import { ArrowRight, Droplet, History, PlusCircle, Smartphone, TrendingUp } from "lucide-react";
import { auth } from "@/lib/auth";
import { prisma } from "@/lib/prisma";
import {
  estimateHbA1c,
  formatValue,
  MOMENT_LABELS,
  STATUS_STYLE,
  statusFor,
  type Moment,
} from "@/lib/glycemia";
import { GlycemiaChart } from "@/components/GlycemiaChart";
import { DailyInsight } from "@/components/DailyInsight";

export const dynamic = "force-dynamic";

function summarize(rows: { value: number; moment: string }[]) {
  if (rows.length === 0) {
    return { count: 0, avg: null as number | null, inRangePct: null as number | null, hypo: 0, hyper: 0 };
  }
  let inRange = 0, hypo = 0, hyper = 0, sum = 0;
  for (const r of rows) {
    sum += r.value;
    const s = statusFor(r.value, r.moment as Moment);
    if (s === "in-range") inRange++;
    else if (s === "hypo") hypo++;
    else hyper++;
  }
  return { count: rows.length, avg: sum / rows.length, inRangePct: (inRange / rows.length) * 100, hypo, hyper };
}

export default async function DashboardPage() {
  const session = await auth();
  if (!session?.user?.id) redirect("/auth/login");
  const userId = session.user.id;
  const plan = (session.user as { plan?: string }).plan ?? "FREE";

  const now = new Date();
  const ago7 = new Date(now.getTime() - 7 * 24 * 60 * 60 * 1000);
  const ago30 = new Date(now.getTime() - 30 * 24 * 60 * 60 * 1000);
  const ago90 = new Date(now.getTime() - 90 * 24 * 60 * 60 * 1000);

  // FREE plan: only last 7 days
  const readingCutoff = plan === "PREMIUM" ? ago90 : ago7;

  const [last, last7, last30, last90, chartRows, patient] = await Promise.all([
    prisma.reading.findFirst({ where: { userId }, orderBy: { measuredAt: "desc" } }),
    prisma.reading.findMany({ where: { userId, measuredAt: { gte: ago7 } } }),
    plan === "PREMIUM"
      ? prisma.reading.findMany({ where: { userId, measuredAt: { gte: ago30 } } })
      : Promise.resolve([]),
    plan === "PREMIUM"
      ? prisma.reading.findMany({ where: { userId, measuredAt: { gte: ago90 } } })
      : Promise.resolve([]),
    prisma.reading.findMany({
      where: { userId, measuredAt: { gte: readingCutoff } },
      orderBy: { measuredAt: "asc" },
      select: { measuredAt: true, value: true, moment: true },
    }),
    prisma.patient.findUnique({ where: { userId }, select: { firstName: true } }),
  ]);

  const week = summarize(last7);
  const month = summarize(last30);
  const quarter = summarize(last90);
  const hba1c = quarter.avg ? estimateHbA1c(quarter.avg) : null;

  const lastStatus = last ? statusFor(last.value, last.moment as Moment) : null;
  const isPremium = plan === "PREMIUM";

  return (
    <div className="space-y-6">
      <div className="flex flex-wrap items-end justify-between gap-3">
        <div>
          <h1 className="text-2xl font-semibold text-slate-900">
            {patient ? `Bonjour ${patient.firstName}` : "Tableau de bord"}
          </h1>
          <p className="text-sm text-slate-500">
            Suivi de votre glycémie — 3 relevés par jour (matin, midi, soir).
          </p>
        </div>
        <div className="flex items-center gap-2">
          <Link
            href="/dashboard/mobile"
            className="inline-flex items-center gap-2 rounded-lg border border-teal-300 bg-teal-50 px-3 py-2 text-sm font-medium text-teal-700 hover:bg-teal-100 md:hidden"
          >
            <Smartphone className="h-4 w-4" />
            Saisie rapide
          </Link>
          <Link
            href="/dashboard/saisie"
            className="inline-flex items-center gap-2 rounded-lg bg-teal-600 px-4 py-2 text-sm font-medium text-white shadow-sm hover:bg-teal-700"
          >
            <PlusCircle className="h-4 w-4" />
            Nouveau relevé
          </Link>
        </div>
      </div>

      {/* Dernière mesure */}
      <section className="rounded-xl border border-slate-200 bg-white p-5 shadow-sm">
        <div className="flex items-center justify-between">
          <h2 className="text-sm font-medium text-slate-500 uppercase tracking-wide">Dernière mesure</h2>
          <Droplet className="h-4 w-4 text-teal-600" />
        </div>
        {last && lastStatus ? (
          <div className="mt-3 flex flex-wrap items-end gap-x-6 gap-y-3">
            <div>
              <div className="text-4xl font-semibold tracking-tight text-slate-900">
                {formatValue(last.value)}
              </div>
              <div className="mt-1 text-sm text-slate-500">
                {MOMENT_LABELS[last.moment as Moment]} · il y a{" "}
                {formatDistanceToNow(new Date(last.measuredAt), { locale: fr })}
              </div>
              <div className="mt-1 text-xs text-slate-400">
                {format(new Date(last.measuredAt), "EEEE d MMMM yyyy 'à' HH:mm", { locale: fr })}
              </div>
            </div>
            <span className={`inline-flex items-center rounded-full border px-3 py-1 text-xs font-medium ${STATUS_STYLE[lastStatus].bg} ${STATUS_STYLE[lastStatus].color} ${STATUS_STYLE[lastStatus].border}`}>
              {STATUS_STYLE[lastStatus].label}
            </span>
            {last.notes && (
              <div className="basis-full text-sm text-slate-600 italic">« {last.notes} »</div>
            )}
          </div>
        ) : (
          <div className="mt-3 text-sm text-slate-500">
            Aucun relevé pour le moment.{" "}
            <Link href="/dashboard/saisie" className="text-teal-700 underline">
              Saisir le premier
            </Link>
            .
          </div>
        )}
      </section>

      {isPremium ? (
        <DailyInsight />
      ) : (
        <section className="rounded-xl border border-amber-200 bg-amber-50 p-5">
          <p className="text-sm text-amber-800">
            💡 L&apos;analyse IA quotidienne et le coach Diablo sont disponibles avec le plan{" "}
            <Link href="/pricing" className="font-semibold underline">
              Premium
            </Link>
            .
          </p>
        </section>
      )}

      {/* Stats cards */}
      <section className="grid gap-4 sm:grid-cols-2 lg:grid-cols-4">
        <StatCard
          title="Moyenne 7 jours"
          value={week.avg !== null ? formatValue(week.avg) : "—"}
          sub={`${week.count} relevé${week.count > 1 ? "s" : ""}`}
        />
        {isPremium ? (
          <>
            <StatCard
              title="Moyenne 30 jours"
              value={month.avg !== null ? formatValue(month.avg) : "—"}
              sub={`${month.count} relevé${month.count > 1 ? "s" : ""}`}
            />
            <StatCard
              title="% dans la cible (30j)"
              value={month.inRangePct !== null ? `${month.inRangePct.toFixed(0)} %` : "—"}
              sub={month.count > 0 ? `${month.hypo} hypo · ${month.hyper} hyper` : "Aucune donnée"}
              accent={
                month.inRangePct === null
                  ? undefined
                  : month.inRangePct >= 70
                    ? "text-emerald-700"
                    : month.inRangePct >= 50
                      ? "text-amber-700"
                      : "text-rose-700"
              }
            />
            <StatCard
              title="HbA1c estimée (90j)"
              value={hba1c !== null ? `${hba1c.toFixed(1)} %` : "—"}
              sub="Indicatif — basé sur la moyenne"
            />
          </>
        ) : (
          <div className="col-span-3 flex items-center rounded-xl border border-slate-200 bg-white px-4 py-4 shadow-sm">
            <p className="text-sm text-slate-500">
              Statistiques 30/90 jours et HbA1c estimée disponibles avec le plan{" "}
              <Link href="/pricing" className="text-teal-700 underline font-medium">Premium</Link>.
            </p>
          </div>
        )}
      </section>

      {/* Chart */}
      <section className="rounded-xl border border-slate-200 bg-white p-5 shadow-sm">
        <div className="mb-3 flex items-center justify-between">
          <h2 className="flex items-center gap-2 text-sm font-medium text-slate-700">
            <TrendingUp className="h-4 w-4 text-teal-600" />
            {isPremium ? "Évolution sur 30 jours" : "Évolution sur 7 jours"}
          </h2>
          <Link
            href="/dashboard/historique"
            className="inline-flex items-center gap-1 text-xs font-medium text-teal-700 hover:text-teal-900"
          >
            <History className="h-3.5 w-3.5" />
            Voir l&apos;historique
            <ArrowRight className="h-3 w-3" />
          </Link>
        </div>
        <GlycemiaChart
          data={chartRows.map((r) => ({
            measuredAt: r.measuredAt.toISOString(),
            value: r.value,
            moment: r.moment,
          }))}
        />
        <div className="mt-3 flex flex-wrap gap-3 text-xs text-slate-500">
          <LegendDot color="bg-emerald-400/60" label="Cible (0,7 – 1,8 g/L)" />
          <LegendDot color="bg-amber-400/60" label="Hypo (< 0,7)" />
          <LegendDot color="bg-amber-400/60" label="Hyper (> 1,8)" />
        </div>
      </section>
    </div>
  );
}

function StatCard({ title, value, sub, accent }: { title: string; value: string; sub?: string; accent?: string }) {
  return (
    <div className="rounded-xl border border-slate-200 bg-white p-4 shadow-sm">
      <div className="text-xs font-medium uppercase tracking-wide text-slate-500">{title}</div>
      <div className={`mt-2 text-2xl font-semibold ${accent ?? "text-slate-900"}`}>{value}</div>
      {sub && <div className="mt-1 text-xs text-slate-500">{sub}</div>}
    </div>
  );
}

function LegendDot({ color, label }: { color: string; label: string }) {
  return (
    <span className="inline-flex items-center gap-1.5">
      <span className={`inline-block h-3 w-3 rounded-sm ${color}`} />
      {label}
    </span>
  );
}
