'use client';

import { useState } from 'react';
import { toast } from 'sonner';
import { useAuth } from '@/contexts/AuthContext';
import type { ReviewDecision, EvidenceType, SourceAttachment } from '@/types/firestore';

interface ReviewActionsProps {
    docId: string;
    onActionComplete?: () => void;
}

type ActiveDecision = ReviewDecision | null;

const EVIDENCE_TYPE_OPTIONS: { value: EvidenceType; label: string }[] = [
    { value: 'policy_clause', label: '약관 조항' },
    { value: 'regulation', label: '법령/규정' },
    { value: 'expert_opinion', label: '전문가 의견' },
    { value: 'court_ruling', label: '판례' },
    { value: 'other', label: '기타' },
];

const DECISION_CONFIG: Record<ReviewDecision, { label: string; className: string; activeClassName: string; requireComment: boolean }> = {
    approve: {
        label: '승인',
        className: 'border-green-200 text-green-700 hover:bg-green-50',
        activeClassName: 'bg-green-600 text-white border-green-600',
        requireComment: false,
    },
    request_revision: {
        label: '수정요청',
        className: 'border-orange-200 text-orange-700 hover:bg-orange-50',
        activeClassName: 'bg-orange-500 text-white border-orange-500',
        requireComment: true,
    },
    reject: {
        label: '거절',
        className: 'border-red-200 text-red-700 hover:bg-red-50',
        activeClassName: 'bg-red-600 text-white border-red-600',
        requireComment: true,
    },
};

export default function ReviewActions({ docId, onActionComplete }: ReviewActionsProps) {
    const { user } = useAuth();
    const [activeDecision, setActiveDecision] = useState<ActiveDecision>(null);
    const [comment, setComment] = useState('');
    const [evidenceType, setEvidenceType] = useState<EvidenceType | ''>('');
    const [sourceAttachments, setSourceAttachments] = useState<SourceAttachment[]>([]);
    const [isSubmitting, setIsSubmitting] = useState(false);

    const handleDecisionClick = (decision: ReviewDecision) => {
        if (activeDecision === decision) {
            setActiveDecision(null);
        } else {
            setActiveDecision(decision);
            setComment('');
            setEvidenceType('');
            setSourceAttachments([]);
        }
    };

    const handleAddAttachment = () => {
        setSourceAttachments((prev) => [...prev, { url: '', label: '' }]);
    };

    const handleAttachmentChange = (index: number, field: 'url' | 'label', value: string) => {
        setSourceAttachments((prev) => {
            const next = [...prev];
            next[index] = { ...next[index], [field]: value };
            return next;
        });
    };

    const handleRemoveAttachment = (index: number) => {
        setSourceAttachments((prev) => prev.filter((_, i) => i !== index));
    };

    const handleSubmit = async () => {
        if (!activeDecision) return;

        const config = DECISION_CONFIG[activeDecision];
        if (config.requireComment && !comment.trim()) {
            toast.error('코멘트를 입력해주세요.');
            return;
        }

        setIsSubmitting(true);
        try {
            const token = await user?.getIdToken();
            const body: Record<string, unknown> = {
                decision: activeDecision,
                comment: comment.trim(),
            };
            if (evidenceType) body.evidenceType = evidenceType;
            const validAttachments = sourceAttachments.filter((a) => a.url.trim());
            if (validAttachments.length > 0) body.sourceAttachments = validAttachments;

            const res = await fetch(`/api/wiki/entries/${docId}/review`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    ...(token ? { Authorization: `Bearer ${token}` } : {}),
                },
                body: JSON.stringify(body),
            });

            if (!res.ok) {
                const errData = await res.json().catch(() => ({}));
                throw new Error((errData as { message?: string }).message || '검토 제출에 실패했습니다.');
            }

            const decisionLabel = DECISION_CONFIG[activeDecision].label;
            toast.success(`검토가 제출되었습니다: ${decisionLabel}`);
            setActiveDecision(null);
            setComment('');
            setEvidenceType('');
            setSourceAttachments([]);
            onActionComplete?.();
        } catch (err) {
            const message = err instanceof Error ? err.message : '검토 제출에 실패했습니다.';
            toast.error(message);
        } finally {
            setIsSubmitting(false);
        }
    };

    return (
        <div className="space-y-4">
            {/* 버튼 그룹 */}
            <div className="flex items-center gap-2">
                {(Object.entries(DECISION_CONFIG) as [ReviewDecision, typeof DECISION_CONFIG[ReviewDecision]][]).map(([decision, config]) => (
                    <button
                        key={decision}
                        onClick={() => handleDecisionClick(decision)}
                        className={`flex-1 py-2 px-3 rounded-xl text-sm font-bold border transition-all ${
                            activeDecision === decision ? config.activeClassName : config.className
                        }`}
                    >
                        {config.label}
                    </button>
                ))}
            </div>

            {/* 확장 폼 */}
            {activeDecision && (
                <div className="bg-gray-50 rounded-2xl p-4 space-y-3 border border-gray-100">
                    {/* 코멘트 */}
                    <div>
                        <label className="block text-xs font-bold text-gray-600 mb-1.5">
                            코멘트{DECISION_CONFIG[activeDecision].requireComment && <span className="text-red-500 ml-0.5">*</span>}
                        </label>
                        <textarea
                            value={comment}
                            onChange={(e) => setComment(e.target.value)}
                            rows={3}
                            placeholder="검토 의견을 입력하세요..."
                            className="w-full px-3 py-2 bg-white border border-gray-200 rounded-xl text-sm text-gray-800 placeholder-gray-400 resize-none focus:outline-none focus:ring-2 focus:ring-indigo-300 focus:border-transparent transition-all"
                        />
                    </div>

                    {/* 근거 유형 */}
                    <div>
                        <label className="block text-xs font-bold text-gray-600 mb-1.5">근거 유형 (선택)</label>
                        <select
                            value={evidenceType}
                            onChange={(e) => setEvidenceType(e.target.value as EvidenceType | '')}
                            className="w-full px-3 py-2 bg-white border border-gray-200 rounded-xl text-sm text-gray-800 focus:outline-none focus:ring-2 focus:ring-indigo-300 focus:border-transparent transition-all"
                        >
                            <option value="">선택 안함</option>
                            {EVIDENCE_TYPE_OPTIONS.map((opt) => (
                                <option key={opt.value} value={opt.value}>
                                    {opt.label}
                                </option>
                            ))}
                        </select>
                    </div>

                    {/* 출처 첨부 */}
                    <div>
                        <div className="flex items-center justify-between mb-1.5">
                            <label className="text-xs font-bold text-gray-600">출처 첨부 (선택)</label>
                            <button
                                type="button"
                                onClick={handleAddAttachment}
                                className="text-xs text-indigo-600 hover:text-indigo-800 font-bold transition-colors"
                            >
                                + 추가
                            </button>
                        </div>
                        {sourceAttachments.length > 0 && (
                            <div className="space-y-2">
                                {sourceAttachments.map((attachment, index) => (
                                    <div key={index} className="flex items-center gap-2">
                                        <input
                                            type="url"
                                            value={attachment.url}
                                            onChange={(e) => handleAttachmentChange(index, 'url', e.target.value)}
                                            placeholder="URL"
                                            className="flex-1 px-3 py-1.5 bg-white border border-gray-200 rounded-xl text-xs text-gray-800 placeholder-gray-400 focus:outline-none focus:ring-2 focus:ring-indigo-300 focus:border-transparent transition-all"
                                        />
                                        <input
                                            type="text"
                                            value={attachment.label}
                                            onChange={(e) => handleAttachmentChange(index, 'label', e.target.value)}
                                            placeholder="라벨"
                                            className="w-24 px-3 py-1.5 bg-white border border-gray-200 rounded-xl text-xs text-gray-800 placeholder-gray-400 focus:outline-none focus:ring-2 focus:ring-indigo-300 focus:border-transparent transition-all"
                                        />
                                        <button
                                            type="button"
                                            onClick={() => handleRemoveAttachment(index)}
                                            className="p-1.5 text-gray-400 hover:text-red-500 transition-colors"
                                            aria-label="삭제"
                                        >
                                            <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M6 18L18 6M6 6l12 12" />
                                            </svg>
                                        </button>
                                    </div>
                                ))}
                            </div>
                        )}
                    </div>

                    {/* 제출/취소 */}
                    <div className="flex items-center gap-2 pt-1">
                        <button
                            onClick={handleSubmit}
                            disabled={isSubmitting}
                            className="flex-1 py-2 px-4 bg-indigo-600 hover:bg-indigo-700 disabled:opacity-50 disabled:cursor-not-allowed text-white text-sm font-bold rounded-xl transition-colors"
                        >
                            {isSubmitting ? '제출 중...' : '제출'}
                        </button>
                        <button
                            onClick={() => setActiveDecision(null)}
                            disabled={isSubmitting}
                            className="py-2 px-4 bg-white text-gray-600 hover:text-gray-800 border border-gray-200 text-sm font-bold rounded-xl transition-colors"
                        >
                            취소
                        </button>
                    </div>
                </div>
            )}
        </div>
    );
}
