'use client';

import { useState, useEffect } from 'react';
import { useAuth } from '@/contexts/AuthContext';
import AIWhispers from '@/components/AIWhispers';
import ActionTooltip from '@/components/ActionTooltip';
import { toast } from 'sonner';

interface AISidepanelProps {
    isOpen: boolean;
    onClose: () => void;
    docId: string;
    onApply?: (text: string) => void;
    apiKey: string | null;
    /** 음성 명령에 의해 자동 실행할 프리셋 (설정 시 패널 오픈과 동시에 실행) */
    autoAction?: 'summarize' | 'structure' | 'extract' | 'compare' | 'mask' | 'coach' | null;
    /** autoAction 처리 후 리셋 콜백 */
    onAutoActionComplete?: () => void;
}

export default function AISidepanel({ isOpen, onClose, docId, onApply, apiKey, autoAction, onAutoActionComplete }: AISidepanelProps) {
    const { user } = useAuth();
    const [isLoading, setIsLoading] = useState(false);
    const [result, setResult] = useState('');
    const [error, setError] = useState('');

    const handleAIAction = async (promptType: 'summarize' | 'structure' | 'extract' | 'compare' | 'mask' | 'coach') => {
        if (!user) return;
        setIsLoading(true);
        setError('');
        setResult('');

        try {
            const token = await user.getIdToken();
            const response = await fetch('/api/ai/summarize', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'Authorization': `Bearer ${token}`
                },
                body: JSON.stringify({ docId, promptType })
            });

            const data = await response.json();
            if (response.ok) {
                setResult(data.text);
            } else {
                setError(data.error || 'AI 처리 중 오류가 발생했습니다.');
            }
        } catch (err) {
            console.error('AI Action Error:', err);
            setError('연결 오류가 발생했습니다. 잠시 후 다시 시도해주세요.');
        } finally {
            setIsLoading(false);
        }
    };

    // 음성 명령에 의한 자동 실행
    useEffect(() => {
        if (isOpen && autoAction && !isLoading) {
            handleAIAction(autoAction);
            onAutoActionComplete?.();
        }
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [isOpen, autoAction]);

    if (!isOpen) return null;

    return (
        <div className={`fixed inset-y-0 right-0 z-[100] w-full max-w-md bg-white shadow-2xl transform transition-transform duration-300 ease-in-out ${isOpen ? 'translate-x-0' : 'translate-x-full'} border-l border-gray-100 flex flex-col`}>
            {/* Header */}
            <div className="px-6 py-5 border-b border-gray-100 bg-slate-50 flex items-center justify-between">
                <div className="flex items-center gap-2">
                    <span className="text-xl">✨</span>
                    <h3 className="text-lg font-bold text-slate-900">AI 어시스턴트</h3>
                </div>
                <button onClick={onClose} className="p-2 hover:bg-white rounded-full transition-colors text-slate-400 hover:text-slate-600">
                    <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M6 18L18 6M6 6l12 12m0-12L6 18" />
                    </svg>
                </button>
            </div>

            {/* AI Whispers (Phase 2 Focus) */}
            <div className="p-4 border-b border-gray-50 bg-indigo-50/30">
                <AIWhispers
                    apiKey={apiKey}
                    onTranscription={(text) => {
                        // For real-time writing, we could call onApply directly
                        // but for now let's just show it in the component
                    }}
                />
            </div>

            {/* Action Buttons */}
            <div className="p-4 grid grid-cols-3 gap-2 border-b border-gray-50">
                <ActionTooltip label="요약하기" description="문서의 핵심 내용을 파악하여 간결하게 요약해줍니다.">
                    <button
                        onClick={() => handleAIAction('summarize')}
                        disabled={isLoading}
                        className="w-full flex flex-col items-center gap-1 p-3 rounded-2xl bg-indigo-50 text-indigo-700 hover:bg-indigo-100 transition-all active:scale-95 disabled:opacity-50"
                    >
                        <span className="text-xl">📝</span>
                        <span className="text-xs font-bold">요약하기</span>
                    </button>
                </ActionTooltip>
                <ActionTooltip label="구조화" description="마크다운 문법을 사용하여 문서의 가독성과 구조를 개선합니다.">
                    <button
                        onClick={() => handleAIAction('structure')}
                        disabled={isLoading}
                        className="w-full flex flex-col items-center gap-1 p-3 rounded-2xl bg-amber-50 text-amber-700 hover:bg-amber-100 transition-all active:scale-95 disabled:opacity-50"
                    >
                        <span className="text-xl">🪜</span>
                        <span className="text-xs font-bold">구조화</span>
                    </button>
                </ActionTooltip>
                <ActionTooltip label="정보추출" description="문서에서 날짜, 금액, 인물 등 중요 정보를 자동으로 추출합니다.">
                    <button
                        onClick={() => handleAIAction('extract')}
                        disabled={isLoading}
                        className="w-full flex flex-col items-center gap-1 p-3 rounded-2xl bg-emerald-50 text-emerald-700 hover:bg-emerald-100 transition-all active:scale-95 disabled:opacity-50"
                    >
                        <span className="text-xl">🔍</span>
                        <span className="text-xs font-bold">정보추출</span>
                    </button>
                </ActionTooltip>
                <ActionTooltip label="비교표" description="여러 데이터나 상품 정보를 비교분석하여 표 형태로 정리합니다.">
                    <button
                        onClick={() => handleAIAction('compare')}
                        disabled={isLoading}
                        className="w-full flex flex-col items-center gap-1 p-3 rounded-2xl bg-sky-50 text-sky-700 hover:bg-sky-100 transition-all active:scale-95 disabled:opacity-50"
                    >
                        <span className="text-xl">⚖️</span>
                        <span className="text-xs font-bold">비교표</span>
                    </button>
                </ActionTooltip>
                <ActionTooltip label="PII 마스킹" description="전화번호, 주민번호 등 민감한 개인정보를 식별하여 가려줍니다.">
                    <button
                        onClick={() => handleAIAction('mask')}
                        disabled={isLoading}
                        className="w-full flex flex-col items-center gap-1 p-3 rounded-2xl bg-rose-50 text-rose-700 hover:bg-rose-100 transition-all active:scale-95 disabled:opacity-50"
                    >
                        <span className="text-xl">🛡️</span>
                        <span className="text-xs font-bold">PII 마스킹</span>
                    </button>
                </ActionTooltip>
                <ActionTooltip label="코칭" description="상담 내용을 분석하여 더 나은 대화 방향과 개선점을 제안합니다.">
                    <button
                        onClick={() => handleAIAction('coach')}
                        disabled={isLoading}
                        className="w-full flex flex-col items-center gap-1 p-3 rounded-2xl bg-violet-50 text-violet-700 hover:bg-violet-100 transition-all active:scale-95 disabled:opacity-50"
                    >
                        <span className="text-xl">🎯</span>
                        <span className="text-xs font-bold">코칭</span>
                    </button>
                </ActionTooltip>
            </div>

            {/* Content Area */}
            <div className="flex-1 overflow-y-auto p-6 space-y-4">
                {isLoading ? (
                    <div className="py-20 text-center">
                        <div className="inline-block w-8 h-8 border-3 border-indigo-500 border-t-transparent rounded-full animate-spin"></div>
                        <p className="mt-4 text-sm text-slate-500 font-medium">Gemini가 생각 중입니다...</p>
                    </div>
                ) : result ? (
                    <div className="space-y-4 animate-in fade-in slide-in-from-bottom-2 duration-300">
                        <div className="prose prose-sm max-w-none text-slate-700 bg-slate-50 p-5 rounded-3xl border border-slate-100 leading-relaxed">
                            {result.split('\n').map((line, i) => (
                                <p key={i}>{line}</p>
                            ))}
                        </div>
                        <div className="flex gap-2">
                            <button
                                onClick={() => {
                                    navigator.clipboard.writeText(result);
                                    toast.success('클립보드에 복사되었습니다.');
                                }}
                                className="flex-1 py-3 bg-white border border-slate-200 text-slate-600 rounded-2xl text-sm font-bold hover:bg-slate-50 transition-all active:scale-95 flex items-center justify-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="M8 5H6a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2v-1M8 5a2 2 0 002 2h2a2 2 0 002-2M8 5a2 2 0 012-2h2a2 2 0 012 2m0 0h2a2 2 0 012 2v3m2 4H10m0 0l3-3m-3 3l3 3" /></svg>
                                복사하기
                            </button>
                            {onApply && (
                                <button
                                    onClick={() => onApply(result)}
                                    className="flex-1 py-3 bg-indigo-600 text-white rounded-2xl text-sm font-bold hover:bg-indigo-700 transition-all shadow-lg shadow-indigo-100 active:scale-95"
                                >
                                    문서에 적용
                                </button>
                            )}
                        </div>
                    </div>
                ) : error ? (
                    <div className="py-10 text-center bg-red-50 rounded-3xl border border-red-100 p-6">
                        <span className="text-3xl mb-4 block">⚠️</span>
                        <p className="text-sm text-red-600 font-bold mb-1">오류 발생</p>
                        <p className="text-xs text-red-500 mb-4">{error}</p>
                    </div>
                ) : (
                    <div className="py-20 text-center text-slate-400">
                        <div className="w-16 h-16 bg-slate-50 rounded-full flex items-center justify-center mx-auto mb-4">
                            <svg className="w-8 h-8 text-slate-200" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M13 10V3L4 14h7v7l9-11h-7z" />
                            </svg>
                        </div>
                        <p className="text-sm font-medium">위의 버튼을 눌러 작업을 시작하세요.</p>
                        <p className="text-xs mt-1">현재 문서의 내용을 기반으로 분석합니다.</p>
                    </div>
                )}
            </div>

            {/* Footer */}
            <div className="p-4 bg-slate-50 border-t border-gray-100">
                <p className="text-[10px] text-slate-400 text-center leading-relaxed">
                    Powered by Google Gemini 1.5 Pro (BYOK)<br />
                    AI는 실수를 할 수 있으므로 항상 원문을 확인하세요.
                </p>
            </div>
        </div>
    );
}
