'use client';

import { useState } from 'react';
import { toast } from 'sonner';
import { useAuth } from '@/contexts/AuthContext';

interface ErrorReportButtonProps {
  docId: string;
}

const REPORT_REASONS = [
  { value: 'factual_error', label: '사실 오류' },
  { value: 'outdated_info', label: '정보 outdated' },
  { value: 'missing_source', label: '출처 누락' },
  { value: 'inappropriate_content', label: '부적절한 내용' },
] as const;

type ReportReason = typeof REPORT_REASONS[number]['value'];

export default function ErrorReportButton({ docId }: ErrorReportButtonProps) {
  const { user } = useAuth();
  const [isOpen, setIsOpen] = useState(false);
  const [reason, setReason] = useState<ReportReason | ''>('');
  const [memo, setMemo] = useState('');
  const [isSubmitting, setIsSubmitting] = useState(false);

  const handleSubmit = async () => {
    if (!reason || !user) return;

    setIsSubmitting(true);
    try {
      const token = await user.getIdToken();
      const res = await fetch(`/api/wiki/entries/${docId}/error-report`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          Authorization: `Bearer ${token}`,
        },
        body: JSON.stringify({ reason, memo }),
      });

      if (!res.ok) throw new Error('신고 제출 실패');

      toast.success('오류 신고가 접수되었습니다.');
      setIsOpen(false);
      setReason('');
      setMemo('');
    } catch (e) {
      toast.error('신고 제출에 실패했습니다.');
    } finally {
      setIsSubmitting(false);
    }
  };

  return (
    <div className="border-t border-gray-200 mt-8 pt-0">
      <button
        onClick={() => setIsOpen(prev => !prev)}
        className="w-full flex items-center justify-between px-4 py-3 text-sm text-gray-500 hover:text-gray-700 hover:bg-gray-50 transition-colors rounded-lg"
      >
        <span className="flex items-center gap-2">
          <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M3 21V4m0 0l9-1 9 1v10l-9-1-9 1V4z" />
          </svg>
          이 정보에 오류가 있나요?
        </span>
        <svg className={`w-4 h-4 transition-transform ${isOpen ? 'rotate-180' : ''}`} fill="none" stroke="currentColor" viewBox="0 0 24 24">
          <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M19 9l-7 7-7-7" />
        </svg>
      </button>

      {isOpen && (
        <div className="px-4 pb-4 animate-in fade-in slide-in-from-top-2 duration-200">
          <div className="bg-white rounded-xl border border-gray-100 p-4 shadow-sm">
            <h4 className="text-sm font-bold text-gray-800 mb-3">오류 신고</h4>

            <div className="space-y-2 mb-3">
              {REPORT_REASONS.map(opt => (
                <label key={opt.value} className="flex items-center gap-2 cursor-pointer group">
                  <input
                    type="radio"
                    name="error-reason"
                    value={opt.value}
                    checked={reason === opt.value}
                    onChange={() => setReason(opt.value)}
                    className="text-red-500 focus:ring-red-400"
                  />
                  <span className="text-sm text-gray-700 group-hover:text-gray-900">{opt.label}</span>
                </label>
              ))}
            </div>

            <input
              type="text"
              value={memo}
              onChange={e => setMemo(e.target.value)}
              maxLength={200}
              placeholder="추가 설명 (선택)"
              className="w-full text-sm border border-gray-200 rounded-xl px-3 py-2 mb-3 focus:outline-none focus:ring-2 focus:ring-red-300 focus:border-red-300 placeholder-gray-400"
            />

            <button
              onClick={handleSubmit}
              disabled={!reason || isSubmitting}
              className="w-full py-2 text-sm font-bold text-white bg-red-500 hover:bg-red-600 disabled:opacity-50 disabled:cursor-not-allowed rounded-xl transition-colors"
            >
              {isSubmitting ? '제출 중...' : '신고하기'}
            </button>
          </div>
        </div>
      )}
    </div>
  );
}
