import { useState, useEffect } from 'react';
import { useAuth } from '../context/AuthContext';
import api from '../services/api';
import { cn } from '../lib/utils';
import {
    Settings as SettingsIcon, Building2, Bell, Shield, Key, Globe,
    Mail, Save, Loader2, Plus, Trash2, Copy, Eye, EyeOff, Code2,
    Brain, Check, AlertCircle, RefreshCw
} from 'lucide-react';

const tabs = [
    { id: 'general', label: 'General', icon: Building2 },
    { id: 'ai', label: 'AI Configuration', icon: Brain },
    { id: 'notifications', label: 'Notifications', icon: Bell },
    { id: 'security', label: 'Security', icon: Shield },
    { id: 'api', label: 'API Keys', icon: Key },
    { id: 'webhooks', label: 'Webhooks', icon: Globe },
];

const LLM_PROVIDERS = [
    { id: 'openrouter', name: 'OpenRouter', baseUrl: 'https://openrouter.ai/api/v1', models: [
        { id: 'meta-llama/llama-3.3-70b-instruct', name: 'Llama 3.3 70B (Free)' },
        { id: 'anthropic/claude-3.5-sonnet', name: 'Claude 3.5 Sonnet' },
        { id: 'openai/gpt-4o', name: 'GPT-4o' },
        { id: 'google/gemini-pro-1.5', name: 'Gemini Pro 1.5' },
    ]},
    { id: 'anthropic', name: 'Anthropic', baseUrl: 'https://api.anthropic.com/v1', models: [
        { id: 'claude-3-5-sonnet-20241022', name: 'Claude 3.5 Sonnet' },
        { id: 'claude-3-opus-20240229', name: 'Claude 3 Opus' },
        { id: 'claude-3-haiku-20240307', name: 'Claude 3 Haiku (Fast)' },
    ]},
    { id: 'openai', name: 'OpenAI', baseUrl: 'https://api.openai.com/v1', models: [
        { id: 'gpt-4o', name: 'GPT-4o' },
        { id: 'gpt-4o-mini', name: 'GPT-4o Mini (Fast)' },
        { id: 'gpt-4-turbo', name: 'GPT-4 Turbo' },
    ]},
    { id: 'google', name: 'Google AI', baseUrl: 'https://generativelanguage.googleapis.com/v1beta', models: [
        { id: 'gemini-1.5-pro', name: 'Gemini 1.5 Pro' },
        { id: 'gemini-1.5-flash', name: 'Gemini 1.5 Flash (Fast)' },
    ]},
    { id: 'groq', name: 'Groq', baseUrl: 'https://api.groq.com/openai/v1', models: [
        { id: 'llama-3.3-70b-versatile', name: 'Llama 3.3 70B' },
        { id: 'mixtral-8x7b-32768', name: 'Mixtral 8x7B' },
    ]},
];

export default function Settings() {
    const { currentOrg } = useAuth();
    const [activeTab, setActiveTab] = useState('general');
    const [saving, setSaving] = useState(false);
    const [showToken, setShowToken] = useState(false);
    
    // AI Config state
    const [aiConfig, setAiConfig] = useState({
        provider: 'openrouter',
        apiKey: '',
        model: 'meta-llama/llama-3.3-70b-instruct',
        autoAnalyze: true,
        autoCreatePR: true,
        confidenceThreshold: 70,
    });
    const [showApiKey, setShowApiKey] = useState(false);
    const [testingConnection, setTestingConnection] = useState(false);
    const [connectionStatus, setConnectionStatus] = useState(null);
    const [loadingConfig, setLoadingConfig] = useState(true);

    useEffect(() => {
        if (currentOrg) {
            loadAiConfig();
        }
    }, [currentOrg]);

    const loadAiConfig = async () => {
        try {
            const response = await api.get(`/organizations/${currentOrg.id}/settings`);
            if (response.data?.ai_config) {
                setAiConfig(prev => ({ ...prev, ...response.data.ai_config }));
            }
        } catch (err) {
            // Config not found, use defaults
        } finally {
            setLoadingConfig(false);
        }
    };

    const handleSaveAiConfig = async () => {
        setSaving(true);
        try {
            await api.put(`/organizations/${currentOrg.id}/settings`, {
                ai_config: aiConfig
            });
            setConnectionStatus({ type: 'success', message: 'Configuration saved!' });
        } catch (err) {
            setConnectionStatus({ type: 'error', message: 'Failed to save configuration' });
        } finally {
            setSaving(false);
        }
    };

    const testConnection = async () => {
        setTestingConnection(true);
        setConnectionStatus(null);
        try {
            const response = await api.post(`/organizations/${currentOrg.id}/test-llm`, {
                provider: aiConfig.provider,
                api_key: aiConfig.apiKey,
                model: aiConfig.model,
            });
            setConnectionStatus({ type: 'success', message: 'Connection successful! API key is valid.' });
        } catch (err) {
            setConnectionStatus({ 
                type: 'error', 
                message: err.response?.data?.detail || 'Connection failed. Check your API key.' 
            });
        } finally {
            setTestingConnection(false);
        }
    };

    const selectedProvider = LLM_PROVIDERS.find(p => p.id === aiConfig.provider);

    if (!currentOrg) return <div className="flex items-center justify-center h-full p-8"><p className="text-gray-500">Select an organization</p></div>;

    const handleSave = async () => {
        setSaving(true);
        await new Promise(r => setTimeout(r, 1000));
        setSaving(false);
    };

    return (
        <div className="p-6 animate-fade-in">
            <div className="page-header">
                <div>
                    <h1 className="page-title">Settings</h1>
                    <p className="page-subtitle">Manage your organization settings</p>
                </div>
            </div>

            <div className="flex gap-6">
                {/* Sidebar tabs */}
                <div className="w-52 flex-shrink-0">
                    <div className="space-y-0.5">
                        {tabs.map(tab => {
                            const Icon = tab.icon;
                            return (
                                <button
                                    key={tab.id}
                                    onClick={() => setActiveTab(tab.id)}
                                    className={cn(
                                        "w-full sidebar-item",
                                        activeTab === tab.id ? "sidebar-item-active" : "sidebar-item-inactive"
                                    )}
                                >
                                    <Icon size={16} />
                                    <span>{tab.label}</span>
                                </button>
                            );
                        })}
                    </div>
                </div>

                {/* Content */}
                <div className="flex-1 max-w-2xl">
                    {activeTab === 'general' && (
                        <div className="card animate-fade-in">
                            <div className="card-header">
                                <h3 className="text-sm font-semibold">Organization Details</h3>
                            </div>
                            <div className="card-body space-y-5">
                                <div>
                                    <label className="block text-xs font-medium text-gray-400 mb-1.5 uppercase tracking-wide">Organization Name</label>
                                    <input defaultValue={currentOrg.name} className="input" placeholder="My Organization" />
                                </div>
                                <div>
                                    <label className="block text-xs font-medium text-gray-400 mb-1.5 uppercase tracking-wide">Slug</label>
                                    <input defaultValue={currentOrg.slug || ''} className="input font-mono" placeholder="my-org" />
                                </div>
                                <div className="pt-3 border-t border-gray-800">
                                    <button onClick={handleSave} disabled={saving} className="btn btn-primary">
                                        {saving ? <Loader2 size={14} className="animate-spin" /> : <Save size={14} />}
                                        Save Changes
                                    </button>
                                </div>
                            </div>
                        </div>
                    )}

                    {activeTab === 'ai' && (
                        <div className="space-y-6 animate-fade-in">
                            {/* AI Provider Configuration */}
                            <div className="card">
                                <div className="card-header">
                                    <h3 className="text-sm font-semibold flex items-center gap-2">
                                        <Brain size={16} className="text-indigo-400" />
                                        AI Provider Configuration
                                    </h3>
                                </div>
                                <div className="card-body space-y-5">
                                    {/* Provider Selection */}
                                    <div>
                                        <label className="block text-xs font-medium text-gray-400 mb-1.5 uppercase tracking-wide">Provider</label>
                                        <select 
                                            value={aiConfig.provider}
                                            onChange={(e) => {
                                                const provider = LLM_PROVIDERS.find(p => p.id === e.target.value);
                                                setAiConfig({
                                                    ...aiConfig,
                                                    provider: e.target.value,
                                                    model: provider?.models[0]?.id || ''
                                                });
                                                setConnectionStatus(null);
                                            }}
                                            className="input"
                                        >
                                            {LLM_PROVIDERS.map(p => (
                                                <option key={p.id} value={p.id}>{p.name}</option>
                                            ))}
                                        </select>
                                    </div>

                                    {/* API Key */}
                                    <div>
                                        <label className="block text-xs font-medium text-gray-400 mb-1.5 uppercase tracking-wide">API Key</label>
                                        <div className="relative">
                                            <input 
                                                type={showApiKey ? "text" : "password"}
                                                value={aiConfig.apiKey}
                                                onChange={(e) => {
                                                    setAiConfig({ ...aiConfig, apiKey: e.target.value });
                                                    setConnectionStatus(null);
                                                }}
                                                className="input pr-20 font-mono"
                                                placeholder={`Enter your ${selectedProvider?.name} API key`}
                                            />
                                            <div className="absolute right-2 top-1/2 -translate-y-1/2 flex items-center gap-1">
                                                <button 
                                                    type="button"
                                                    onClick={() => setShowApiKey(!showApiKey)}
                                                    className="p-1 text-gray-500 hover:text-gray-300"
                                                >
                                                    {showApiKey ? <EyeOff size={14} /> : <Eye size={14} />}
                                                </button>
                                            </div>
                                        </div>
                                        <p className="text-xs text-gray-600 mt-1">
                                            Get your API key from{' '}
                                            <a 
                                                href={selectedProvider?.id === 'openrouter' ? 'https://openrouter.ai/keys' : 
                                                      selectedProvider?.id === 'anthropic' ? 'https://console.anthropic.com/settings/keys' :
                                                      selectedProvider?.id === 'openai' ? 'https://platform.openai.com/api-keys' :
                                                      selectedProvider?.id === 'google' ? 'https://aistudio.google.com/app/apikey' :
                                                      'https://console.groq.com/keys'}
                                                target="_blank"
                                                rel="noopener noreferrer"
                                                className="text-indigo-400 hover:text-indigo-300"
                                            >
                                                {selectedProvider?.name} dashboard
                                            </a>
                                        </p>
                                    </div>

                                    {/* Model Selection */}
                                    <div>
                                        <label className="block text-xs font-medium text-gray-400 mb-1.5 uppercase tracking-wide">Model</label>
                                        <select 
                                            value={aiConfig.model}
                                            onChange={(e) => setAiConfig({ ...aiConfig, model: e.target.value })}
                                            className="input"
                                        >
                                            {selectedProvider?.models.map(m => (
                                                <option key={m.id} value={m.id}>{m.name}</option>
                                            ))}
                                        </select>
                                    </div>

                                    {/* Test Connection */}
                                    <div className="flex items-center gap-3 pt-3 border-t border-gray-800">
                                        <button 
                                            onClick={testConnection}
                                            disabled={testingConnection || !aiConfig.apiKey}
                                            className="btn btn-secondary"
                                        >
                                            {testingConnection ? (
                                                <Loader2 size={14} className="animate-spin" />
                                            ) : (
                                                <RefreshCw size={14} />
                                            )}
                                            Test Connection
                                        </button>
                                        {connectionStatus && (
                                            <div className={cn(
                                                "flex items-center gap-2 text-sm",
                                                connectionStatus.type === 'success' ? "text-green-400" : "text-red-400"
                                            )}>
                                                {connectionStatus.type === 'success' ? <Check size={14} /> : <AlertCircle size={14} />}
                                                {connectionStatus.message}
                                            </div>
                                        )}
                                    </div>
                                </div>
                            </div>

                            {/* Analysis Settings */}
                            <div className="card">
                                <div className="card-header">
                                    <h3 className="text-sm font-semibold">Analysis Settings</h3>
                                </div>
                                <div className="card-body space-y-4">
                                    <div className="flex items-center justify-between py-2">
                                        <div>
                                            <p className="text-sm font-medium text-gray-200">Auto-analyze new issues</p>
                                            <p className="text-xs text-gray-500">Automatically analyze issues when received</p>
                                        </div>
                                        <label className="relative inline-flex items-center cursor-pointer">
                                            <input 
                                                type="checkbox" 
                                                checked={aiConfig.autoAnalyze}
                                                onChange={(e) => setAiConfig({ ...aiConfig, autoAnalyze: e.target.checked })}
                                                className="sr-only peer" 
                                            />
                                            <div className="w-9 h-5 bg-gray-700 rounded-full peer peer-checked:bg-indigo-600 after:content-[''] after:absolute after:top-0.5 after:left-0.5 after:bg-white after:rounded-full after:h-4 after:w-4 after:transition-all peer-checked:after:translate-x-4" />
                                        </label>
                                    </div>
                                    <div className="flex items-center justify-between py-2">
                                        <div>
                                            <p className="text-sm font-medium text-gray-200">Auto-create Pull Requests</p>
                                            <p className="text-xs text-gray-500">Create PRs automatically for high-confidence fixes</p>
                                        </div>
                                        <label className="relative inline-flex items-center cursor-pointer">
                                            <input 
                                                type="checkbox" 
                                                checked={aiConfig.autoCreatePR}
                                                onChange={(e) => setAiConfig({ ...aiConfig, autoCreatePR: e.target.checked })}
                                                className="sr-only peer" 
                                            />
                                            <div className="w-9 h-5 bg-gray-700 rounded-full peer peer-checked:bg-indigo-600 after:content-[''] after:absolute after:top-0.5 after:left-0.5 after:bg-white after:rounded-full after:h-4 after:w-4 after:transition-all peer-checked:after:translate-x-4" />
                                        </label>
                                    </div>
                                    <div>
                                        <label className="block text-xs font-medium text-gray-400 mb-1.5 uppercase tracking-wide">
                                            Confidence Threshold for Auto-PR ({aiConfig.confidenceThreshold}%)
                                        </label>
                                        <input 
                                            type="range"
                                            min="50"
                                            max="95"
                                            step="5"
                                            value={aiConfig.confidenceThreshold}
                                            onChange={(e) => setAiConfig({ ...aiConfig, confidenceThreshold: parseInt(e.target.value) })}
                                            className="w-full h-2 bg-gray-700 rounded-lg appearance-none cursor-pointer accent-indigo-600"
                                        />
                                        <div className="flex justify-between text-xs text-gray-600 mt-1">
                                            <span>50% (More PRs)</span>
                                            <span>95% (Higher quality)</span>
                                        </div>
                                    </div>
                                </div>
                            </div>

                            {/* Save Button */}
                            <div className="flex justify-end">
                                <button onClick={handleSaveAiConfig} disabled={saving} className="btn btn-primary">
                                    {saving ? <Loader2 size={14} className="animate-spin" /> : <Save size={14} />}
                                    Save AI Configuration
                                </button>
                            </div>
                        </div>
                    )}

                    {activeTab === 'notifications' && (
                        <div className="card animate-fade-in">
                            <div className="card-header">
                                <h3 className="text-sm font-semibold">Notification Preferences</h3>
                            </div>
                            <div className="card-body space-y-4">
                                {[
                                    { label: 'New issue received', desc: 'When a new issue arrives from an integration' },
                                    { label: 'Analysis completed', desc: 'When AI finishes analyzing an issue' },
                                    { label: 'PR created', desc: 'When a Pull Request is automatically generated' },
                                    { label: 'Analysis error', desc: 'When AI fails to analyze an issue' },
                                    { label: 'Daily digest', desc: 'Summary of daily activity' },
                                ].map(item => (
                                    <div key={item.label} className="flex items-center justify-between py-2">
                                        <div>
                                            <p className="text-sm font-medium text-gray-200">{item.label}</p>
                                            <p className="text-xs text-gray-500">{item.desc}</p>
                                        </div>
                                        <label className="relative inline-flex items-center cursor-pointer">
                                            <input type="checkbox" defaultChecked className="sr-only peer" />
                                            <div className="w-9 h-5 bg-gray-700 rounded-full peer peer-checked:bg-indigo-600 after:content-[''] after:absolute after:top-0.5 after:left-0.5 after:bg-white after:rounded-full after:h-4 after:w-4 after:transition-all peer-checked:after:translate-x-4" />
                                        </label>
                                    </div>
                                ))}
                                <div className="pt-3 border-t border-gray-800">
                                    <label className="block text-xs font-medium text-gray-400 mb-1.5 uppercase tracking-wide">Notification Email</label>
                                    <div className="flex gap-2">
                                        <div className="relative flex-1">
                                            <Mail size={16} className="absolute left-3 top-1/2 -translate-y-1/2 text-gray-500" />
                                            <input className="input pl-10" placeholder="team@company.com" />
                                        </div>
                                        <button className="btn btn-primary btn-sm"><Save size={14} /></button>
                                    </div>
                                </div>
                            </div>
                        </div>
                    )}

                    {activeTab === 'security' && (
                        <div className="card animate-fade-in">
                            <div className="card-header">
                                <h3 className="text-sm font-semibold">Security Settings</h3>
                            </div>
                            <div className="card-body space-y-5">
                                <div className="flex items-center justify-between py-2">
                                    <div>
                                        <p className="text-sm font-medium text-gray-200">Two-Factor Authentication</p>
                                        <p className="text-xs text-gray-500">Require 2FA for all organization members</p>
                                    </div>
                                    <label className="relative inline-flex items-center cursor-pointer">
                                        <input type="checkbox" className="sr-only peer" />
                                        <div className="w-9 h-5 bg-gray-700 rounded-full peer peer-checked:bg-indigo-600 after:content-[''] after:absolute after:top-0.5 after:left-0.5 after:bg-white after:rounded-full after:h-4 after:w-4 after:transition-all peer-checked:after:translate-x-4" />
                                    </label>
                                </div>
                                <div className="flex items-center justify-between py-2">
                                    <div>
                                        <p className="text-sm font-medium text-gray-200">SSO / SAML</p>
                                        <p className="text-xs text-gray-500">Enable Single Sign-On with your identity provider</p>
                                    </div>
                                    <span className="badge badge-gray">Enterprise</span>
                                </div>
                                <div>
                                    <label className="block text-xs font-medium text-gray-400 mb-1.5 uppercase tracking-wide">IP Allowlist</label>
                                    <textarea className="input h-20 resize-none font-mono text-xs" placeholder="192.168.1.0/24&#10;10.0.0.0/8" />
                                    <p className="text-xs text-gray-600 mt-1">One CIDR per line. Leave empty to allow all.</p>
                                </div>
                            </div>
                        </div>
                    )}

                    {activeTab === 'api' && (
                        <div className="card animate-fade-in">
                            <div className="card-header">
                                <h3 className="text-sm font-semibold">API Keys</h3>
                                <button className="btn btn-primary btn-sm"><Plus size={14} /> Create Key</button>
                            </div>
                            <div className="card-body">
                                <div className="space-y-3">
                                    <div className="flex items-center gap-3 p-3 bg-gray-900/50 rounded-lg border border-gray-800/50">
                                        <Key size={16} className="text-gray-500" />
                                        <div className="flex-1 min-w-0">
                                            <p className="text-sm font-medium">Production API Key</p>
                                            <div className="flex items-center gap-2 mt-1">
                                                <code className="text-xs text-gray-500 font-mono">
                                                    {showToken ? 'jaf_live_sk_a1b2c3d4e5f6...' : 'jaf_live_sk_••••••••••••...'}
                                                </code>
                                                <button onClick={() => setShowToken(!showToken)} className="text-gray-500 hover:text-gray-300">
                                                    {showToken ? <EyeOff size={12} /> : <Eye size={12} />}
                                                </button>
                                                <button className="text-gray-500 hover:text-gray-300"><Copy size={12} /></button>
                                            </div>
                                        </div>
                                        <span className="badge badge-green text-[10px]">Active</span>
                                        <button className="btn btn-danger btn-sm btn-icon"><Trash2 size={12} /></button>
                                    </div>
                                </div>
                                <div className="mt-4 p-4 bg-gray-950 rounded-lg border border-gray-800">
                                    <h4 className="text-xs font-semibold text-gray-400 mb-2 flex items-center gap-1.5"><Code2 size={12} /> Quick Start</h4>
                                    <pre className="text-xs text-gray-400 font-mono overflow-x-auto">
{`curl -X POST https://jira-fixer.startdata.com.br/api/issues \\
  -H "Authorization: Bearer YOUR_API_KEY" \\
  -H "Content-Type: application/json" \\
  -d '{"title": "Bug fix needed", "source": "api"}'`}
                                    </pre>
                                </div>
                            </div>
                        </div>
                    )}

                    {activeTab === 'webhooks' && (
                        <div className="card animate-fade-in">
                            <div className="card-header">
                                <h3 className="text-sm font-semibold">Webhook Endpoints</h3>
                                <button className="btn btn-primary btn-sm"><Plus size={14} /> Add Endpoint</button>
                            </div>
                            <div className="card-body">
                                <div className="p-4 bg-gray-900/50 rounded-lg border border-gray-800/50 mb-4">
                                    <h4 className="text-xs font-semibold text-gray-400 mb-2">Incoming Webhook URLs</h4>
                                    <div className="space-y-2">
                                        {['tickethub', 'jira', 'servicenow', 'github', 'gitlab', 'gitea'].map(source => (
                                            <div key={source} className="flex items-center gap-2">
                                                <span className="text-xs text-gray-500 w-24 capitalize">{source}:</span>
                                                <code className="text-xs text-indigo-400 font-mono flex-1 truncate">
                                                    https://jira-fixer.startdata.com.br/api/webhooks/{currentOrg.id}/{source}
                                                </code>
                                                <button className="text-gray-500 hover:text-gray-300"><Copy size={12} /></button>
                                            </div>
                                        ))}
                                    </div>
                                </div>
                                <div className="text-center py-6 text-gray-500">
                                    <Globe size={24} className="mx-auto mb-2 text-gray-600" />
                                    <p className="text-sm">No outgoing webhook endpoints configured</p>
                                    <p className="text-xs text-gray-600 mt-1">Add endpoints to receive event notifications</p>
                                </div>
                            </div>
                        </div>
                    )}
                </div>
            </div>
        </div>
    );
}
