'use client';

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

interface Props {
  reviewId: string;
  open: boolean;
  onClose: () => void;
  onReported?: () => void;
}

const REASONS: { value: ReportReason; label: string; description: string }[] = [
  {
    value: 'inappropriate',
    label: 'Inappropriate',
    description: 'Offensive, harassing, or otherwise inappropriate content.',
  },
  {
    value: 'spam',
    label: 'Spam',
    description: 'Promotional content, link-spam, or off-topic.',
  },
  {
    value: 'not_about_purchase',
    label: 'Not about this purchase',
    description: "Doesn't describe the item or transaction.",
  },
  {
    value: 'personal_info',
    label: 'Personal info',
    description: 'Discloses private contact information or PII.',
  },
  {
    value: 'other',
    label: 'Other',
    description: 'Tell us what’s wrong (required).',
  },
];

export function ReportReviewDialog({ reviewId, open, onClose, onReported }: Props) {
  const [reason, setReason] = useState<ReportReason | ''>('');
  const [reasonText, setReasonText] = useState('');
  const [error, setError] = useState<string | null>(null);
  const reportMut = useReportReview();

  useEscapeToClose(open, onClose);

  if (!open) return null;

  const isOther = reason === 'other';
  const reasonTextOk = !isOther || reasonText.trim().length >= 10;
  const submitDisabled = !reason || !reasonTextOk || reportMut.isPending;

  const handleClose = () => {
    setReason('');
    setReasonText('');
    setError(null);
    onClose();
  };

  const submit = async () => {
    setError(null);
    if (!reason || !reasonTextOk) return;
    try {
      const payload: { reason: ReportReason; reason_text?: string } = { reason };
      const trimmed = reasonText.trim();
      if (trimmed.length > 0) payload.reason_text = trimmed;
      await reportMut.mutateAsync({ reviewId, input: payload });
      onReported?.();
      handleClose();
    } catch (e) {
      setError((e as Error).message ?? 'Failed to submit report.');
    }
  };

  return (
    <div
      role="dialog"
      aria-modal="true"
      aria-label="Report this review"
      className="fixed inset-0 z-50 flex items-center justify-center bg-slate-900/50 p-4"
    >
      <div className="w-full max-w-md rounded-lg bg-white p-6 shadow-xl">
        <h2 className="text-lg font-semibold text-slate-900">Report this review</h2>
        <p className="mt-1 text-xs text-slate-500">
          Our moderation team will read the review and take action if needed.
        </p>

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

        {isOther && (
          <label className="mt-4 block">
            <span className="text-sm font-medium text-slate-700">
              Tell us more (≥ 10 chars)
            </span>
            <textarea
              aria-label="Additional details"
              value={reasonText}
              onChange={(e) => setReasonText(e.target.value)}
              rows={3}
              maxLength={1000}
              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={handleClose}
            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"
          >
            {reportMut.isPending ? 'Submitting…' : 'Submit report'}
          </button>
        </div>
      </div>
    </div>
  );
}
