'use client';

import { useState } from 'react';
import { useAdminResolveReviewReport } from '@/lib/queries/use-review-reports';
import { useEscapeToClose } from '@/lib/hooks/use-escape-to-close';
import type { ReportReason, ReviewAdminAction, ReviewReport } from '@alqove/api-client';

interface Props {
  report: ReviewReport;
  open: boolean;
  onClose: () => void;
  onResolved?: () => void;
}

const ACTIONS: { value: ReviewAdminAction; label: string; description: string }[] = [
  {
    value: 'keep',
    label: 'Keep — leave the review visible',
    description: 'The report is dismissed; the review stays on the store page.',
  },
  {
    value: 'hide',
    label: 'Hide — remove the review from public view',
    description: 'The buyer is informed and the review is hidden from the store page.',
  },
];

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

export function AdminResolveReviewDialog({ report, open, onClose, onResolved }: Props) {
  const [action, setAction] = useState<ReviewAdminAction | ''>('');
  const [note, setNote] = useState('');
  const [error, setError] = useState<string | null>(null);
  const resolve = useAdminResolveReviewReport();

  useEscapeToClose(open, onClose);

  if (!open) return null;

  const noteOk = note.trim().length >= 10;
  const submitDisabled = !action || !noteOk || resolve.isPending;

  const submit = async () => {
    setError(null);
    if (!action || !noteOk) return;
    try {
      await resolve.mutateAsync({
        reportId: report.id,
        input: { action, resolution_note: note.trim() },
      });
      onResolved?.();
      onClose();
      setAction('');
      setNote('');
    } catch (e) {
      setError((e as Error).message ?? 'Failed to resolve report.');
    }
  };

  return (
    <div
      role="dialog"
      aria-modal="true"
      aria-label="Resolve review report"
      className="fixed inset-0 z-50 flex items-center justify-center bg-slate-900/50 p-4"
    >
      <div className="w-full max-w-2xl rounded-lg bg-white p-6 shadow-xl">
        <h2 className="text-lg font-semibold text-slate-900">Resolve review report</h2>
        <p className="mt-1 text-xs text-slate-500">
          Report {report.id.slice(0, 8)} · store{' '}
          <span className="font-medium text-slate-700">{report.review.store_name}</span>
        </p>

        <section className="mt-4 rounded-md bg-slate-50 p-3 text-sm">
          <div className="flex items-baseline justify-between">
            <div>
              <span className="text-xs font-medium text-slate-500">Reviewer</span>{' '}
              <span className="font-medium text-slate-900">{report.review.reviewer_name}</span>
              <span className="ml-2 text-xs text-slate-500">
                Rating {report.review.rating}/5
              </span>
            </div>
            <span className="text-xs text-slate-500">
              {new Date(report.review.created_at).toLocaleDateString()}
            </span>
          </div>
          {report.review.title && (
            <p className="mt-2 text-sm font-semibold text-slate-900">{report.review.title}</p>
          )}
          <p className="mt-1 whitespace-pre-wrap text-sm text-slate-700">
            {report.review.body}
          </p>
        </section>

        <section className="mt-3 rounded-md bg-amber-50 p-3 text-sm text-amber-900">
          <div className="text-xs font-medium text-amber-800">
            Reported by {report.reporter.name}
          </div>
          <div className="mt-1">
            <span className="font-medium">Reason:</span> {REASON_LABELS[report.reason]}
          </div>
          {report.reason_text && (
            <p className="mt-1 whitespace-pre-wrap">{report.reason_text}</p>
          )}
        </section>

        <fieldset className="mt-4">
          <legend className="text-sm font-medium text-slate-700">Action</legend>
          <div className="mt-2 space-y-2">
            {ACTIONS.map((a) => (
              <label key={a.value} className="flex items-start gap-2 text-sm text-slate-800">
                <input
                  type="radio"
                  name="resolve-action"
                  value={a.value}
                  checked={action === a.value}
                  onChange={() => setAction(a.value)}
                  className="mt-1"
                />
                <span>
                  <span className="font-medium text-slate-900">{a.label}</span>
                  <span className="block text-xs text-slate-500">{a.description}</span>
                </span>
              </label>
            ))}
          </div>
        </fieldset>

        <label className="mt-4 block">
          <span className="text-sm font-medium text-slate-700">
            Resolution notes (≥ 10 chars)
          </span>
          <textarea
            aria-label="Resolution notes"
            value={note}
            onChange={(e) => setNote(e.target.value)}
            rows={3}
            maxLength={2000}
            className="mt-1 block w-full rounded-md border border-slate-300 p-2 text-sm"
          />
        </label>

        {error && <p className="mt-2 text-sm text-red-600">{error}</p>}

        <div className="mt-4 flex justify-end gap-2">
          <button
            type="button"
            onClick={onClose}
            className="rounded-md border border-slate-300 px-4 py-2 text-sm text-slate-700 hover:bg-slate-50"
          >
            Cancel
          </button>
          <button
            type="button"
            onClick={submit}
            disabled={submitDisabled}
            className="rounded-md bg-slate-900 px-4 py-2 text-sm font-medium text-white hover:bg-slate-800 disabled:cursor-not-allowed disabled:opacity-60"
          >
            {resolve.isPending ? 'Resolving…' : 'Resolve'}
          </button>
        </div>
      </div>
    </div>
  );
}
