'use client';

import { useState } from 'react';
import { usePathname, useRouter, useSearchParams } from 'next/navigation';
import {
  useAdminStoreReviews,
  useAdminHideReview,
  useAdminRestoreReview,
} from '@/lib/queries/use-review-reports';
import { ConfirmWithJustificationDialog } from '@/components/admin/confirm-with-justification-dialog';
import type { Review } from '@alqove/api-client';

type StateKey = 'visible' | 'hidden' | 'all';

const STATES: { key: StateKey; label: string }[] = [
  { key: 'all', label: 'All' },
  { key: 'visible', label: 'Visible' },
  { key: 'hidden', label: 'Hidden' },
];

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

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

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

interface Props {
  storeId: string;
}

type PendingAction =
  | { kind: 'hide'; review: Review }
  | { kind: 'restore'; review: Review };

export function AdminStoreReviewsTab({ storeId }: Props) {
  const router = useRouter();
  const pathname = usePathname();
  const searchParams = useSearchParams();

  const raw = searchParams.get('reviews_state') ?? 'all';
  const activeKey: StateKey = (STATE_KEYS as readonly string[]).includes(raw)
    ? (raw as StateKey)
    : 'all';
  const page = Math.max(1, Number(searchParams.get('reviews_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 setStateKey = (next: StateKey) => {
    writeParams((p) => {
      if (next === 'all') p.delete('reviews_state');
      else p.set('reviews_state', next);
      p.delete('reviews_page');
    });
  };

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

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

  const hideMut = useAdminHideReview();
  const restoreMut = useAdminRestoreReview();
  const [pending, setPending] = useState<PendingAction | null>(null);

  const closeDialog = () => setPending(null);

  const onConfirm = (justification: string) => {
    if (!pending) return;
    if (pending.kind === 'hide') {
      hideMut.mutate(
        { reviewId: pending.review.id, input: { reason: justification } },
        { onSuccess: closeDialog },
      );
    } else {
      restoreMut.mutate(
        { reviewId: pending.review.id, input: { reason: justification } },
        { onSuccess: closeDialog },
      );
    }
  };

  const dialogIsPending = hideMut.isPending || restoreMut.isPending;

  return (
    <div>
      <div className="flex gap-2">
        {STATES.map((s) => (
          <button
            key={s.key}
            type="button"
            onClick={() => setStateKey(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'
            }`}
            data-testid={`admin-store-reviews-pill-${s.key}`}
          >
            {s.label}
          </button>
        ))}
      </div>

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

      <div
        className="mt-4 overflow-hidden rounded border border-slate-200 bg-white"
        data-testid="admin-store-reviews-list"
      >
        <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">Reviewer</th>
              <th className="px-4 py-3 text-left font-medium text-slate-500">Rating</th>
              <th className="px-4 py-3 text-left font-medium text-slate-500">Review</th>
              <th className="px-4 py-3 text-left font-medium text-slate-500">State</th>
              <th className="px-4 py-3 text-left font-medium text-slate-500">Created</th>
              <th className="px-4 py-3 text-left font-medium text-slate-500" />
            </tr>
          </thead>
          <tbody>
            {isLoading && (
              <tr>
                <td colSpan={6} className="px-4 py-6 text-center text-sm text-slate-400">
                  Loading…
                </td>
              </tr>
            )}
            {!isLoading && rows.length === 0 && (
              <tr>
                <td colSpan={6} className="px-4 py-6 text-center text-sm text-slate-400">
                  No reviews.
                </td>
              </tr>
            )}
            {rows.map((r) => (
              <tr
                key={r.id}
                className="border-b border-slate-100 last:border-0 align-top"
                data-testid={`admin-store-review-row-${r.id}`}
              >
                <td className="px-4 py-3 font-mono text-xs text-slate-700">
                  {r.reviewer_user_id.slice(0, 8)}
                </td>
                <td className="px-4 py-3 text-slate-700">{r.rating}/5</td>
                <td className="px-4 py-3 text-slate-700">
                  {r.title && (
                    <div className="text-sm font-semibold text-slate-900">{r.title}</div>
                  )}
                  <p className="whitespace-pre-wrap text-xs text-slate-600 line-clamp-3">
                    {r.body}
                  </p>
                  {r.state === 'hidden' && r.hide_reason && (
                    <p className="mt-2 rounded bg-red-50 p-2 text-xs text-red-700">
                      <span className="font-medium">Hide reason:</span> {r.hide_reason}
                    </p>
                  )}
                </td>
                <td className="px-4 py-3">
                  {r.state === 'hidden' ? (
                    <span className="rounded bg-red-100 px-2 py-0.5 text-xs font-medium text-red-700">
                      Hidden
                    </span>
                  ) : (
                    <span className="rounded bg-forest-100 px-2 py-0.5 text-xs font-medium text-forest-800">
                      Visible
                    </span>
                  )}
                </td>
                <td className="px-4 py-3 text-xs text-slate-500">
                  {formatDate(r.created_at)}
                </td>
                <td className="px-4 py-3">
                  {r.state === 'visible' && (
                    <button
                      type="button"
                      onClick={() => setPending({ kind: 'hide', review: r })}
                      className="rounded-md border border-red-300 bg-red-50 px-3 py-1 text-xs text-red-700 hover:bg-red-100"
                      data-testid={`admin-store-review-hide-${r.id}`}
                    >
                      Hide
                    </button>
                  )}
                  {r.state === 'hidden' && (
                    <button
                      type="button"
                      onClick={() => setPending({ kind: 'restore', review: r })}
                      className="rounded-md border border-slate-300 px-3 py-1 text-xs text-slate-700 hover:bg-slate-50"
                      data-testid={`admin-store-review-restore-${r.id}`}
                    >
                      Restore
                    </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>
      )}

      <ConfirmWithJustificationDialog
        open={pending?.kind === 'hide'}
        title="Hide this review"
        description="The review will be hidden from the public store page. The buyer will see a hidden marker on their own reviews list with this reason."
        confirmLabel="Hide review"
        onConfirm={onConfirm}
        onCancel={closeDialog}
        isPending={dialogIsPending}
      />
      <ConfirmWithJustificationDialog
        open={pending?.kind === 'restore'}
        title="Restore this review"
        description="The review will become visible on the public store page again."
        confirmLabel="Restore review"
        onConfirm={onConfirm}
        onCancel={closeDialog}
        isPending={dialogIsPending}
      />
    </div>
  );
}
