import { Search } from 'lucide-react';
import { requireUser } from '@/lib/auth/dal';
import { listOwnReports } from '@/lib/reports/access';
import { chakraMeta } from '@/lib/aura/chakraMeta';
import type { ChakraType } from '@/lib/aura/types';
import { NewScanButton } from '@/components/account/NewScanButton';
import { ReportCard } from '@/components/account/ReportCard';
import { EmptyState, PageHeader, Panel, ShellPage } from '@/components/layout/DashboardPage';
import { getLocale, getMessages } from '@/i18n/server';

export default async function MyReportsPage({
  searchParams,
}: {
  searchParams: Promise<Record<string, string | string[] | undefined>>;
}) {
  const user = await requireUser('/akun/laporan');
  const locale = await getLocale();
  const all = await getMessages();
  const t = all.dash.reports;
  const sp = await searchParams;
  const q = typeof sp.q === 'string' ? sp.q.trim().toLowerCase().slice(0, 80) : '';

  const reports = await listOwnReports(user.id);
  const meta = chakraMeta(locale);
  const shown = q
    ? reports.filter((r) =>
        [
          r.subjectName,
          r.auraProfile ?? '',
          r.dominantChakra ? meta[r.dominantChakra as ChakraType].archetype : '',
          r.eventName ?? '',
          ...r.services.map((sv) => all.services.names[sv]),
        ]
          .join(' ')
          .toLowerCase()
          .includes(q),
      )
    : reports;

  return (
    <ShellPage>
      <PageHeader eyebrow={t.eyebrow} title={t.title} text={t.text(reports.length)} actions={<NewScanButton userName={user.name} />} />

      {reports.length > 0 && (
        <form role="search" className="relative mt-8 sm:w-80">
          <Search className="pointer-events-none absolute top-1/2 left-4 size-4 -translate-y-1/2 text-subtle" aria-hidden />
          <label htmlFor="q" className="sr-only">
            {all.dash.common.search}
          </label>
          <input
            id="q"
            name="q"
            type="search"
            defaultValue={q}
            placeholder={t.searchPlaceholder}
            className="h-10 w-full rounded-full bg-surface pr-4 pl-10 text-[13px] text-ink ring-1 ring-line placeholder:text-subtle focus:ring-2 focus:ring-ink/70 focus:outline-none"
          />
        </form>
      )}

      {reports.length === 0 ? (
        <Panel className="mt-8">
          <EmptyState title={all.account.emptyTitle} text={all.dash.overview.noReportText}>
            <NewScanButton userName={user.name} />
          </EmptyState>
        </Panel>
      ) : shown.length === 0 ? (
        <Panel className="mt-6">
          <EmptyState text={t.noMatch} />
        </Panel>
      ) : (
        <ul className="mt-6 grid gap-4 sm:grid-cols-2 lg:grid-cols-3">
          {shown.map((r) => (
            <ReportCard key={r.id} report={r} locale={locale} sessionLabel={t.fromSession} serviceNames={all.services.short} />
          ))}
        </ul>
      )}
    </ShellPage>
  );
}
