<template>
    <div>
        <h1 class="text-3xl font-bold mb-4 text-gray-800">{{ $t('LLM Settings') }}</h1>
        <div class="border-b border-gray-100 mb-4"></div>

        <div class="space-y-4">
            <!-- LLM Provider Selection -->
            <div class="mb-8">
                <div class="flex items-center justify-between mb-6">
                    <div>
                        <h3 class="text-xl font-bold text-gray-900">{{ $t('AI Provider') }}</h3>
                        <p class="text-sm text-gray-600 mt-1">{{
                                $t('Select your preferred language model provider')
                            }}</p>
                    </div>
                    <div class="hidden md:flex items-center text-xs text-gray-500 bg-gray-50 px-3 py-1.5 rounded-full">
                        <Icon name="information-line" size="xs" class="mr-1"/>
                        {{ $t('You can change this anytime') }}
                    </div>
                </div>

                <!-- Loading Skeleton -->
                <div v-if="state.loading.page" class="grid grid-cols-1 lg:grid-cols-3 gap-5">
                    <div v-for="i in 3" :key="i" class="animate-pulse">
                        <div class="bg-gray-200 rounded-3xl h-48"></div>
                    </div>
                </div>

                <!-- Provider Cards -->
                <div v-else class="grid grid-cols-1 lg:grid-cols-3 gap-5">
                    <!-- OpenAI -->
                    <label class="provider-radio-card group" :class="{ 'selected': form.provider === 'openai' }">
                        <input
                            type="radio"
                            name="llm_provider"
                            value="openai"
                            v-model="form.provider"
                            @change="onProviderChange"
                            class="sr-only"
                        />
                        <div class="relative overflow-hidden h-full rounded-3xl">
                            <!-- Selection indicator -->
                            <div v-if="form.provider === 'openai'"
                                 class="absolute top-4 right-4 w-6 h-6 bg-gradient-to-r from-blue-600 to-blue-700 rounded-full flex items-center justify-center z-10 shadow-lg">
                                <Icon name="check-line" size="xs" class="text-white"/>
                            </div>

                            <!-- Background pattern -->
                            <div
                                class="absolute inset-0 bg-gradient-to-br from-green-50/50 to-emerald-50/50 opacity-0 group-hover:opacity-100 transition-all duration-500 rounded-3xl"></div>
                            <div
                                class="absolute inset-0 bg-gradient-to-br from-transparent via-transparent to-green-100/20 opacity-0 group-hover:opacity-100 transition-all duration-700 rounded-3xl"></div>

                            <div class="relative p-6 h-full flex flex-col">
                                <!-- Header with icon and title in one line -->
                                <div class="flex items-center mb-4">
                                    <div
                                        class="w-12 h-12 bg-gradient-to-br from-white to-green-50 shadow-md border border-green-200/50 rounded-xl flex items-center justify-center group-hover:shadow-lg transition-all duration-300 mr-4">
                                        <Icon name="openai-line" size="lg" class="text-green-600"/>
                                    </div>
                                    <h4 class="text-lg font-bold text-gray-900">OpenAI</h4>
                                </div>

                                <!-- Content -->
                                <div class="flex-1">
                                    <p class="text-sm text-gray-600 mb-4 leading-relaxed">Industry-leading GPT models
                                        with exceptional natural language understanding and generation capabilities.</p>
                                </div>
                            </div>
                        </div>
                    </label>

                    <!-- Google Gemini -->
                    <label class="provider-radio-card group" :class="{ 'selected': form.provider === 'gemini' }">
                        <input
                            type="radio"
                            name="llm_provider"
                            value="gemini"
                            v-model="form.provider"
                            @change="onProviderChange"
                            class="sr-only"
                        />
                        <div class="relative overflow-hidden h-full rounded-3xl">
                            <!-- Selection indicator -->
                            <div v-if="form.provider === 'gemini'"
                                 class="absolute top-4 right-4 w-6 h-6 bg-gradient-to-r from-blue-600 to-blue-700 rounded-full flex items-center justify-center z-10 shadow-lg">
                                <Icon name="check-line" size="xs" class="text-white"/>
                            </div>

                            <!-- Background pattern -->
                            <div
                                class="absolute inset-0 bg-gradient-to-br from-blue-50/50 to-sky-50/50 opacity-0 group-hover:opacity-100 transition-all duration-500 rounded-3xl"></div>
                            <div
                                class="absolute inset-0 bg-gradient-to-br from-transparent via-transparent to-blue-100/20 opacity-0 group-hover:opacity-100 transition-all duration-700 rounded-3xl"></div>

                            <div class="relative p-6 h-full flex flex-col">
                                <!-- Header with icon and title in one line -->
                                <div class="flex items-center mb-4">
                                    <div
                                        class="w-12 h-12 bg-gradient-to-br from-white to-blue-50 shadow-md border border-blue-200/50 rounded-xl flex items-center justify-center group-hover:shadow-lg transition-all duration-300 mr-4">
                                        <Icon name="google-line" size="lg" class="text-blue-600"/>
                                    </div>
                                    <h4 class="text-lg font-bold text-gray-900">Google Gemini</h4>
                                </div>

                                <!-- Content -->
                                <div class="flex-1">
                                    <p class="text-sm text-gray-600 mb-4 leading-relaxed">Gemini models with
                                        cutting-edge multimodal capabilities, handling text, images, and complex
                                        reasoning tasks.</p>
                                </div>
                            </div>
                        </div>
                    </label>

                    <!-- Anthropic Claude (Disabled) -->
                    <div class="provider-radio-card group disabled opacity-60 cursor-not-allowed">
                        <div class="relative overflow-hidden h-full rounded-3xl">
                            <!-- Disabled indicator -->
                            <div
                                class="absolute top-4 right-4 px-2 py-1 bg-gray-500 text-white text-xs rounded-full font-medium">
                                Coming Soon
                            </div>

                            <!-- Background pattern (muted) -->
                            <div
                                class="absolute inset-0 bg-gradient-to-br from-gray-50/50 to-gray-100/50 rounded-3xl"></div>

                            <div class="relative p-6 h-full flex flex-col">
                                <!-- Header with icon and title in one line -->
                                <div class="flex items-center mb-4">
                                    <div
                                        class="w-12 h-12 bg-gradient-to-br from-white to-gray-50 shadow-md border border-gray-200/50 rounded-xl flex items-center justify-center mr-4">
                                        <Icon name="robot-line" size="lg" class="text-gray-400"/>
                                    </div>
                                    <h4 class="text-lg font-bold text-gray-500">Anthropic Claude</h4>
                                </div>

                                <!-- Content -->
                                <div class="flex-1">
                                    <p class="text-sm text-gray-500 mb-4 leading-relaxed">Claude models with
                                        constitutional AI training, offering thoughtful responses and strong ethical
                                        reasoning.</p>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>


            <!-- Provider-specific Configuration -->
            <div v-if="form.provider">
                <!-- Loading Skeleton for Provider Configuration -->
                <div v-if="state.loading.page" class="animate-pulse space-y-6">
                    <div class="bg-gray-200 rounded-xl h-32"></div>
                    <div class="bg-gray-200 rounded-xl h-24"></div>
                    <div class="bg-gray-200 rounded-xl h-20"></div>
                </div>

                <!-- Provider Configuration Components -->
                <div v-else>
                    <!-- OpenAI Configuration -->
                    <OpenAISettings
                        v-if="form.provider === 'openai'"
                        v-model="form"
                        @test-connection="testConnection"
                        :is-testing="state.loading.testing"
                        :connection-status="state.connectionStatus"
                        :is-configured="state.isConfigured"
                        :smart-defaults="state.smartDefaults"
                        :available-models="state.availableProviders.openai?.models || {}"
                    />

                    <!-- Google Gemini Configuration -->
                    <GoogleSettings
                        v-if="form.provider === 'gemini'"
                        v-model="form"
                        @test-connection="testConnection"
                        :is-testing="state.loading.testing"
                        :connection-status="state.connectionStatus"
                        :is-configured="state.isConfigured"
                        :smart-defaults="state.smartDefaults"
                        :available-models="state.availableProviders.gemini?.models || {}"
                    />

                    <!-- Anthropic Claude Configuration (Disabled) -->
                    <!-- AnthropicSettings component removed since Claude is disabled -->
                </div>
            </div>


            <!-- Actions -->
            <div class="flex items-center justify-end pt-2">
                <button type="button" class="btn-primary" @click="onSave"
                        :disabled="state.loading.page || state.loading.saving || !canSave">
                    <span v-if="state.loading.saving">{{ $t('Saving...') }}</span>
                    <span v-else>{{ $t('Save Settings') }}</span>
                </button>
            </div>
        </div>
    </div>
</template>

<script setup>
import { reactive, computed, onMounted } from 'vue'
import OpenAISettings from './Components/OpenAISettings.vue'
import GoogleSettings from './Components/GoogleSettings.vue'
import Icon from '@/Admin/Components/Icon.vue'

import { useForm } from '@/Admin/js/composables/useForm.js'
import { useToast } from '@/Admin/js/composables/useToast.js'
import Http from '@/Admin/js/utils/http.js'

// Reactive state
const state = reactive({
    loading: {
        page: true,
        saving: false,
        testing: false
    },
    connectionStatus: null,
    // Provider data
    availableProviders: {},
    currentProviderConfig: {},
    limits: {},
    isConfigured: false,
    smartDefaults: null
})

// Toast notifications
const { showSuccess, showError } = useToast()

const makeDefaults = () => ( {
    // Single model configuration - user selects one provider and one model at a time
    provider: 'openai',
    model: 'gpt-3.5-turbo',
    temperature: 0.7,
    max_tokens: 1000,
    system_prompt: '',
    api_key: '',

    // Provider-specific fields for existing components
    openai_api_key: '',
    openai_model: 'gpt-3.5-turbo',
    openai_temperature: 0.7,
    openai_max_tokens: 1000,

    google_api_key: '',
    google_model: 'gemini-pro',
    google_temperature: 0.7,
    google_max_tokens: 1000
} )

const form = useForm(makeDefaults())

// Computed properties
const selectedProvider = computed(() => form.provider || 'openai')

const canSave = computed(() => {
    const provider = form.provider
    if (!provider) return false

    // Check if the current provider has required fields filled
    switch (provider) {
        case 'openai':
            return form.openai_api_key && form.openai_model
        case 'gemini':
            return form.google_api_key && form.google_model
        default:
            return false
    }
})

// Actions
const onProviderChange = () => {
    // Reset connection status when provider changes
    state.connectionStatus = null

    // Sync provider-specific fields when provider changes
    const provider = form.provider

    // Get default models from available providers
    const openaiDefaultModel = state.availableProviders.openai?.default_model || 'gpt-5-mini'
    const geminiDefaultModel = state.availableProviders.gemini?.default_model || 'gemini-2.5-flash'

    if (provider === 'openai') {
        form.model = form.openai_model || openaiDefaultModel
        form.api_key = form.openai_api_key || ''
        form.temperature = form.openai_temperature || 0.7
        form.max_tokens = form.openai_max_tokens || 1000
    } else if (provider === 'gemini') {
        form.model = form.google_model || geminiDefaultModel
        form.api_key = form.google_api_key || ''
        form.temperature = form.google_temperature || 0.7
        form.max_tokens = form.google_max_tokens || 1000
    }
}


const testConnection = async (providerData) => {
    state.loading.testing = true
    state.connectionStatus = null

    try {
        const response = await Http.post('llm-settings/test-connection', {
            provider: form.provider,
            model: form.provider === 'openai' ? form.openai_model : form.google_model,
            api_key: form.provider === 'openai' ? form.openai_api_key : form.google_api_key
        })

        state.connectionStatus = {
            success: response.success,
            message: response.message || ( response.success ? 'Connection successful!' : 'Connection failed.' )
        }
    } catch (error) {
        state.connectionStatus = {
            success: false,
            message: 'Connection test failed. Please try again.'
        }
    } finally {
        state.loading.testing = false
    }
}

const onSave = async () => {
    state.loading.saving = true

    try {
        // Map provider-specific fields to simplified backend structure
        const provider = form.provider
        let model, apiKey, temperature, maxTokens

        switch (provider) {
            case 'openai':
                model = form.openai_model
                apiKey = form.openai_api_key
                temperature = form.openai_temperature || form.temperature
                maxTokens = form.openai_max_tokens || form.max_tokens
                break
            case 'gemini':
                model = form.google_model
                apiKey = form.google_api_key
                temperature = form.google_temperature || form.temperature
                maxTokens = form.google_max_tokens || form.max_tokens
                break
            default:
                model = form.model
                apiKey = form.api_key
                temperature = form.temperature
                maxTokens = form.max_tokens
        }

        const saveData = {
            provider: provider,
            model: model,
            temperature: temperature,
            max_tokens: maxTokens,
            system_prompt: form.system_prompt,
            api_key: apiKey !== '••••••••••••••••' ? apiKey : undefined
        }

        const result = await Http.post('llm-settings', saveData)
        showSuccess(result.message || 'LLM settings saved successfully!')
    } catch (error) {
        showError(error.message || 'Failed to save settings. Please try again.')
    } finally {
        state.loading.saving = false
    }
}

const fetchSettings = async () => {
    try {
        state.loading.page = true

        const data = await Http.get('llm-settings')

        if (data.success && data.data) {
            // Store configuration status and smart defaults info
            state.isConfigured = data.data.is_configured || false
            state.smartDefaults = data.data.smart_defaults || null

            // Store available providers and their models for dynamic rendering
            state.availableProviders = data.data.available_providers || {}
            state.currentProviderConfig = data.data.current_provider_config || {}
            state.limits = data.data.limits || {}

            // Map simplified backend data to provider-specific frontend fields
            const provider = data.data.provider
            const model = data.data.model
            const apiKey = data.data.api_key // Will be masked if exists
            const temperature = data.data.temperature
            const maxTokens = data.data.max_tokens

            // Get default models from available providers
            const openaiDefaultModel = state.availableProviders.openai?.default_model || 'gpt-5-mini'
            const geminiDefaultModel = state.availableProviders.gemini?.default_model || 'gemini-2.5-flash'

            const formData = {
                provider: provider,
                model: model,
                temperature: temperature,
                max_tokens: maxTokens,
                system_prompt: data.data.system_prompt,
                api_key: apiKey,

                // Map to provider-specific fields based on current provider
                openai_api_key: provider === 'openai' ? apiKey : '',
                openai_model: provider === 'openai' ? model : openaiDefaultModel,
                openai_temperature: provider === 'openai' ? temperature : 0.7,
                openai_max_tokens: provider === 'openai' ? maxTokens : 1000,

                google_api_key: provider === 'gemini' ? apiKey : '',
                google_model: provider === 'gemini' ? model : geminiDefaultModel,
                google_temperature: provider === 'gemini' ? temperature : 0.7,
                google_max_tokens: provider === 'gemini' ? maxTokens : 1000
            }

            form.fill(formData)
        }
    } catch (error) {
        showError('Failed to load settings. Please refresh the page.')
    } finally {
        state.loading.page = false
    }
}

// Initialize
onMounted(fetchSettings)
</script>

<style lang="scss" scoped>
// Settings layout styles (matching ChatSettings and EmailSettings)
.settings-row {
  @apply flex flex-col md:flex-row md:items-start gap-4;
}

.settings-label {
  @apply md:w-1/3 flex-shrink-0;
}

.label-title {
  @apply text-sm font-medium text-gray-900 mb-1;
}

.label-help {
  @apply text-sm text-gray-500;
}

.settings-control {
  @apply md:w-2/3 flex-1;
}

// Form input styles
.form-input, .form-textarea, .form-select {
  @apply px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500 transition-colors;
}

.form-select {
  @apply bg-white;
}

// Button styles
.btn-primary {
  @apply bg-blue-600 text-white px-4 py-2 rounded-lg font-medium transition-colors hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-2 disabled:opacity-50 disabled:cursor-not-allowed flex items-center;
}

.btn-secondary {
  @apply bg-gray-100 text-gray-700 px-4 py-2 rounded-lg font-medium transition-colors hover:bg-gray-200 focus:outline-none focus:ring-2 focus:ring-gray-500 focus:ring-offset-2 flex items-center;
}

.btn-success {
  @apply bg-green-600 text-white px-4 py-2 rounded-lg font-medium transition-colors hover:bg-green-700 focus:outline-none focus:ring-2 focus:ring-green-500 focus:ring-offset-2 disabled:opacity-50 disabled:cursor-not-allowed flex items-center;
}

// Provider radio card styles
.provider-radio-card {
  @apply block border border-gray-100 rounded-3xl cursor-pointer transition-all duration-500 bg-gray-50 backdrop-blur-sm;
  box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.05), 0 1px 2px 0 rgba(0, 0, 0, 0.02);

  &.selected {
    @apply border-blue-400/60 shadow-2xl ring-1 ring-blue-200/50 bg-white;
    box-shadow: 0 20px 25px -5px rgba(0, 0, 0, 0.08), 0 10px 10px -5px rgba(0, 0, 0, 0.04);
    transform: translateY(-2px) scale(1.02);
  }

  &:hover:not(.selected) {
    @apply border-gray-200 shadow-xl bg-gray-100;
    box-shadow: 0 10px 15px -3px rgba(0, 0, 0, 0.08), 0 4px 6px -2px rgba(0, 0, 0, 0.04);
    transform: translateY(-4px) scale(1.01);
  }

  &:active {
    transform: translateY(-1px) scale(1.005);
  }

  // Ensure proper stacking context
  .relative {
    @apply z-0;
  }

  // Smooth height transitions
  min-height: 200px;
}

// Screen reader only
.sr-only {
  @apply absolute w-px h-px p-0 -m-px overflow-hidden whitespace-nowrap border-0;
  clip: rect(0, 0, 0, 0);
}
</style>

