<template>
    <div class="space-y-4">
        <!-- API Key -->
        <div>
            <div class="settings-row border-b border-gray-100 py-4">
                <div class="settings-label">
                    <div class="label-title flex items-center gap-2">
                        {{ $t('Google API Key') }} <span class="text-red-500">*</span>
                        <span v-if="!isConfigured" class="inline-flex items-center px-2 py-1 bg-orange-100 text-orange-800 text-xs rounded-full font-medium">
                            {{ $t('Required') }}
                        </span>
                        <span v-else-if="localForm.google_api_key" class="inline-flex items-center px-2 py-1 bg-green-100 text-green-800 text-xs rounded-full font-medium">
                            {{ $t('Configured') }}
                        </span>
                    </div>
                    <div class="label-help">{{ $t('Your Google AI API key will be encrypted and stored securely.') }}</div>
                </div>
                <div class="settings-control">
                    <div class="relative">
                        <input
                            :type="showApiKey ? 'text' : 'password'"
                            v-model="localForm.google_api_key"
                            class="form-input w-full pr-10"
                            placeholder="AIza..."
                        />
                        <button
                            type="button"
                            @click="showApiKey = !showApiKey"
                            class="absolute inset-y-0 right-0 pr-3 flex items-center"
                        >
                            <Icon
                                :name="showApiKey ? 'eye-off-line' : 'eye-line'"
                                size="sm"
                                class="text-gray-400 hover:text-gray-600"
                            />
                        </button>
                    </div>
                </div>
            </div>
        </div>

        <!-- Model Selection -->
        <div>
            <div class="settings-row border-b border-gray-100 py-4">
                <div class="settings-label">
                    <div class="label-title">{{ $t('Model') }} <span class="text-red-500">*</span></div>
                    <div class="label-help">{{ $t('Choose the Google Gemini model for generating responses.') }}</div>
                </div>
                <div class="settings-control">
                    <select v-model="localForm.google_model" class="form-select llm-model-select w-full !max-w-none">
                        <option value="">{{ $t('Select a model') }}</option>
                        <option
                            v-for="(modelConfig, modelKey) in availableModels"
                            :key="modelKey"
                            :value="modelKey"
                        >
                            {{ modelConfig.name }}
                        </option>
                    </select>

                    <!-- Selected Model Details -->
                    <div v-if="selectedModelInfo" class="mt-3 rounded-lg border border-gray-200 bg-white p-4">
                        <div class="flex items-start">
                            <div class="flex h-10 w-10 flex-shrink-0 items-center justify-center rounded-lg bg-gradient-to-br from-blue-500 to-blue-600">
                                <Icon name="google-line" class="h-6 w-6 text-white" />
                            </div>
                            <div class="ml-4 flex-1">
                                <div class="flex items-center">
                                    <h4 class="text-sm font-medium text-gray-900">{{ selectedModelInfo.name }}</h4>
                                    <span class="ml-2 inline-flex items-center rounded-full bg-blue-50 px-2 py-1 text-xs font-medium text-blue-700">
                                        Google Gemini
                                    </span>
                                </div>
                                <p v-if="selectedModelInfo.description" class="mt-1 text-sm text-gray-500">
                                    {{ selectedModelInfo.description }}
                                </p>
                                <div class="mt-2 flex flex-wrap gap-4 text-xs text-gray-500">
                                    <div class="flex items-center">
                                        <Icon name="file-text-line" class="mr-1 h-3 w-3" />
                                        {{ formatNumber(selectedModelInfo.context_window) }} context tokens
                                    </div>
                                    <div class="flex items-center">
                                        <Icon name="cpu-line" class="mr-1 h-3 w-3" />
                                        {{ formatNumber(selectedModelInfo.max_tokens) }} max output
                                    </div>
                                    <div v-if="selectedModelInfo.cost_per_1k_input_tokens" class="flex items-center">
                                        <Icon name="money-dollar-circle-line" class="mr-1 h-3 w-3" />
                                        ${{ selectedModelInfo.cost_per_1k_input_tokens }}/${{ selectedModelInfo.cost_per_1k_output_tokens }} per 1K tokens
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Temperature -->
        <div>
            <div class="settings-row border-b border-gray-100 py-4">
                <div class="settings-label">
                    <div class="label-title flex items-center gap-2">
                        {{ $t('Temperature') }}: {{ localForm.google_temperature }}
                        <div class="relative group">
                            <Icon
                                name="information-line"
                                size="sm"
                                class="text-gray-400 hover:text-gray-600 cursor-help"
                            />
                            <div class="absolute bottom-full left-1/2 transform -translate-x-1/2 mb-2 px-3 py-2 bg-gray-900 text-white text-xs rounded-lg opacity-0 group-hover:opacity-100 transition-opacity duration-200 pointer-events-none whitespace-nowrap z-10">
                                Temperature controls Gemini's response diversity.<br/>
                                0 = Deterministic answers, 1 = More creative responses.
                                <div class="absolute top-full left-1/2 transform -translate-x-1/2 w-0 h-0 border-l-4 border-r-4 border-t-4 border-transparent border-t-gray-900"></div>
                            </div>
                        </div>
                    </div>
                    <div class="label-help">{{ $t('Controls randomness in responses. Lower values are more focused, higher values are more creative.') }}</div>
                </div>
                <div class="settings-control">
                    <RangeSlider
                        v-model="localForm.google_temperature"
                        :min="0"
                        :max="1"
                        :step="0.1"
                        :labels="[
                            '0 (' + $t('Focused') + ')',
                            '0.5 (' + $t('Balanced') + ')',
                            '1 (' + $t('Creative') + ')'
                        ]"
                        color="blue"
                    />
                </div>
            </div>
        </div>

        <!-- Max Tokens -->
        <div>
            <div class="settings-row border-b border-gray-100 py-4">
                <div class="settings-label">
                    <div class="label-title flex items-center gap-2">
                        {{ $t('Max Tokens') }}
                        <div class="relative group">
                            <Icon
                                name="information-line"
                                size="sm"
                                class="text-gray-400 hover:text-gray-600 cursor-help"
                            />
                            <div class="absolute bottom-full left-1/2 transform -translate-x-1/2 mb-2 px-3 py-2 bg-gray-900 text-white text-xs rounded-lg opacity-0 group-hover:opacity-100 transition-opacity duration-200 pointer-events-none whitespace-nowrap z-10">
                                Higher values = longer responses but use more quota.<br/>
                                Lower values = shorter responses and save quota.
                                <div class="absolute top-full left-1/2 transform -translate-x-1/2 w-0 h-0 border-l-4 border-r-4 border-t-4 border-transparent border-t-gray-900"></div>
                            </div>
                        </div>
                    </div>
                    <div class="label-help">{{ $t('Maximum number of tokens in the response. Gemini models support up to 2048 tokens.') }}</div>
                </div>
                <div class="settings-control">
                    <input
                        type="number"
                        min="1"
                        max="2048"
                        v-model="localForm.google_max_tokens"
                        class="form-input w-full"
                        placeholder="1024"
                    />
                </div>
            </div>
        </div>

        <!-- Test Connection -->
        <div v-if="localForm.google_api_key">
            <div class="settings-row border-b border-gray-100 py-4">
                <div class="settings-label">
                    <div class="label-title">{{ $t('Test Connection') }}</div>
                    <div class="label-help">{{ $t('Verify your Google AI API configuration.') }}</div>
                </div>
                <div class="settings-control">
                    <div class="flex items-center gap-4">
                        <button
                            @click="handleTestConnection"
                            :disabled="isTesting"
                            class="btn-success"
                        >
                            <Icon
                                :name="isTesting ? 'loader-line' : 'play-line'"
                                size="sm"
                                :class="{ 'animate-spin': isTesting }"
                                class="mr-2"
                            />
                            {{ isTesting ? $t('Testing...') : $t('Test Connection') }}
                        </button>

                        <div v-if="connectionStatus" class="flex items-center gap-2">
                            <Icon
                                :name="connectionStatus.success ? 'check-line' : 'close-line'"
                                size="sm"
                                :class="connectionStatus.success ? 'text-green-600' : 'text-red-600'"
                            />
                            <span :class="connectionStatus.success ? 'text-green-600' : 'text-red-600'">
                                {{ connectionStatus.message }}
                            </span>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</template>

<script setup>
import { ref, computed } from 'vue'
import Icon from '@/Admin/Components/Icon.vue'
import RangeSlider from '@/Admin/Components/RangeSlider.vue'

const props = defineProps({
    modelValue: {
        type: Object,
        required: true
    },
    isTesting: {
        type: Boolean,
        default: false
    },
    connectionStatus: {
        type: Object,
        default: null
    },
    isConfigured: {
        type: Boolean,
        default: false
    },
    smartDefaults: {
        type: Object,
        default: null
    },
    availableModels: {
        type: Object,
        default: () => ({})
    }
})

const emit = defineEmits(['update:modelValue', 'test-connection'])

// Local reactive state
const showApiKey = ref(false)

// Create a local form object that syncs with the parent
const localForm = computed({
    get: () => props.modelValue,
    set: (value) => emit('update:modelValue', value)
})

const selectedModelInfo = computed(() => {
    const modelKey = localForm.value.google_model
    return modelKey ? props.availableModels[modelKey] : null
})

// Helper function to format numbers
const formatNumber = (num) => {
    if (!num) return '0'
    return new Intl.NumberFormat().format(num)
}

const handleTestConnection = () => {
    emit('test-connection', {
        api_key: localForm.value.google_api_key,
        model: localForm.value.google_model,
        temperature: localForm.value.google_temperature,
        max_tokens: localForm.value.google_max_tokens
    })
}
</script>

<style lang="scss" scoped>
// Settings layout styles
.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-select {
  @apply px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:border-transparent transition-colors bg-white;
}

.form-input {
  @apply focus:ring-blue-500 focus:border-blue-500;
}

.form-select {
  @apply focus:ring-blue-500 focus:border-blue-500;
}

// Button styles
.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;
}

// Range slider styles are now handled by the RangeSlider component
</style>
