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

        <div class="space-y-4">

            <!-- Language Settings -->
            <div>
                <div class="settings-row border-b border-gray-100 py-4">
                    <div class="settings-label">
                        <div class="label-title">{{ $t('Language settings') }}</div>
                        <div class="label-help">{{ $t('Select the language for the chatbot.') }}</div>
                    </div>
                    <div class="settings-control">
                        <el-select v-model="form.language" class="form-select w-full" filterable placeholder="Select language">
                            <el-option
                                v-for="lang in availableLanguages"
                                :key="lang.code"
                                :label="`${lang.language} (${lang.code})`"
                                :value="lang.language_code"
                            />
                        </el-select>
                    </div>
                </div>
            </div>

            <!-- System Prompts Section -->
            <div>
                <div class="settings-row border-b border-gray-100 py-4">
                    <div class="settings-label">
                        <div class="label-title">{{ $t('System Prompts') }}</div>
                        <div class="label-help">{{ $t('Define the system instructions and behavior for the AI assistant. This sets the context and personality of your chatbot.') }}</div>
                    </div>
                    <div class="settings-control">
                        <textarea
                            v-model="form.system_prompts"
                            class="form-textarea w-full"
                            :rows="6"
                            :placeholder="$t('You are a helpful assistant. Answer questions based on the provided context and be professional, friendly, and concise in your responses...')"
                        />
                    </div>
                </div>
            </div>

            <!-- On Error Response Section -->
            <div>
                <div class="settings-row border-b border-gray-100 py-4">
                    <div class="settings-label">
                        <div class="label-title">{{ $t('On Error Response') }}</div>
                        <div class="label-help">{{ $t('Message to display when the AI encounters an error or cannot process a request. This ensures users receive a helpful response even when issues occur.') }}</div>
                    </div>
                    <div class="settings-control">
                        <textarea
                            v-model="form.on_error_response"
                            class="form-textarea w-full"
                            :rows="4"
                            :placeholder="$t('I apologize, but I encountered an issue processing your request. Please try again or contact our support team if the problem persists.')"
                        />
                    </div>
                </div>
            </div>

            <!-- Actions -->
            <div class="flex items-center justify-end pt-2">
                <BaseButton
                    variant="primary"
                    :loading="state.loading.saving"
                    :disabled="state.loading.page || state.loading.saving"
                    @click="onSave"
                >
                    {{ $t('Save Settings') }}
                </BaseButton>
            </div>
        </div>
    </div>
</template>

<script setup>
import { computed, onMounted, reactive } from 'vue'
import BaseButton from '@/Admin/Components/BaseButton.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: false,
        saving: false
    }
})

// Form defaults
const makeDefaults = () => ({
    system_prompts: 'You are a helpful AI assistant. Provide accurate, professional, and friendly responses based on the available context. Be concise and clear in your explanations.',
    on_error_response: 'I apologize, but I encountered an issue processing your request. Please try again or contact our support team if the problem persists.',
    language: 'en'
})

const form = useForm(makeDefaults())

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

const availableLanguages = computed(()=> window.zenochatbot_admin?.languages || []);

// API calls
const loadSettings = async () => {
    try {
        state.loading.page = true
        const response = await Http.get('general-settings')

        if (response.success && response.data) {
            form.fill({
                system_prompts: response.data.system_prompts || makeDefaults().system_prompts,
                on_error_response: response.data.on_error_response || makeDefaults().on_error_response,
                language: response.data.language || 'en'
            })
        }
    } catch (error) {
        showError('Failed to load general settings. Please refresh the page.')
    } finally {
        state.loading.page = false
    }
}

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

        const response = await Http.post('general-settings', {
            system_prompts: form.system_prompts,
            on_error_response: form.on_error_response,
            language: form.language
        })

        if (response.success) {
            showSuccess('General settings saved successfully!')
        } else {
            throw new Error(response.message || 'Failed to save settings')
        }
    } catch (error) {
        console.error('Failed to save general settings:', error)
        showError(error.message || 'Failed to save general settings. Please try again.')
    } finally {
        state.loading.saving = false
    }
}

// Initialize
onMounted(loadSettings)
</script>

<style lang="scss" scoped>
/* Settings two-column row layout - matching ChatSettings design */
.settings-row {
  @apply grid grid-cols-1 md:grid-cols-12 items-center gap-6;
}

.settings-label {
  @apply md:col-span-5 flex flex-col justify-center;
}

.settings-control {
  @apply md:col-span-7 flex items-center;
}

.label-title {
  @apply text-sm md:text-base font-medium text-gray-800;
}

.label-help {
  @apply text-xs text-gray-500 mt-1;
}

.form-textarea {
  @apply px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:ring-blue-500 focus:border-blue-500 text-sm;
}
</style>

