// apps/web/app/(shell)/compliance/page.tsx
import { prisma } from "@dpf/db";
import { RegulatoryAlerts } from "@/components/compliance/RegulatoryAlerts";
import { ScanStatus } from "@/components/compliance/ScanStatus";
import { LocalTime } from "@/components/ui/LocalTime";

export default async function CompliancePage() {
  const [
    regulationCount,
    activeObligationCount,
    implementedControlCount,
    totalControlCount,
    openIncidentCount,
    overdueActionCount,
    regulations,
    upcomingDeadlines,
    recentActivity,
    publishedPolicyCount,
    totalAcks,
    pendingAlerts,
    latestScan,
  ] = await Promise.all([
    prisma.regulation.count({ where: { status: "active" } }),
    prisma.obligation.count({ where: { status: "active" } }),
    prisma.control.count({ where: { implementationStatus: "implemented", status: "active" } }),
    prisma.control.count({ where: { status: "active" } }),
    prisma.complianceIncident.count({ where: { status: { in: ["open", "investigating"] } } }),
    prisma.correctiveAction.count({ where: { status: { in: ["open", "in-progress"] }, dueDate: { lt: new Date() } } }),
    prisma.regulation.findMany({
      where: { status: "active" },
      include: { _count: { select: { obligations: true } } },
      orderBy: { shortName: "asc" },
    }),
    prisma.calendarEvent.findMany({
      where: { complianceEntityType: { not: null }, startAt: { gte: new Date() } },
      orderBy: { startAt: "asc" },
      take: 5,
      select: { id: true, title: true, startAt: true },
    }),
    prisma.complianceAuditLog.findMany({
      orderBy: { performedAt: "desc" },
      take: 10,
      include: { performedBy: { select: { displayName: true } } },
    }),
    prisma.policy.count({ where: { lifecycleStatus: "published", status: "active" } }),
    prisma.policyAcknowledgment.count(),
    prisma.regulatoryAlert.findMany({
      where: { status: "pending" },
      include: { regulation: { select: { shortName: true, jurisdiction: true } } },
      orderBy: [{ severity: "desc" }, { createdAt: "desc" }],
      take: 10,
    }),
    prisma.regulatoryMonitorScan.findFirst({
      orderBy: { startedAt: "desc" },
      select: { scanId: true, status: true, startedAt: true, regulationsChecked: true, alertsGenerated: true },
    }),
  ]);

  const coveragePct = totalControlCount > 0
    ? Math.round((implementedControlCount / totalControlCount) * 100)
    : 0;

  return (
    <div>
      <div className="mb-6">
        <h1 className="text-xl font-bold text-[var(--dpf-text)]">Compliance</h1>
        <p className="text-sm text-[var(--dpf-muted)] mt-0.5">
          {regulationCount} regulation{regulationCount !== 1 ? "s" : ""} · {activeObligationCount} obligation{activeObligationCount !== 1 ? "s" : ""}
        </p>
      </div>

      {/* Posture Summary */}
      <div className="grid grid-cols-2 lg:grid-cols-4 gap-4 mb-8">
        <MetricCard label="Obligations" value={activeObligationCount} accent="var(--dpf-accent)" />
        <MetricCard label="Control Coverage" value={`${coveragePct}%`} accent={coveragePct >= 80 ? "var(--dpf-success)" : "var(--dpf-warning)"} />
        <MetricCard label="Open Incidents" value={openIncidentCount} accent={openIncidentCount > 0 ? "var(--dpf-error)" : "var(--dpf-success)"} />
        <MetricCard label="Overdue Actions" value={overdueActionCount} accent={overdueActionCount > 0 ? "var(--dpf-error)" : "var(--dpf-success)"} />
      </div>

      {/* Regulatory Alerts */}
      <section className="mb-8">
        <h2 className="text-xs text-[var(--dpf-muted)] uppercase tracking-widest mb-3">Regulatory Alerts</h2>
        <ScanStatus latestScan={latestScan} />
        <div className="mt-4">
          <RegulatoryAlerts alerts={pendingAlerts} />
        </div>
      </section>

      {/* Upcoming Deadlines */}
      <section className="mb-8">
        <h2 className="text-xs text-[var(--dpf-muted)] uppercase tracking-widest mb-3">Upcoming Deadlines</h2>
        {upcomingDeadlines.length === 0
          ? <p className="text-sm text-[var(--dpf-muted)]">No upcoming compliance deadlines.</p>
          : <ul className="space-y-2">
              {upcomingDeadlines.map((e) => (
                <li key={e.id} className="text-sm text-[var(--dpf-text)] flex justify-between">
                  <span>{e.title}</span>
                  <LocalTime value={e.startAt} mode="date" className="text-[var(--dpf-muted)]" />
                </li>
              ))}
            </ul>
        }
      </section>

      {/* Recent Activity */}
      <section className="mb-8">
        <h2 className="text-xs text-[var(--dpf-muted)] uppercase tracking-widest mb-3">Recent Activity</h2>
        {recentActivity.length === 0
          ? <p className="text-sm text-[var(--dpf-muted)]">No compliance activity yet.</p>
          : <ul className="space-y-2">
              {recentActivity.map((log) => (
                <li key={log.id} className="text-sm text-[var(--dpf-muted)]">
                  <span className="text-[var(--dpf-text)]">{log.performedBy?.displayName ?? log.agentId ?? "System"}</span>{" "}
                  {log.action} {log.entityType} — <LocalTime value={log.performedAt} />
                </li>
              ))}
            </ul>
        }
      </section>

      {/* By Regulation */}
      <section>
        <h2 className="text-xs text-[var(--dpf-muted)] uppercase tracking-widest mb-3">By Regulation</h2>
        {regulations.length === 0
          ? <p className="text-sm text-[var(--dpf-muted)]">No regulations registered yet. Add your first regulation to get started.</p>
          : <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
              {regulations.map((r) => (
                <a key={r.id} href={`/compliance/regulations/${r.id}`}
                  className="block p-4 rounded-lg border border-[var(--dpf-border)] hover:border-[var(--dpf-accent)] transition-colors">
                  <div className="flex items-center gap-2 mb-1">
                    <span className="text-sm font-semibold text-[var(--dpf-text)]">{r.shortName}</span>
                    <span className="text-[9px] px-1.5 py-0.5 rounded-full bg-[var(--dpf-surface-2)] text-[var(--dpf-muted)]">{r.jurisdiction}</span>
                  </div>
                  <p className="text-xs text-[var(--dpf-muted)]">
                    {r._count.obligations} obligation{r._count.obligations !== 1 ? "s" : ""}
                  </p>
                </a>
              ))}
            </div>
        }
      </section>

      {/* Policy Compliance */}
      <section className="mt-8">
        <h2 className="text-xs text-[var(--dpf-muted)] uppercase tracking-widest mb-3">Policy Compliance</h2>
        <div className="grid grid-cols-2 lg:grid-cols-3 gap-4">
          <MetricCard label="Published Policies" value={publishedPolicyCount} accent="var(--dpf-accent)" />
          <MetricCard label="Total Acknowledgments" value={totalAcks} accent="var(--dpf-success)" />
        </div>
      </section>
    </div>
  );
}

function MetricCard({ label, value, accent }: { label: string; value: number | string; accent: string }) {
  return (
    <div
      className="p-4 rounded-lg border"
      style={{
        borderColor: `color-mix(in srgb, ${accent} 28%, var(--dpf-border))`,
        background: `color-mix(in srgb, ${accent} 8%, var(--dpf-surface-1))`,
      }}
    >
      <p className="text-xs text-[var(--dpf-muted)] mb-1">{label}</p>
      <p className="text-2xl font-bold" style={{ color: accent }}>{value}</p>
    </div>
  );
}
