'use client';

import { useState } from 'react';
import { usePathname, useRouter, useSearchParams } from 'next/navigation';
import { useAdminActivity } from '@/lib/queries/use-admin';
import type { AdminActivityQueryInput } from '@alqove/api-client';

const SUBJECT_TYPES: Array<AdminActivityQueryInput['subject_type'] | undefined> = [
  undefined,
  'Dispute',
  'Order',
  'Store',
  'User',
  'Review',
  'ReviewReport',
];

const VALID_SUBJECT_TYPES = [
  'Dispute',
  'Order',
  'Store',
  'User',
  'Review',
  'ReviewReport',
] as const;

const EVENT_PREFIXES: Array<{ value: string | undefined; label: string }> = [
  { value: undefined, label: 'All events' },
  { value: 'review.', label: 'Review events' },
  { value: 'review_report.', label: 'Review report events' },
];

const VALID_EVENT_PREFIXES = ['review.', 'review_report.'] as const;

export function ActivityClient() {
  const router = useRouter();
  const pathname = usePathname();
  const searchParams = useSearchParams();
  const raw = searchParams.get('subject_type');
  const subjectType: AdminActivityQueryInput['subject_type'] | undefined =
    raw && (VALID_SUBJECT_TYPES as readonly string[]).includes(raw)
      ? (raw as AdminActivityQueryInput['subject_type'])
      : undefined;
  const rawPrefix = searchParams.get('event_prefix');
  const eventPrefix: string | undefined =
    rawPrefix && (VALID_EVENT_PREFIXES as readonly string[]).includes(rawPrefix)
      ? rawPrefix
      : undefined;
  const setSubjectType = (next: AdminActivityQueryInput['subject_type'] | undefined) => {
    const params = new URLSearchParams(searchParams.toString());
    if (next) params.set('subject_type', next);
    else params.delete('subject_type');
    const qs = params.toString();
    router.replace(qs ? `${pathname}?${qs}` : pathname);
  };
  const setEventPrefix = (next: string | undefined) => {
    const params = new URLSearchParams(searchParams.toString());
    if (next) params.set('event_prefix', next);
    else params.delete('event_prefix');
    const qs = params.toString();
    router.replace(qs ? `${pathname}?${qs}` : pathname);
  };
  const [openId, setOpenId] = useState<number | null>(null);
  const { data, isLoading, isError } = useAdminActivity({
    subject_type: subjectType,
    event_prefix: eventPrefix,
  });
  const rows = data?.data ?? [];

  return (
    <div>
      <h1 className="text-2xl font-bold text-slate-900">Activity log</h1>
      <p className="mt-1 text-sm text-slate-500">
        Every state-changing admin action with the actor and justification.
      </p>

      <div className="mt-4 flex flex-wrap gap-2" data-testid="subject-type-pills">
        {SUBJECT_TYPES.map((s) => (
          <button
            key={s ?? 'all'}
            onClick={() => setSubjectType(s)}
            className={`rounded-md px-3 py-1 text-xs font-medium ${
              subjectType === s
                ? 'bg-slate-900 text-white'
                : 'border border-slate-300 text-slate-600 hover:bg-slate-50'
            }`}
          >
            {s ?? 'All'}
          </button>
        ))}
      </div>

      <div className="mt-2 flex flex-wrap gap-2" data-testid="event-prefix-pills">
        {EVENT_PREFIXES.map((p) => (
          <button
            key={p.value ?? 'all'}
            onClick={() => setEventPrefix(p.value)}
            className={`rounded-md px-3 py-1 text-xs font-medium ${
              eventPrefix === p.value
                ? 'bg-slate-900 text-white'
                : 'border border-slate-300 text-slate-600 hover:bg-slate-50'
            }`}
          >
            {p.label}
          </button>
        ))}
      </div>

      {isError && (
        <p className="mt-4 rounded bg-red-50 p-3 text-sm text-red-700">
          Couldn&apos;t load activity log.
        </p>
      )}

      <div className="mt-4 bg-white rounded border border-slate-200">
        <table className="w-full text-sm">
          <thead>
            <tr className="border-b border-slate-200">
              <th className="text-left px-4 py-3 font-medium text-slate-500">When</th>
              <th className="text-left px-4 py-3 font-medium text-slate-500">Actor</th>
              <th className="text-left px-4 py-3 font-medium text-slate-500">Action</th>
              <th className="text-left px-4 py-3 font-medium text-slate-500">Subject</th>
              <th className="text-left px-4 py-3 font-medium text-slate-500">Justification</th>
            </tr>
          </thead>
          <tbody>
            {isLoading && (
              <tr><td colSpan={5} className="px-4 py-6 text-center text-sm text-slate-400">Loading…</td></tr>
            )}
            {!isLoading && rows.length === 0 && (
              <tr><td colSpan={5} className="px-4 py-6 text-center text-sm text-slate-400">No activity yet.</td></tr>
            )}
            {rows.map((row) => {
              const justification =
                typeof row.properties?.['justification'] === 'string'
                  ? (row.properties['justification'] as string)
                  : '';
              const truncated = justification.length > 80
                ? justification.slice(0, 77) + '…'
                : justification;
              const isOpen = openId === row.id;
              return (
                <>
                  <tr
                    key={row.id}
                    className="border-b border-slate-100 last:border-0 hover:bg-slate-50 cursor-pointer"
                    onClick={() => setOpenId(isOpen ? null : row.id)}
                  >
                    <td className="px-4 py-3 text-xs text-slate-500">
                      {new Date(row.created_at).toLocaleString()}
                    </td>
                    <td className="px-4 py-3 text-slate-700">{row.actor?.name ?? '—'}</td>
                    <td className="px-4 py-3 font-mono text-xs text-slate-700">{row.event}</td>
                    <td className="px-4 py-3 text-slate-500">
                      {row.subject.type ? `${row.subject.type} ${row.subject.id?.slice(0, 8) ?? ''}` : '—'}
                    </td>
                    <td className="px-4 py-3 text-slate-600">{truncated || '—'}</td>
                  </tr>
                  {isOpen && (
                    <tr key={`${row.id}-detail`} className="bg-slate-50">
                      <td colSpan={5} className="px-4 py-3 text-xs">
                        <pre className="overflow-auto whitespace-pre-wrap font-mono text-slate-700">
{JSON.stringify(row.properties, null, 2)}
                        </pre>
                      </td>
                    </tr>
                  )}
                </>
              );
            })}
          </tbody>
        </table>
      </div>
    </div>
  );
}
