import { apiFetch, getCurrentUser, type CurrentUser } from "@/lib/api";
import { getDict, getLocale } from "@/lib/i18n";
import { Icon, type IconName } from "@/components/Icon";

export const dynamic = "force-dynamic";

interface DashboardSummary {
  user: { id: number; fullName: string; isDemo: boolean; mustChangePassword: boolean };
  stats: {
    users: { total: number; active: number; demo: number };
    roles: { total: number; governanceConfirmed: number; activeAssignments: number };
    activeSessions: number;
    auditEvents24h: number;
  };
  recentAudit: {
    id: number;
    occurred_at: string;
    action: string;
    entity_type: string | null;
    actor_username: string | null;
  }[];
  system: { schemaVersion: string | null; schemaAppliedAt: string | null; canViewAudit: boolean; canManageUsers: boolean };
  modules: {
    code: string;
    nameAr: string;
    nameEn?: string;
    description: string;
    descriptionEn?: string;
    href: string;
    color: string;
    status: "ready" | "in_development" | "planned";
    accessible: boolean;
    permitted: boolean;
  }[];
}

const MODULE_ICONS: Record<string, IconName> = {
  members: "users",
  structure: "sitemap",
  plans: "clipboard",
  activities: "sparkles",
  meetings: "scale",
  training: "academic",
  kpis: "chart",
};

const COLOR_CLASSES: Record<string, string> = {
  emerald: "bg-emerald-50 text-emerald-700 ring-emerald-600/20",
  sky: "bg-sky-50 text-sky-700 ring-sky-600/20",
  violet: "bg-violet-50 text-violet-700 ring-violet-600/20",
  amber: "bg-amber-50 text-amber-700 ring-amber-600/20",
  rose: "bg-rose-50 text-rose-700 ring-rose-600/20",
  teal: "bg-teal-50 text-teal-700 ring-teal-600/20",
  indigo: "bg-indigo-50 text-indigo-700 ring-indigo-600/20",
};

function formatDateTimeCairo(iso: string): string {
  return new Intl.DateTimeFormat("ar-EG", {
    dateStyle: "medium",
    timeStyle: "short",
    timeZone: "Africa/Cairo",
  }).format(new Date(iso));
}

function StatCard({ label, value, hint, icon }: { label: string; value: number | string; hint?: string; icon: IconName }) {
  return (
    <div className="rounded-xl border border-slate-200 bg-white p-5 shadow-card transition hover:shadow-card-hover">
      <div className="flex items-start justify-between gap-3">
        <div>
          <p className="text-sm font-semibold text-slate-500">{label}</p>
          <p className="numeric mt-2 text-3xl font-extrabold text-slate-900">{value}</p>
          {hint && <p className="mt-1 text-xs text-slate-400">{hint}</p>}
        </div>
        <span className="grid h-11 w-11 shrink-0 place-items-center rounded-lg bg-bousla-50 text-bousla-700 ring-1 ring-bousla-600/10">
          <Icon name={icon} className="h-5 w-5" />
        </span>
      </div>
    </div>
  );
}

export default async function DashboardPage() {
  const t = await getDict();
  const locale = await getLocale();
  const user: CurrentUser | null = await getCurrentUser();
  const { status, data } = await apiFetch<DashboardSummary>("/api/dashboard/summary");

  if (status !== 200 || !data) {
    return (
      <div className="rounded-xl border border-red-200 bg-red-50 p-6 text-sm text-red-700">
        {t.dashboard.loadError}
      </div>
    );
  }

  const firstName = user?.fullName.split(" ").slice(0, 2).join(" ") ?? "";

  return (
    <div className="space-y-8">
      <header>
        <h1 className="text-2xl font-extrabold text-slate-900">
          {t.dashboard.hello}{locale === "ar" ? "،" : ","} <span className="text-bousla-700">{firstName}</span>
        </h1>
        <p className="mt-1 text-sm text-slate-500">
          {t.dashboard.subtitle}
        </p>
      </header>

      <section aria-label={t.dashboard.kpisSection}>
        <div className="grid grid-cols-1 gap-4 sm:grid-cols-2 xl:grid-cols-4">
          <StatCard
            label={t.dashboard.statsAccounts}
            value={data.stats.users.total}
            hint={`${data.stats.users.active} ${t.dashboard.statsAccountsHintActive} · ${data.stats.users.demo} ${t.dashboard.statsAccountsHintDemo}`}
            icon="users"
          />
          <StatCard
            label={t.dashboard.statsRoles}
            value={data.stats.roles.total}
            hint={`${data.stats.roles.governanceConfirmed} ${t.dashboard.statsRolesHint}`}
            icon="shield"
          />
          <StatCard
            label={t.dashboard.statsAssignments}
            value={data.stats.roles.activeAssignments}
            hint={t.dashboard.statsAssignmentsHint}
            icon="sitemap"
          />
          <StatCard
            label={t.dashboard.statsAudit}
            value={data.stats.auditEvents24h}
            hint={`${data.stats.activeSessions} ${t.dashboard.statsAuditHintActive}`}
            icon="database"
          />
        </div>
      </section>

      <section aria-label={t.dashboard.modulesSection}>
        <div className="mb-4 flex items-baseline justify-between">
          <h2 className="text-lg font-bold text-slate-900">{t.dashboard.modulesSection}</h2>
          <p className="text-xs text-slate-400">{t.dashboard.modulesTrueStatus}</p>
        </div>
        <div className="grid grid-cols-1 gap-4 sm:grid-cols-2 xl:grid-cols-3">
          {data.modules.map((m) => (
            <article
              key={m.code}
              className={`rounded-xl border bg-white p-5 shadow-card transition ${
                m.accessible ? "border-slate-200 hover:shadow-card-hover" : "border-dashed border-slate-300"
              }`}
            >
              <div className="flex items-start justify-between gap-3">
                <span className={`grid h-11 w-11 shrink-0 place-items-center rounded-lg ring-1 ${COLOR_CLASSES[m.color] ?? COLOR_CLASSES.teal}`}>
                  <Icon name={MODULE_ICONS[m.code] ?? "compass"} className="h-5 w-5" />
                </span>
                <span className="rounded-full bg-slate-100 px-2.5 py-1 text-[11px] font-bold text-slate-500">
                  {m.status === "ready" ? t.dashboard.statusReady : m.status === "in_development" ? t.dashboard.statusDev : t.dashboard.statusPlanned}
                </span>
              </div>
              <h3 className="mt-4 font-bold text-slate-900" dir="auto">{locale === "en" && m.nameEn ? m.nameEn : m.nameAr}</h3>
              <p className="mt-1 min-h-10 text-sm leading-6 text-slate-500" dir="auto">{locale === "en" && m.descriptionEn ? m.descriptionEn : m.description}</p>
              <div className="mt-4">
                {m.accessible ? (
                  <a href={m.href} className="inline-flex items-center gap-1.5 text-sm font-bold text-bousla-700 hover:text-bousla-800">
                    {t.dashboard.openModule}
                  </a>
                ) : (
                  <p className="text-xs font-semibold text-slate-400">
                    {m.permitted
                      ? t.dashboard.moduleSoon
                      : t.dashboard.moduleLocked}
                  </p>
                )}
              </div>
            </article>
          ))}
        </div>
      </section>

      <section aria-label={t.dashboard.recentEvents} className="grid gap-6 lg:grid-cols-3">
        <div className="rounded-xl border border-slate-200 bg-white p-5 shadow-card lg:col-span-2">
          <div className="mb-4 flex items-center justify-between">
            <h2 className="flex items-center gap-2 text-lg font-bold text-slate-900">
              <Icon name="shield" className="h-5 w-5 text-bousla-700" />
              {t.dashboard.recentEvents}
            </h2>
            {data.system.canViewAudit && (
              <a href="/dashboard/audit" className="text-sm font-bold text-bousla-700 hover:text-bousla-800">
                {t.dashboard.fullLog}
              </a>
            )}
          </div>
          {data.system.canViewAudit ? (
            data.recentAudit.length === 0 ? (
              <p className="rounded-lg bg-slate-50 px-4 py-6 text-center text-sm text-slate-400">{t.dashboard.noEvents}</p>
            ) : (
              <ul className="divide-y divide-slate-100">
                {data.recentAudit.map((a) => (
                  <li key={a.id} className="flex flex-wrap items-center justify-between gap-2 py-2.5 text-sm">
                    <span className="flex items-center gap-2.5">
                      <code className="numeric rounded bg-slate-100 px-2 py-0.5 text-[11px] font-semibold text-slate-600" dir="ltr">
                        {a.action}
                      </code>
                      <span className="text-slate-500" dir="ltr">{a.actor_username ?? "—"}</span>
                    </span>
                    <span className="text-xs text-slate-400">{formatDateTimeCairo(a.occurred_at)}</span>
                  </li>
                ))}
              </ul>
            )
          ) : (
            <p className="rounded-lg bg-slate-50 px-4 py-6 text-center text-sm text-slate-400">
              {t.dashboard.auditRestricted}
            </p>
          )}
        </div>

        <div className="rounded-xl border border-slate-200 bg-white p-5 shadow-card">
          <h2 className="mb-4 flex items-center gap-2 text-lg font-bold text-slate-900">
            <Icon name="database" className="h-5 w-5 text-bousla-700" />
            {t.dashboard.systemStatus}
          </h2>
          <dl className="space-y-3 text-sm">
            <div className="flex items-center justify-between">
              <dt className="text-slate-500">{t.dashboard.dbLabel}</dt>
              <dd className="rounded-full bg-emerald-50 px-2.5 py-0.5 text-xs font-bold text-emerald-700">{t.dashboard.dbConnected}</dd>
            </div>
            <div className="flex items-center justify-between">
              <dt className="text-slate-500">{t.dashboard.schemaVersion}</dt>
              <dd className="numeric font-bold text-slate-800" dir="ltr">{data.system.schemaVersion ?? "—"}</dd>
            </div>
            <div className="flex items-center justify-between">
              <dt className="text-slate-500">{t.dashboard.lastMigration}</dt>
              <dd className="text-xs text-slate-600">
                {data.system.schemaAppliedAt ? formatDateTimeCairo(data.system.schemaAppliedAt) : "—"}
              </dd>
            </div>
            <div className="flex items-center justify-between">
              <dt className="text-slate-500">{t.dashboard.activeSessions}</dt>
              <dd className="numeric font-bold text-slate-800">{data.stats.activeSessions}</dd>
            </div>
          </dl>
        </div>
      </section>
    </div>
  );
}
