'use client';

import { useState, useEffect, useRef } from 'react';
import { useAuth } from '@/contexts/AuthContext';
import AIWhispers from '@/components/AIWhispers';
import { toast } from 'sonner';

interface MobileAIBarProps {
    isOpen: boolean;
    onOpen: () => void;
    onClose: () => void;
    docId: string;
    onApply?: (text: string, type?: 'ai' | 'voice') => void;
    apiKey: string | null;
    autoAction?: 'summarize' | 'structure' | 'extract' | 'compare' | 'mask' | 'coach' | null;
    onAutoActionComplete?: () => void;
    isEditable?: boolean;
}

export default function MobileAIBar({
    isOpen,
    onOpen,
    onClose,
    docId,
    onApply,
    apiKey,
    autoAction,
    onAutoActionComplete,
    isEditable = false,
}: MobileAIBarProps) {
    const { user } = useAuth();
    const [isLoading, setIsLoading] = useState(false);
    const [result, setResult] = useState('');
    const [error, setError] = useState('');
    const bottomSheetRef = useRef<HTMLDivElement>(null);
    const [source, setSource] = useState<'ai' | 'voice'>('ai');

    // AI Action Logic (Reused from AISidepanel)
    const handleAIAction = async (promptType: 'summarize' | 'structure' | 'extract' | 'compare' | 'mask' | 'coach') => {
        if (!user) return;
        setIsLoading(true);
        setError('');
        setResult(''); // Clear previous result instantly for responsiveness
        setSource('ai');

        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) {
                // Streaming effect simulation (optional, can be improved later)
                setResult(data.text);
            } else {
                setError(data.error || 'AI 처리 중 오류가 발생했습니다.');
            }
        } catch (err) {
            console.error('AI Action Error:', err);
            setError('연결 오류가 발생했습니다.');
        } finally {
            setIsLoading(false);
        }
    };

    // Auto-execute from voice commands
    useEffect(() => {
        if (isOpen && autoAction && !isLoading) {
            handleAIAction(autoAction);
            onAutoActionComplete?.();
        }
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [isOpen, autoAction]);

    // [New] Clear previous result when re-opening
    useEffect(() => {
        if (isOpen) {
            setResult('');
            setError('');
            setSource('ai');
        }
    }, [isOpen]);

    // Close when clicking outside (backdrop)
    useEffect(() => {
        const handleClickOutside = (event: MouseEvent) => {
            if (isOpen && bottomSheetRef.current && !bottomSheetRef.current.contains(event.target as Node)) {
                onClose();
            }
        };
        document.addEventListener('mousedown', handleClickOutside);
        return () => document.removeEventListener('mousedown', handleClickOutside);
    }, [isOpen, onClose]);

    // [New] Refine Action
    const handleRefine = async () => {
        if (!user || !result) return;
        setIsLoading(true);
        setError('');

        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: 'refine',
                    text: result // Send current text for refinement
                })
            });

            const data = await response.json();
            if (response.ok) {
                setResult(data.text);
                setSource('ai'); // Mark as AI-generated/refined
            } else {
                setError(data.error || 'AI 다듬기 중 오류가 발생했습니다.');
            }
        } catch (err) {
            console.error('AI Refine Error:', err);
            setError('연결 오류가 발생했습니다.');
        } finally {
            setIsLoading(false);
        }
    };

    // ─── Render ───

    return (
        <>
            {/* 1. Mini Bar (Always Visible when closed) */}
            {!isOpen && (
                <div
                    onClick={onOpen}
                    className="fixed bottom-24 right-6 z-[90] flex items-center gap-2 px-4 py-3 bg-indigo-600 hover:bg-indigo-700 text-white rounded-full shadow-lg shadow-indigo-200 transition-transform active:scale-95 cursor-pointer md:hidden animate-in fade-in slide-in-from-bottom-4"
                >
                    <span className="text-xl">✨</span>
                    <span className="text-sm font-bold">AI 비서</span>
                </div>
            )}

            {/* 2. Backdrop (Overlay) */}
            {isOpen && (
                <div className="fixed inset-0 bg-black/40 backdrop-blur-sm z-[100] md:hidden animate-in fade-in duration-200" aria-hidden="true" />
            )}

            {/* 3. Bottom Sheet */}
            <div
                ref={bottomSheetRef}
                className={`fixed inset-x-0 bottom-0 z-[101] bg-white rounded-t-3xl shadow-[0_-10px_40px_-15px_rgba(0,0,0,0.2)] md:hidden transition-transform duration-300 ease-out flex flex-col max-h-[85dvh] ${isOpen ? 'translate-y-0' : 'translate-y-full'
                    }`}
            >
                {/* Handle Bar */}
                <div className="w-full flex justify-center pt-3 pb-1 cursor-grab active:cursor-grabbing" onClick={onClose}>
                    <div className="w-12 h-1.5 bg-gray-200 rounded-full" />
                </div>

                {/* Header */}
                <div className="px-6 py-3 border-b border-gray-50 flex items-center justify-between shrink-0">
                    <div className="flex items-center gap-2">
                        <span className="text-xl">✨</span>
                        <h3 className="text-lg font-bold text-gray-900">InsuWiki AI</h3>
                    </div>
                    {isLoading && (
                        <div className="text-xs font-medium text-indigo-600 animate-pulse">
                            Thinking...
                        </div>
                    )}
                </div>

                {/* AI Whispers (Voice Feedback) */}
                <div className="px-4 py-2 bg-indigo-50/50 flex flex-col gap-2 shrink-0">
                    {/* [Fix] Conditionally render to reset state on close */}
                    {isOpen && (
                        <AIWhispers
                            apiKey={apiKey}
                            onTranscription={(text) => {
                                // Only update if text is meaningful (final or long interim)
                                if (text) {
                                    setResult(text);
                                    setSource('voice');
                                }
                            }}
                        />
                    )}
                    {/* Voice Tips */}
                    <p className="text-[10px] text-indigo-400 px-1">
                        💡 "요약해줘", "정리해줘"라고 말하면 AI가 자동으로 실행됩니다.
                    </p>
                </div>

                {/* Content Area (Scrollable) */}
                <div className="flex-1 overflow-y-auto p-5 min-h-0 bg-white">
                    {isLoading ? (
                        <div className="space-y-3">
                            <div className="h-4 bg-gray-100 rounded w-3/4 animate-pulse" />
                            <div className="h-4 bg-gray-100 rounded w-1/2 animate-pulse" />
                            <div className="h-4 bg-gray-100 rounded w-5/6 animate-pulse" />
                        </div>
                    ) : result ? (
                        <div className="space-y-4">
                            <div className="prose prose-sm max-w-none text-gray-700 leading-relaxed bg-gray-50 p-4 rounded-2xl border border-gray-100">
                                {result.split('\n').map((line, i) => <p key={i}>{line}</p>)}
                            </div>
                        </div>
                    ) : error ? (
                        <div className="text-center py-8 text-red-500">
                            <p className="font-bold">⚠️ 오류 발생</p>
                            <p className="text-xs mt-1 opacity-80">{error}</p>
                        </div>
                    ) : (
                        <div className="grid grid-cols-2 gap-3">
                            <AIActionButton icon="📝" label="요약하기" onClick={() => handleAIAction('summarize')} />
                            <AIActionButton icon="ladder" emoji="🪜" label="구조화" onClick={() => handleAIAction('structure')} />
                            <AIActionButton icon="search" emoji="🔍" label="정보추출" onClick={() => handleAIAction('extract')} />
                            <AIActionButton icon="scale" emoji="⚖️" label="비교표" onClick={() => handleAIAction('compare')} />
                            <AIActionButton icon="shield" emoji="🛡️" label="마스킹" onClick={() => handleAIAction('mask')} />
                            <AIActionButton icon="target" emoji="🎯" label="코칭" onClick={() => handleAIAction('coach')} />
                        </div>
                    )}
                </div>

                {/* Fixed Footer Buttons */}
                {!isLoading && result && (
                    <div className="p-4 border-t border-gray-100 bg-white pb-[env(safe-area-inset-bottom,20px)] shrink-0 z-20">
                        <div className="flex gap-2">
                            {/* Refine Button */}
                            <button
                                onClick={handleRefine}
                                className="flex items-center justify-center p-3 bg-white border border-indigo-100 text-indigo-600 rounded-xl shadow-sm active:scale-95 transition-transform"
                                title="AI 다듬기"
                            >
                                <span className="text-lg">✨</span>
                            </button>
                            <button
                                onClick={() => { navigator.clipboard.writeText(result); toast.success('복사됨'); }}
                                className="flex-1 py-3 bg-white border border-gray-200 text-gray-600 rounded-xl text-sm font-bold shadow-sm active:scale-95 transition-transform"
                            >
                                복사
                            </button>
                            {onApply && (
                                <button
                                    onClick={() => onApply(result, source)}
                                    disabled={!isEditable && source === 'voice'}
                                    style={{ display: (!isEditable && source === 'voice') ? 'none' : 'block' }}
                                    className={`flex-1 py-3 rounded-xl text-sm font-bold shadow-md active:scale-95 transition-all ${!isEditable && source === 'voice'
                                        ? 'bg-gray-100 text-gray-400 cursor-not-allowed shadow-none'
                                        : 'bg-indigo-600 text-white shadow-indigo-200'
                                        }`}
                                >
                                    {source === 'voice' ? '본문 삽입' : '적용'}
                                </button>
                            )}
                        </div>
                    </div>
                )}
            </div>
        </>
    );
}

function AIActionButton({ icon, emoji, label, onClick }: { icon: string, emoji?: string, label: string, onClick: () => void }) {
    return (
        <button
            onClick={onClick}
            className="flex flex-col items-center justify-center p-4 bg-gray-50 hover:bg-gray-100 active:bg-gray-200 rounded-2xl border border-gray-100 transition-all"
        >
            <span className="text-2xl mb-1">{emoji || icon}</span>
            <span className="text-xs font-bold text-gray-600">{label}</span>
        </button>
    );
}
