'use client';

import { useState } from 'react';
import { usePathname, useRouter, useSearchParams } from 'next/navigation';
import { useAdminReviewReports } from '@/lib/queries/use-review-reports';
import { AdminResolveReviewDialog } from '@/components/admin/admin-resolve-review-dialog';
import type { ReportReason, ReviewReport } from '@alqove/api-client';

type StateKey = 'open' | 'resolved' | 'all';

const STATES: { key: StateKey; label: string }[] = [
  { key: 'open', label: 'Open' },
  { key: 'resolved', label: 'Resolved' },
  { key: 'all', label: 'All' },
];

const STATE_KEYS = STATES.map((s) => s.key);

const REASON_LABELS: Record<ReportReason, string> = {
  inappropriate: 'Inappropriate',
  spam: 'Spam',
  not_about_purchase: 'Not about purchase',
  personal_info: 'Personal info',
  other: 'Other',
};

const DATE_FORMATTER = new Intl.DateTimeFormat('en-US', {
  month: 'short',
  day: 'numeric',
  year: 'numeric',
  hour: 'numeric',
  minute: '2-digit',
  hour12: true,
  timeZone: 'UTC',
});

function formatDate(iso: string): string {
  const d = new Date(iso);
  if (Number.isNaN(d.getTime())) return '';
  return DATE_FORMATTER.format(d);
}

function truncate(s: string | null, n: number): string {
  if (!s) return '—';
  return s.length > n ? `${s.slice(0, n)}…` : s;
}

export function AdminReviewsClient() {
  const router = useRouter();
  const pathname = usePathname();
  const searchParams = useSearchParams();
  const raw = searchParams.get('state') ?? 'open';
  const activeKey: StateKey = (STATE_KEYS as readonly string[]).includes(raw)
    ? (raw as StateKey)
    : 'open';
  const page = Math.max(1, Number(searchParams.get('page') ?? '1'));

  const writeParams = (mut: (p: URLSearchParams) => void) => {
    const params = new URLSearchParams(searchParams.toString());
    mut(params);
    const qs = params.toString();
    router.replace(qs ? `${pathname}?${qs}` : pathname);
  };

  const setState = (next: StateKey) => {
    writeParams((p) => {
      if (next === 'open') p.delete('state');
      else p.set('state', next);
      p.delete('page');
    });
  };

  const setPage = (next: number) => {
    writeParams((p) => {
      if (next <= 1) p.delete('page');
      else p.set('page', String(next));
    });
  };

  const { data, isLoading, isError } = useAdminReviewReports({ state: activeKey, page });
  const rows = data?.data ?? [];
  const meta = data?.meta;

  const [reviewing, setReviewing] = useState<ReviewReport | null>(null);

  return (
    <div>
      <h1 className="text-2xl font-bold text-slate-900">Reviews</h1>
      <p className="mt-1 text-sm text-slate-500">
        Reported reviews awaiting moderation.
      </p>

      <div className="mt-4 flex gap-2">
        {STATES.map((s) => (
          <button
            key={s.key}
            type="button"
            onClick={() => setState(s.key)}
            className={`rounded-md px-3 py-1 text-xs font-medium ${
              activeKey === s.key
                ? 'bg-slate-900 text-white'
                : 'border border-slate-300 text-slate-600 hover:bg-slate-50'
            }`}
          >
            {s.label}
          </button>
        ))}
      </div>

      {isError && (
        <p className="mt-4 rounded bg-red-50 p-3 text-sm text-red-700">
          Couldn&apos;t load reports. You may need admin access.
        </p>
      )}

      <div className="mt-4 overflow-hidden rounded border border-slate-200 bg-white">
        <table className="w-full text-sm">
          <thead>
            <tr className="border-b border-slate-200">
              <th className="px-4 py-3 text-left font-medium text-slate-500">Report</th>
              <th className="px-4 py-3 text-left font-medium text-slate-500">Store</th>
              <th className="px-4 py-3 text-left font-medium text-slate-500">Reviewer</th>
              <th className="px-4 py-3 text-left font-medium text-slate-500">Reason</th>
              <th className="px-4 py-3 text-left font-medium text-slate-500">Reporter</th>
              <th className="px-4 py-3 text-left font-medium text-slate-500">Reported</th>
              <th className="px-4 py-3 text-left font-medium text-slate-500" />
            </tr>
          </thead>
          <tbody>
            {isLoading && (
              <tr>
                <td colSpan={7} className="px-4 py-6 text-center text-sm text-slate-400">
                  Loading…
                </td>
              </tr>
            )}
            {!isLoading && rows.length === 0 && (
              <tr>
                <td colSpan={7} className="px-4 py-6 text-center text-sm text-slate-400">
                  No reports.
                </td>
              </tr>
            )}
            {rows.map((r) => (
              <tr
                key={r.id}
                className="border-b border-slate-100 last:border-0 hover:bg-slate-50"
              >
                <td className="px-4 py-3 font-mono text-xs text-slate-700">
                  {r.id.slice(0, 8)}
                </td>
                <td className="px-4 py-3 text-slate-700">{r.review.store_name}</td>
                <td className="px-4 py-3 text-slate-700">
                  {r.review.reviewer_name}
                  <span className="ml-2 text-xs text-slate-400">{r.review.rating}/5</span>
                </td>
                <td className="px-4 py-3 text-slate-600">
                  <div className="text-xs font-medium text-slate-700">
                    {REASON_LABELS[r.reason]}
                  </div>
                  {r.reason_text && (
                    <div
                      className="text-xs text-slate-500 line-clamp-2"
                      title={r.reason_text}
                    >
                      {truncate(r.reason_text, 80)}
                    </div>
                  )}
                </td>
                <td className="px-4 py-3 text-slate-700">{r.reporter.name}</td>
                <td className="px-4 py-3 text-xs text-slate-500">
                  {formatDate(r.created_at)}
                </td>
                <td className="px-4 py-3">
                  <button
                    type="button"
                    onClick={() => setReviewing(r)}
                    className="rounded-md border border-slate-300 px-3 py-1 text-xs text-slate-700 hover:bg-slate-50"
                    data-testid={`admin-review-report-review-${r.id}`}
                  >
                    Review
                  </button>
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>

      {meta && meta.last_page > 1 && (
        <div className="mt-4 flex items-center justify-between text-xs text-slate-600">
          <span>
            Page {meta.current_page} of {meta.last_page} · {meta.total} total
          </span>
          <div className="flex gap-2">
            <button
              type="button"
              onClick={() => setPage(page - 1)}
              disabled={page <= 1}
              className="rounded border border-slate-300 px-3 py-1 disabled:cursor-not-allowed disabled:opacity-50 hover:bg-slate-50"
            >
              Previous
            </button>
            <button
              type="button"
              onClick={() => setPage(page + 1)}
              disabled={page >= meta.last_page}
              className="rounded border border-slate-300 px-3 py-1 disabled:cursor-not-allowed disabled:opacity-50 hover:bg-slate-50"
            >
              Next
            </button>
          </div>
        </div>
      )}

      {reviewing && (
        <AdminResolveReviewDialog
          report={reviewing}
          open
          onClose={() => setReviewing(null)}
        />
      )}
    </div>
  );
}
