import { Suspense } from 'react';
import Link from 'next/link';
import { cookies } from 'next/headers';
import { redirect } from 'next/navigation';
import { loadSessionUser } from '@/src/server/session';
import { COOKIE_NAME } from '@/src/server/utils/auth';
import { invokeLocal } from '@/src/server/adapter';
import { actionDashboard, sampleDashboard } from '@/src/server/controllers/metaController';
import { formatRole } from '@/lib/format';
import { FilterBar } from './filter';
import { DashboardCharts, StatCard } from './charts';

export const dynamic = 'force-dynamic';

export default async function DashboardPage({ searchParams }: { searchParams?: Promise<Record<string, string | string[]>> }) {
  let user;
  try {
    user = await loadSessionUser((await cookies()).get(COOKIE_NAME)?.value);
  } catch {
    redirect('/login');
  }
  const sp = (await searchParams) ?? {};
  const pick = (k: string) => {
    const v = sp[k];
    return Array.isArray(v) ? v[0] : v;
  };
  const query: Record<string, string> = {};
  if (pick('from')) query.from = pick('from')!;
  if (pick('to')) query.to = pick('to')!;

  let a: any = null;
  let s: any = null;
  let degraded = false;
  try {
    [a, s] = await Promise.all([
      invokeLocal(actionDashboard, { user, query }),
      invokeLocal(sampleDashboard, { user }),
    ]);
  } catch (e) {
    console.error('[dashboard ssr]', e);
    degraded = true;
  }

  const todayLabel = new Date().toLocaleDateString('en-GB', { weekday: 'long', day: 'numeric', month: 'long', year: 'numeric' });
  const attention = (a?.overdue ?? 0) + (a?.dueToday ?? 0) + (s?.overdue ?? 0);
  return (
    <div className="space-y-4">
      <div className="relative overflow-hidden rounded-xl text-white shadow-sm"
        style={{ background: 'linear-gradient(120deg, #0B1626 30%, #1c3049 70%, #2c4a6b 100%)' }}>
        <div aria-hidden="true" className="absolute -right-16 -top-24 w-72 h-72 rounded-full opacity-20" style={{ background: 'radial-gradient(circle, #7FA8D9 0%, transparent 70%)' }} />
        <div aria-hidden="true" className="absolute right-24 -bottom-28 w-80 h-80 rounded-full opacity-10" style={{ background: 'radial-gradient(circle, #A9C3E6 0%, transparent 70%)' }} />
        <div className="relative p-5 md:p-6 flex flex-wrap gap-4 items-center">
          <div className="mr-auto min-w-0">
            <p className="text-xs font-semibold uppercase tracking-widest text-slate-300">
              {todayLabel} · <span className="text-white">{formatRole(user.role)}</span>
            </p>
            <h1 className="text-2xl md:text-[1.7rem] font-extrabold tracking-tight mt-1">
              Welcome back, {user.name?.split(' ')[0] ?? 'there'}
            </h1>
            <p className="text-sm text-slate-300 mt-0.5">
              {attention > 0 ? `${attention} item${attention === 1 ? '' : 's'} need${attention === 1 ? 's' : ''} attention right now.` : 'Everything is on track. Nice work.'}
            </p>
          </div>
          <div className="flex flex-wrap gap-2">
            <Link href="/actions" className="inline-flex h-10 items-center rounded-lg px-4 text-sm font-semibold bg-white text-slate-900 hover:bg-slate-100 transition">Deviations</Link>
            <Link href="/samples" className="inline-flex h-10 items-center rounded-lg px-4 text-sm font-semibold border border-white/40 text-white hover:bg-white/10 transition">QC Samples</Link>
            <Link href="/calendar" className="inline-flex h-10 items-center rounded-lg px-4 text-sm font-semibold border border-white/40 text-white hover:bg-white/10 transition">Calendar</Link>
          </div>
        </div>
      </div>
      <div className="flex flex-wrap gap-2 items-center">
        <h2 className="page-title mr-auto">{user.role === 'employee' ? 'My Work' : 'Overview'}</h2>
        <Suspense>
          <FilterBar />
        </Suspense>
      </div>
      {degraded && (
        <p role="alert" className="alert-error">Live data is unavailable right now — showing an empty dashboard. Check the database connection.</p>
      )}
      <div className="grid grid-cols-2 md:grid-cols-4 gap-3">
        <StatCard label="Total Deviations" value={a?.total} sub={`${a?.inProgress ?? 0} in progress`} tint="rgb(59, 130, 246)" icon="◈" />
        <StatCard label="Overdue" value={a?.overdue} sub={`${a?.dueToday ?? 0} due today · ${a?.dueSoon ?? 0} in 7 days`} tint="rgb(239, 68, 68)" icon="!" />
        <StatCard label="Escalated" value={a?.escalated} sub={`${a?.escL3 ?? 0} critical (L3)`} tint="rgb(245, 158, 11)" icon="▲" />
        <StatCard label="QC Samples" value={s?.total} sub={`${s?.testingWeek ?? 0} testing this week · ${s?.overdue ?? 0} overdue`} tint="rgb(16, 185, 129)" icon="●" />
      </div>
      {!degraded && <DashboardCharts action={a} sample={s} />}
    </div>
  );
}
