import React, { useState, useEffect } from 'react';
import { Key, Save, Check, Trash2, X } from 'lucide-react';

interface ApiKeyModalProps {
    isOpen: boolean;
    onClose: () => void;
}

export const ApiKeyModal: React.FC<ApiKeyModalProps> = ({ isOpen, onClose }) => {
    const [key, setKey] = useState('');
    const [saved, setSaved] = useState(false);

    useEffect(() => {
        const storedKey = localStorage.getItem('gemini_api_key');
        if (storedKey) {
            setKey(storedKey);
            setSaved(true);
        }
    }, [isOpen]);

    const handleSave = () => {
        if (key.trim()) {
            localStorage.setItem('gemini_api_key', key.trim());
            setSaved(true);
            // Optional: Trigger a storage event for immediate UI updates elsewhere if needed
            window.dispatchEvent(new Event('storage'));
            onClose();
        }
    };

    const handleClear = () => {
        localStorage.removeItem('gemini_api_key');
        setKey('');
        setSaved(false);
        window.dispatchEvent(new Event('storage'));
    };

    if (!isOpen) return null;

    return (
        <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/60 backdrop-blur-sm p-4 animate-in fade-in duration-200">
            <div className="w-full max-w-md bg-stone-900 border border-stone-800 rounded-xl shadow-2xl overflow-hidden animate-in zoom-in-95 duration-200">

                {/* Header */}
                <div className="px-6 py-4 border-b border-stone-800 flex justify-between items-center bg-stone-900/50">
                    <div className="flex items-center gap-3">
                        <div className="p-2 bg-emerald-500/10 rounded-lg">
                            <Key className="w-5 h-5 text-emerald-400" />
                        </div>
                        <div>
                            <h2 className="text-lg font-semibold text-stone-100">API Configuration</h2>
                            <p className="text-xs text-stone-500">Bring Your Own Key (Beta Mode)</p>
                        </div>
                    </div>
                    <button onClick={onClose} className="text-stone-500 hover:text-stone-300 transition-colors">
                        <X className="w-5 h-5" />
                    </button>
                </div>

                {/* Body */}
                <div className="p-6 space-y-4">
                    <div className="p-3 bg-stone-800/50 rounded-lg border border-stone-700/50">
                        <p className="text-sm text-stone-400 leading-relaxed">
                            <span className="text-emerald-400 font-medium">Why use your own key?</span>
                            <br />
                            Using your personal Google Gemini API key ensures strictly private usage limits and helps support the platform during this free Beta period.
                        </p>
                    </div>

                    <div className="space-y-2">
                        <label className="text-xs font-medium text-stone-400 uppercase tracking-wider ml-1">
                            Google Gemini API Key
                        </label>
                        <input
                            type="password"
                            value={key}
                            onChange={(e) => setKey(e.target.value)}
                            placeholder="AIzaSy..."
                            className="w-full bg-black/40 border border-stone-700 rounded-lg px-4 py-3 text-stone-200 placeholder-stone-600 focus:outline-none focus:ring-2 focus:ring-emerald-500/50 focus:border-emerald-500 transition-all font-mono text-sm"
                        />
                    </div>

                    <div className="flex items-center justify-between pt-2">
                        <a
                            href="https://aistudio.google.com/app/apikey"
                            target="_blank"
                            rel="noreferrer"
                            className="text-xs text-emerald-500 hover:text-emerald-400 hover:underline flex items-center gap-1"
                        >
                            Get a key from Google AI Studio
                        </a>

                        {saved && (
                            <button
                                onClick={handleClear}
                                className="text-xs text-red-400 hover:text-red-300 flex items-center gap-1 px-2 py-1 hover:bg-red-950/30 rounded transition-colors"
                            >
                                <Trash2 className="w-3 h-3" /> Clear Key
                            </button>
                        )}
                    </div>
                </div>

                {/* Footer */}
                <div className="px-6 py-4 bg-stone-950/50 border-t border-stone-800 flex justify-end gap-3">
                    <button
                        onClick={onClose}
                        className="px-4 py-2 text-sm text-stone-400 hover:text-stone-200 transition-colors"
                    >
                        Cancel
                    </button>
                    <button
                        onClick={handleSave}
                        disabled={!key.trim()}
                        className="flex items-center gap-2 px-6 py-2 bg-emerald-600 hover:bg-emerald-500 text-white text-sm font-medium rounded-lg shadow-lg shadow-emerald-900/20 disabled:opacity-50 disabled:cursor-not-allowed transition-all active:scale-95"
                    >
                        {saved ? <Check className="w-4 h-4" /> : <Save className="w-4 h-4" />}
                        {saved ? 'Updated' : 'Save Key'}
                    </button>
                </div>

            </div>
        </div>
    );
};
