'use client';

/**
 * Right-side Sheet with the full activity stream for one session.
 * Driven by /api/v1/website-analytics?metric=session-activity. Each row
 * is a pageview or custom event in chronological order.
 */

import { Sheet, SheetContent, SheetHeader, SheetTitle } from '@/components/ui/sheet';
import { Skeleton } from '@/components/ui/skeleton';
import { useUmamiSessionActivity } from './use-website-analytics';
import { CountryFlag } from '@/components/shared/country-flag';
import { getCountryName } from '@/lib/i18n/countries';
import type { DateRange } from '@/lib/analytics/range';
import type { UmamiSession } from '@/lib/services/umami.service';

interface Props {
  session: UmamiSession | null;
  range: DateRange;
  onClose: () => void;
}

export function SessionDetailSheet({ session, range, onClose }: Props) {
  const activityQuery = useUmamiSessionActivity(range, session?.id ?? null);
  const activity = activityQuery.data?.data ?? [];

  return (
    <Sheet open={!!session} onOpenChange={(open) => !open && onClose()}>
      <SheetContent side="right" className="w-full sm:max-w-lg overflow-y-auto">
        <SheetHeader>
          <SheetTitle>Session detail</SheetTitle>
        </SheetHeader>

        {session ? (
          <div className="mt-4 space-y-5">
            {/* Top facts */}
            <dl className="grid grid-cols-2 gap-y-2 text-sm">
              <DtDd label="Location">
                <span className="inline-flex items-center gap-1.5">
                  {session.country ? (
                    <CountryFlag code={session.country} className="h-3 w-4" decorative />
                  ) : null}
                  <span>
                    {getCountryName(session.country, 'en') || 'Unknown'}
                    {session.city ? ` · ${session.city}` : ''}
                  </span>
                </span>
              </DtDd>
              <DtDd label="Device">{session.device}</DtDd>
              <DtDd label="Browser">{session.browser}</DtDd>
              <DtDd label="OS">{session.os}</DtDd>
              <DtDd label="Screen">{session.screen || '-'}</DtDd>
              <DtDd label="Language">{session.language || '-'}</DtDd>
              <DtDd label="First visit">{fmtTime(session.firstAt)}</DtDd>
              <DtDd label="Last visit">{fmtTime(session.lastAt)}</DtDd>
              <DtDd label="Visits">{session.visits.toLocaleString()}</DtDd>
              <DtDd label="Pageviews">{session.views.toLocaleString()}</DtDd>
            </dl>

            {/* Activity stream */}
            <div>
              <h3 className="text-sm font-medium">Activity</h3>
              {activityQuery.isLoading ? (
                <div className="mt-2 space-y-2">
                  {Array.from({ length: 6 }).map((_, i) => (
                    <Skeleton key={i} className="h-8 w-full" />
                  ))}
                </div>
              ) : activity.length === 0 ? (
                <p className="mt-2 text-xs text-muted-foreground">
                  No activity recorded for this session.
                </p>
              ) : (
                <ol className="mt-2 space-y-1 border-l border-border pl-3">
                  {activity.map((row) => (
                    <li key={row.eventId} className="relative text-xs">
                      <span className="absolute -left-[15px] top-1 inline-block size-2 rounded-full bg-brand" />
                      <div className="flex items-baseline justify-between gap-2">
                        <span className="truncate font-medium">
                          {row.eventName ? `Event: ${row.eventName}` : row.urlPath || '/'}
                        </span>
                        <span className="shrink-0 tabular-nums text-muted-foreground">
                          {fmtTime(row.createdAt)}
                        </span>
                      </div>
                      {row.eventName && row.urlPath ? (
                        <div className="text-muted-foreground">{row.urlPath}</div>
                      ) : null}
                    </li>
                  ))}
                </ol>
              )}
            </div>
          </div>
        ) : null}
      </SheetContent>
    </Sheet>
  );
}

function DtDd({ label, children }: { label: string; children: React.ReactNode }) {
  return (
    <>
      <dt className="text-xs uppercase tracking-wide text-muted-foreground">{label}</dt>
      <dd className="text-foreground">{children}</dd>
    </>
  );
}

function fmtTime(iso: string): string {
  const d = new Date(iso);
  if (isNaN(d.getTime())) return iso;
  return d.toLocaleString(undefined, { dateStyle: 'medium', timeStyle: 'short' });
}
