'use client';
/**
 * RejectModal — 打回原因模态框（必填校验）
 * 飞轮最强信号：组长打回必填原因，下次自动注入 prompt
 */
import { useState } from 'react';

interface RejectModalProps {
  taskId: number;
  onConfirm: (reason: string) => Promise<void>;
  onClose: () => void;
}

export function RejectModal({ taskId, onConfirm, onClose }: RejectModalProps) {
  const [reason, setReason] = useState('');
  const [submitting, setSubmitting] = useState(false);
  const [error, setError] = useState('');

  async function handleSubmit(e: React.FormEvent) {
    e.preventDefault();
    if (!reason.trim()) {
      setError('打回原因必填，下次 AI 生成时会自动注入此原因避免同类问题');
      return;
    }
    setSubmitting(true);
    try {
      await onConfirm(reason.trim());
      onClose();
    } finally {
      setSubmitting(false);
    }
  }

  return (
    <div
      className="fixed inset-0 z-50 flex items-center justify-center bg-black/40"
      role="dialog"
      aria-modal="true"
      aria-labelledby="reject-modal-title"
    >
      <div className="bg-surface-primary rounded-2xl shadow-xl w-full max-w-md mx-4 p-6">
        <h2 id="reject-modal-title" className="text-base font-bold text-text-primary mb-1">
          打回原因
        </h2>
        <p className="text-xs text-text-secondary mb-4">
          必填。原因会在下次生成时自动注入 AI 提示词，减少同类问题。
        </p>

        <form onSubmit={handleSubmit} noValidate>
          <textarea
            value={reason}
            onChange={(e) => { setReason(e.target.value); setError(''); }}
            placeholder="如：标题太硬广，不像素人分享"
            rows={4}
            aria-required="true"
            aria-label="打回原因（必填）"
            autoFocus
            className="w-full border border-border-default rounded-xl px-3 py-2 text-sm resize-none
                       focus:outline-none focus:border-brand-orange"
          />
          {error && (
            <p role="alert" className="text-status-error text-xs mt-1">{error}</p>
          )}

          <div className="flex gap-3 mt-4 justify-end">
            <button type="button" onClick={onClose}
              className="px-4 py-2 text-sm text-text-secondary border border-border-default rounded-lg hover:bg-surface-tertiary">
              取消
            </button>
            <button type="submit" disabled={submitting}
              aria-label="确认打回"
              className="px-4 py-2 text-sm bg-status-error text-white rounded-lg hover:bg-red-600 disabled:opacity-50">
              {submitting ? '提交中…' : '确认打回'}
            </button>
          </div>
        </form>
      </div>
    </div>
  );
}
