'use client';

import { useState, useEffect } from 'react';
import { doc, updateDoc, serverTimestamp } from 'firebase/firestore';
import { db } from '@/lib/firebase';
import { useAuth } from '@/contexts/AuthContext';
import { COLLECTIONS } from '@/types/firestore';
import { toast } from 'sonner';
import { confirmDialog } from '@/lib/confirm';

interface AISettingsModalProps {
    isOpen: boolean;
    onClose: () => void;
    initialApiKey?: string;
}

export default function AISettingsModal({ isOpen, onClose, initialApiKey }: AISettingsModalProps) {
    const { user } = useAuth();
    const [apiKey, setApiKey] = useState(initialApiKey || '');
    const [isSaving, setIsSaving] = useState(false);
    const [showKey, setShowKey] = useState(false);

    // New states
    const [pingStatus, setPingStatus] = useState<'loading' | 'ok' | 'error' | null>(null);
    const [availableModels, setAvailableModels] = useState<string[]>([]);
    const [selectedModel, setSelectedModel] = useState<string>('');
    const [isKeyEditing, setIsKeyEditing] = useState(false);
    const [hasKey, setHasKey] = useState(false);

    useEffect(() => {
        if (!isOpen || !user) return;

        const fetchSettings = async () => {
            setPingStatus('loading');
            try {
                const token = await user.getIdToken();
                const res = await fetch('/api/ai/settings', {
                    headers: { 'Authorization': `Bearer ${token}` }
                });
                if (res.ok) {
                    const data = await res.json();
                    setHasKey(data.hasKey);
                    if (data.hasKey) {
                        setApiKey('****************'); // Masked key
                        setIsKeyEditing(false);
                    } else {
                        setApiKey('');
                        setIsKeyEditing(true);
                    }

                    if (data.status === 'ok') {
                        setPingStatus('ok');
                        setAvailableModels(data.availableModels || []);
                        setSelectedModel(data.selectedModel || 'models/gemini-1.5-pro');
                    } else if (data.status === 'error') {
                        setPingStatus('error');
                    } else {
                        setPingStatus(null);
                    }
                }
            } catch (err) {
                console.error("Failed to fetch settings", err);
                setPingStatus('error');
            }
        };
        fetchSettings();
    }, [isOpen, user]);

    const handleSave = async () => {
        if (!user) return;

        if (apiKey === '') {
            const confirmDelete = await confirmDialog('API 키가 비어있습니다. 등록된 키를 완전히 삭제하시겠습니까?');
            if (!confirmDelete) return;
        }

        setIsSaving(true);
        try {
            const token = await user.getIdToken();
            const response = await fetch('/api/ai/settings', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'Authorization': `Bearer ${token}`
                },
                body: JSON.stringify({ geminiApiKey: apiKey, selectedModel })
            });

            if (response.ok) {
                toast.success('AI 설정이 저장되었습니다.');
                onClose();
            } else {
                const data = await response.json();
                toast.error(`저장 실패: ${data.error}`);
            }
        } catch (error) {
            console.error('Error saving AI settings:', error);
            toast.error('설정 저장 중 오류가 발생했습니다.');
        } finally {
            setIsSaving(false);
        }
    };

    if (!isOpen) return null;

    return (
        <div className="fixed inset-0 z-[120] flex items-center justify-center px-4">
            <div className="absolute inset-0 bg-slate-900/60 backdrop-blur-sm" onClick={onClose} />

            <div className="relative w-full max-w-md sm:max-w-sm min-w-[320px] max-h-[90dvh] bg-white rounded-3xl shadow-2xl overflow-y-auto animate-in fade-in zoom-in-95 duration-200">
                <div className="px-6 py-5 border-b border-gray-100 bg-slate-50 flex items-center justify-between">
                    <h3 className="text-xl font-bold text-slate-900">AI 설정 (BYOK)</h3>
                    <button onClick={onClose} className="p-2 hover:bg-white rounded-full transition-colors text-slate-400">
                        <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 6l18 18" />
                        </svg>
                    </button>
                </div>

                <div className="p-6 space-y-4">
                    <div className="bg-amber-50 border border-amber-100 p-4 rounded-2xl">
                        <p className="text-xs text-amber-800 leading-relaxed">
                            💡 <b>인슈위키는 사용자의 개인 API 키를 사용합니다.</b><br />
                            Google AI Studio에서 발급받은 Gemini API 키를 입력해주세요. 키는 암호화되어 안전하게 보관됩니다.
                            기본 키를 삭제하려면 텍스트를 입력하지 않고 저장하세요.
                        </p>
                    </div>

                    {/* 상태 뱃지 */}
                    {hasKey && (
                        <div className={`p-4 rounded-2xl flex items-start gap-3 border ${pingStatus === 'ok' ? 'bg-emerald-50 border-emerald-100 text-emerald-800' : pingStatus === 'error' ? 'bg-red-50 border-red-100 text-red-800' : 'bg-slate-50 border-slate-100 text-slate-600'}`}>
                            {pingStatus === 'ok' ? (
                                <div className="text-xl">🟢</div>
                            ) : pingStatus === 'error' ? (
                                <div className="text-xl">🔴</div>
                            ) : (
                                <div className="text-xl animate-pulse">⏳</div>
                            )}
                            <div className="flex-1 min-w-0">
                                <h4 className="font-bold text-sm mb-1">
                                    {pingStatus === 'ok' ? '연동 원활' : pingStatus === 'error' ? '연결 실패' : '연결 상태 확인 중...'}
                                </h4>
                                {pingStatus === 'ok' ? (
                                    <div className="flex flex-col gap-2 mt-2">
                                        <label className="text-xs font-medium opacity-80">사용 모델 선택</label>
                                        <select
                                            value={selectedModel}
                                            onChange={(e) => setSelectedModel(e.target.value)}
                                            className="w-full text-sm bg-white/50 border border-emerald-200/50 rounded-lg px-2 py-1.5 outline-none focus:ring-2 focus:ring-emerald-500/20 text-emerald-900"
                                        >
                                            {availableModels.map(model => (
                                                <option key={model} value={model}>{model}</option>
                                            ))}
                                            {availableModels.length === 0 && <option value={selectedModel}>{selectedModel}</option>}
                                        </select>
                                    </div>
                                ) : pingStatus === 'error' ? (
                                    <p className="text-xs opacity-80">유효하지 않은 키입니다. 다시 확인해주세요.</p>
                                ) : null}
                            </div>
                        </div>
                    )}

                    <div>
                        <div className="flex items-center justify-between mb-2">
                            <label className="block text-sm font-bold text-slate-700">Gemini API Key</label>
                            {hasKey && !isKeyEditing && (
                                <button
                                    onClick={() => {
                                        setIsKeyEditing(true);
                                        setApiKey('');
                                    }}
                                    className="text-xs font-semibold text-indigo-600 hover:text-indigo-700 bg-indigo-50 hover:bg-indigo-100 px-2 py-1 rounded-md transition-colors"
                                >
                                    키 수정
                                </button>
                            )}
                        </div>
                        <div className="relative">
                            <input
                                type={showKey ? "text" : "password"}
                                value={apiKey}
                                onChange={(e) => setApiKey(e.target.value)}
                                placeholder="AI... (발급받은 키를 입력하세요)"
                                disabled={!isKeyEditing && hasKey}
                                className={`w-full px-4 py-3 border rounded-2xl focus:ring-2 focus:border-transparent outline-none transition-all pr-12 font-mono text-sm ${(!isKeyEditing && hasKey) ? 'bg-slate-100 border-slate-200 text-slate-500 cursor-not-allowed' : 'bg-slate-50 border-slate-200 focus:ring-amber-500'}`}
                            />
                            {(!hasKey || isKeyEditing) && (
                                <button
                                    onClick={() => setShowKey(!showKey)}
                                    className="absolute right-3 top-1/2 -translate-y-1/2 p-1.5 text-slate-400 hover:text-slate-600 transition-colors"
                                >
                                    {showKey ? (
                                        <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M13.875 18.825A10.05 10.05 0 0112 19c-4.478 0-8.268-2.943-9.543-7a9.97 9.97 0 011.563-3.029m5.858.908a3 3 0 114.243 4.243M9.878 9.878l4.242 4.242M9.888 9.888L4.223 4.223" /></svg>
                                    ) : (
                                        <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z" /><path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z" /></svg>
                                    )}
                                </button>
                            )}
                        </div>
                    </div>

                    <a
                        href="https://aistudio.google.com/app/apikey"
                        target="_blank"
                        rel="noopener noreferrer"
                        className="text-xs text-indigo-600 hover:underline font-medium flex items-center gap-1"
                    >
                        키 발급받으러 가기 (Google AI Studio)
                        <svg className="w-3 h-3" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M10 6H6a2 2 0 00-2 2v10a2 2 0 002 2h10a2 2 0 002-2v-4M14 4h6m0 0v6m0-6L10 14" /></svg>
                    </a>
                </div>

                <div className="p-6 bg-slate-50 border-t border-gray-100 flex gap-3">
                    <button
                        onClick={onClose}
                        className="flex-1 py-3 bg-white border border-slate-200 text-slate-600 rounded-2xl font-bold hover:bg-slate-50 transition-all active:scale-95"
                    >
                        취소
                    </button>
                    <button
                        onClick={handleSave}
                        disabled={isSaving || (apiKey === '' && !hasKey && !isKeyEditing)}
                        className="flex-1 py-3 bg-amber-500 text-white rounded-2xl font-bold hover:bg-amber-600 transition-all shadow-lg shadow-amber-200 active:scale-95 disabled:opacity-50 disabled:shadow-none"
                    >
                        {isSaving ? '저장 중...' : '저장하기'}
                    </button>
                </div>
            </div>
        </div>
    );
}
