<template>
    <admin-page-header>
        <template #header>
            <a-page-header :title="$t(`menu.ai_settings`)" class="p-0">
                <template #extra>
                    <a-button type="primary" @click="onSubmit" :loading="loading">
                        <template #icon> <SaveOutlined /> </template>
                        {{ $t("common.update") }}
                    </a-button>
                </template>
            </a-page-header>
        </template>
        <template #breadcrumb>
            <a-breadcrumb separator="-" style="font-size: 12px">
                <a-breadcrumb-item>
                    <router-link :to="{ name: 'admin.dashboard.index' }">
                        {{ $t(`menu.dashboard`) }}
                    </router-link>
                </a-breadcrumb-item>
                <a-breadcrumb-item>
                    {{ $t("menu.settings") }}
                </a-breadcrumb-item>
                <a-breadcrumb-item>
                    {{ $t("menu.ai_settings") }}
                </a-breadcrumb-item>
            </a-breadcrumb>
        </template>
    </admin-page-header>

    <a-row>
        <a-col
            :xs="24"
            :sm="24"
            :md="24"
            :lg="4"
            :xl="4"
            :style="{
                background: themeMode == 'dark' ? '#141414' : '#fff',
                borderRight:
                    themeMode == 'dark' ? '1px solid #303030' : '1px solid #f0f0f0',
            }"
        >
            <SettingSidebar />
        </a-col>
        <a-col :xs="24" :sm="24" :md="24" :lg="20" :xl="20">
            <admin-page-table-content>
                <a-card class="page-content-container mt-20 mb-20">
                    <a-form layout="vertical">
                        <a-row :gutter="16">
                            <a-col :span="24">
                                <a-form-item
                                    :label="$t('ai_settings.provider')"
                                    name="provider"
                                    :help="rules.provider ? rules.provider.message : null"
                                    :validateStatus="rules.provider ? 'error' : null"
                                >
                                    <a-select
                                        v-model:value="formData.provider"
                                        :placeholder="$t('ai_settings.select_provider')"
                                        @change="handleProviderChange"
                                    >
                                        <a-select-option key="none" value="none">
                                            {{ $t("ai_settings.none") }}
                                        </a-select-option>
                                        <a-select-opt-group
                                            :label="$t('ai_settings.cloud_providers')"
                                        >
                                            <a-select-option key="openai" value="openai">
                                                {{ $t("ai_settings.openai") }}
                                            </a-select-option>
                                            <a-select-option key="claude" value="claude">
                                                {{ $t("ai_settings.claude") }}
                                            </a-select-option>
                                            <a-select-option
                                                key="perplexity"
                                                value="perplexity"
                                            >
                                                {{ $t("ai_settings.perplexity") }}
                                            </a-select-option>
                                        </a-select-opt-group>
                                        <a-select-opt-group
                                            v-if="isLocalEnv"
                                            :label="$t('ai_settings.self_hosted')"
                                        >
                                            <a-select-option key="ollama" value="ollama">
                                                {{ $t("ai_settings.ollama") }}
                                            </a-select-option>
                                            <a-select-option
                                                key="openai_compatible"
                                                value="openai_compatible"
                                            >
                                                {{ $t("ai_settings.openai_compatible") }}
                                            </a-select-option>
                                        </a-select-opt-group>
                                    </a-select>
                                </a-form-item>
                            </a-col>
                        </a-row>

                        <div v-if="formData.provider && formData.provider !== 'none'">
                            <a-alert
                                :message="$t('ai_settings.configuration')"
                                type="info"
                                show-icon
                                style="margin-bottom: 16px"
                            >
                                <template #description>
                                    {{ $t("ai_settings.config_description") }}
                                    <a
                                        @click="showInstructionsModal"
                                        style="
                                            margin-left: 8px;
                                            cursor: pointer;
                                            text-decoration: underline;
                                        "
                                    >
                                        {{ $t("ai_settings.view_instructions") }}
                                    </a>
                                </template>
                            </a-alert>

                            <!-- Base URL for self-hosted providers -->
                            <a-row :gutter="16" v-if="showBaseUrl">
                                <a-col :xs="24" :sm="24" :md="24" :lg="24">
                                    <a-form-item
                                        :label="$t('ai_settings.base_url')"
                                        name="base_url"
                                        :help="
                                            rules.base_url ? rules.base_url.message : null
                                        "
                                        :validateStatus="rules.base_url ? 'error' : null"
                                        class="required"
                                    >
                                        <a-input
                                            v-model:value="formData.base_url"
                                            :placeholder="
                                                formData.provider === 'ollama'
                                                    ? 'http://localhost:11434'
                                                    : 'https://api.example.com'
                                            "
                                        />
                                        <template #extra>
                                            <span
                                                class="text-gray-500"
                                                v-if="formData.provider === 'ollama'"
                                            >
                                                {{
                                                    $t("ai_settings.ollama_base_url_hint")
                                                }}
                                            </span>
                                            <span class="text-gray-500" v-else>
                                                {{
                                                    $t(
                                                        "ai_settings.openai_compatible_base_url_hint"
                                                    )
                                                }}
                                            </span>
                                        </template>
                                    </a-form-item>
                                </a-col>
                            </a-row>

                            <a-row :gutter="16">
                                <a-col :xs="24" :sm="24" :md="12" :lg="12">
                                    <a-form-item
                                        :label="$t('ai_settings.api_key')"
                                        name="api_key"
                                        :help="
                                            rules.api_key ? rules.api_key.message : null
                                        "
                                        :validateStatus="rules.api_key ? 'error' : null"
                                        :class="{ required: isApiKeyRequired }"
                                    >
                                        <a-input-password
                                            v-model:value="formData.api_key"
                                            :placeholder="
                                                $t('common.placeholder_default_text', [
                                                    $t('ai_settings.api_key'),
                                                ])
                                            "
                                        />
                                        <template #extra v-if="!isApiKeyRequired">
                                            <span class="text-gray-500">
                                                {{ $t("ai_settings.api_key_optional") }}
                                            </span>
                                        </template>
                                    </a-form-item>
                                </a-col>
                                <a-col :xs="24" :sm="24" :md="12" :lg="12">
                                    <a-form-item
                                        :label="$t('ai_settings.model')"
                                        name="model"
                                        :help="rules.model ? rules.model.message : null"
                                        :validateStatus="rules.model ? 'error' : null"
                                        class="required"
                                    >
                                        <a-select
                                            v-if="
                                                formData.provider !== 'ollama' &&
                                                formData.provider !== 'openai_compatible'
                                            "
                                            v-model:value="formData.model"
                                            :placeholder="
                                                $t('common.select_default_text', [
                                                    $t('ai_settings.model'),
                                                ])
                                            "
                                        >
                                            <a-select-option
                                                v-for="(label, value) in currentModels"
                                                :key="value"
                                                :value="value"
                                            >
                                                {{ label }}
                                            </a-select-option>
                                        </a-select>
                                        <a-input
                                            v-else
                                            v-model:value="formData.model"
                                            :placeholder="
                                                formData.provider === 'ollama'
                                                    ? 'llama3.2, mistral, codellama'
                                                    : 'gpt-4o, gpt-3.5-turbo'
                                            "
                                        />
                                        <template
                                            #extra
                                            v-if="formData.provider === 'ollama'"
                                        >
                                            <span class="text-gray-500">
                                                {{ $t("ai_settings.ollama_model_hint") }}
                                            </span>
                                        </template>
                                    </a-form-item>
                                </a-col>
                            </a-row>

                            <a-row :gutter="16">
                                <a-col :xs="24" :sm="24" :md="12" :lg="12">
                                    <a-form-item
                                        :label="$t('ai_settings.max_tokens')"
                                        name="max_tokens"
                                        :help="
                                            rules.max_tokens
                                                ? rules.max_tokens.message
                                                : null
                                        "
                                        :validateStatus="
                                            rules.max_tokens ? 'error' : null
                                        "
                                    >
                                        <a-input-number
                                            v-model:value="formData.max_tokens"
                                            :min="100"
                                            :max="8000"
                                            style="width: 100%"
                                        />
                                    </a-form-item>
                                </a-col>
                            </a-row>
                        </div>

                        <a-row :gutter="16">
                            <a-col :xs="24" :sm="24" :md="24" :lg="24">
                                <a-form-item>
                                    <a-space>
                                        <a-button
                                            type="primary"
                                            @click="onSubmit"
                                            :loading="loading"
                                        >
                                            <template #icon> <SaveOutlined /> </template>
                                            {{ $t("common.update") }}
                                        </a-button>
                                        <a-button
                                            @click="testConnection"
                                            :loading="testLoading"
                                            :disabled="
                                                isApiKeyRequired && !formData.api_key
                                            "
                                        >
                                            <template #icon> <ApiOutlined /> </template>
                                            {{ $t("ai_settings.test_connection") }}
                                        </a-button>
                                    </a-space>
                                </a-form-item>
                            </a-col>
                        </a-row>
                    </a-form>
                </a-card>
            </admin-page-table-content>
        </a-col>
    </a-row>

    <!-- Instructions Modal -->
    <a-modal
        v-model:open="instructionsVisible"
        :title="$t('ai_settings.setup_instructions')"
        :footer="null"
        :width="700"
    >
        <div style="line-height: 1.8">
            <template v-if="formData.provider === 'openai'">
                <h4>{{ $t("ai_settings.openai_step_1") }}</h4>
                <p>
                    {{ $t("ai_settings.openai_step_1_description") }}
                    <a href="https://platform.openai.com/" target="_blank"
                        >platform.openai.com</a
                    >
                </p>

                <h4 style="margin-top: 20px">{{ $t("ai_settings.openai_step_2") }}</h4>
                <ol>
                    <li>{{ $t("ai_settings.openai_step_2_1") }}</li>
                    <li>{{ $t("ai_settings.openai_step_2_2") }}</li>
                    <li>{{ $t("ai_settings.openai_step_2_3") }}</li>
                </ol>
            </template>

            <template v-else-if="formData.provider === 'claude'">
                <h4>{{ $t("ai_settings.claude_step_1") }}</h4>
                <p>
                    {{ $t("ai_settings.claude_step_1_description") }}
                    <a href="https://console.anthropic.com/" target="_blank"
                        >console.anthropic.com</a
                    >
                </p>

                <h4 style="margin-top: 20px">{{ $t("ai_settings.claude_step_2") }}</h4>
                <ol>
                    <li>{{ $t("ai_settings.claude_step_2_1") }}</li>
                    <li>{{ $t("ai_settings.claude_step_2_2") }}</li>
                    <li>{{ $t("ai_settings.claude_step_2_3") }}</li>
                </ol>
            </template>

            <template v-else-if="formData.provider === 'perplexity'">
                <h4>{{ $t("ai_settings.perplexity_step_1") }}</h4>
                <p>
                    {{ $t("ai_settings.perplexity_step_1_description") }}
                    <a href="https://www.perplexity.ai/settings/api" target="_blank"
                        >perplexity.ai/settings/api</a
                    >
                </p>

                <h4 style="margin-top: 20px">
                    {{ $t("ai_settings.perplexity_step_2") }}
                </h4>
                <ol>
                    <li>{{ $t("ai_settings.perplexity_step_2_1") }}</li>
                    <li>{{ $t("ai_settings.perplexity_step_2_2") }}</li>
                    <li>{{ $t("ai_settings.perplexity_step_2_3") }}</li>
                </ol>
            </template>

            <template v-else-if="formData.provider === 'ollama'">
                <h4>{{ $t("ai_settings.ollama_step_1") }}</h4>
                <p>
                    {{ $t("ai_settings.ollama_step_1_description") }}
                    <a href="https://ollama.com/download" target="_blank"
                        >ollama.com/download</a
                    >
                </p>

                <h4 style="margin-top: 20px">{{ $t("ai_settings.ollama_step_2") }}</h4>
                <ol>
                    <li>{{ $t("ai_settings.ollama_step_2_1") }}</li>
                    <li>{{ $t("ai_settings.ollama_step_2_2") }}</li>
                    <li>{{ $t("ai_settings.ollama_step_2_3") }}</li>
                </ol>

                <h4 style="margin-top: 20px">{{ $t("ai_settings.ollama_step_3") }}</h4>
                <ol>
                    <li>{{ $t("ai_settings.ollama_step_3_1") }}</li>
                    <li>{{ $t("ai_settings.ollama_step_3_2") }}</li>
                </ol>

                <a-alert
                    :message="$t('ai_settings.ollama_note')"
                    :description="$t('ai_settings.ollama_note_description')"
                    type="info"
                    show-icon
                    style="margin-top: 20px"
                />
            </template>

            <template v-else-if="formData.provider === 'openai_compatible'">
                <h4>{{ $t("ai_settings.openai_compatible_step_1") }}</h4>
                <p>{{ $t("ai_settings.openai_compatible_step_1_description") }}</p>
                <ul style="margin-top: 10px">
                    <li>
                        <a href="https://groq.com" target="_blank">Groq</a> -
                        {{ $t("ai_settings.groq_description") }}
                    </li>
                    <li>
                        <a href="https://together.ai" target="_blank">Together AI</a> -
                        {{ $t("ai_settings.together_description") }}
                    </li>
                    <li>
                        <a href="https://openrouter.ai" target="_blank">OpenRouter</a> -
                        {{ $t("ai_settings.openrouter_description") }}
                    </li>
                </ul>

                <h4 style="margin-top: 20px">
                    {{ $t("ai_settings.openai_compatible_step_2") }}
                </h4>
                <ol>
                    <li>{{ $t("ai_settings.openai_compatible_step_2_1") }}</li>
                    <li>{{ $t("ai_settings.openai_compatible_step_2_2") }}</li>
                    <li>{{ $t("ai_settings.openai_compatible_step_2_3") }}</li>
                </ol>

                <h4 style="margin-top: 20px">{{ $t("ai_settings.common_base_urls") }}</h4>
                <ul>
                    <li><strong>Groq:</strong> https://api.groq.com/openai/v1</li>
                    <li><strong>Together AI:</strong> https://api.together.xyz/v1</li>
                    <li><strong>OpenRouter:</strong> https://openrouter.ai/api/v1</li>
                </ul>
            </template>

            <a-alert
                :message="$t('ai_settings.security_note')"
                :description="$t('ai_settings.security_note_description')"
                type="warning"
                show-icon
                style="margin-top: 20px"
            />
        </div>
    </a-modal>
</template>

<script setup>
import { onMounted, ref, computed } from "vue";
import { SaveOutlined, ApiOutlined } from "@ant-design/icons-vue";
import { useI18n } from "vue-i18n";
import { message } from "ant-design-vue";
import SettingSidebar from "../SettingSidebar.vue";
import { getUrlByAppType } from "../../../../common/scripts/functions";

const { addEditRequestAdmin, loading, rules } = window.__composables.apiAdmin();
const { themeMode } = window.__composables.common();
const { t } = useI18n();

const formData = ref({
    provider: null,
    api_key: "",
    model: "",
    max_tokens: 2000,
    base_url: "",
});
const openaiModels = ref({});
const claudeModels = ref({});
const perplexityModels = ref({});
const ollamaModels = ref({});
const openaiCompatibleModels = ref({});
const isLocalEnv = ref(false);

// Providers that need base_url
const providersWithBaseUrl = ["ollama", "openai_compatible"];
// Providers that don't require API key
const providersWithoutApiKey = ["ollama"];
const allSettings = ref({});
const instructionsVisible = ref(false);
const testLoading = ref(false);

const currentModels = computed(() => {
    if (formData.value.provider === "openai") {
        return openaiModels.value;
    } else if (formData.value.provider === "claude") {
        return claudeModels.value;
    } else if (formData.value.provider === "perplexity") {
        return perplexityModels.value;
    } else if (formData.value.provider === "ollama") {
        return ollamaModels.value;
    } else if (formData.value.provider === "openai_compatible") {
        return openaiCompatibleModels.value;
    }
    return {};
});

const showBaseUrl = computed(() => {
    return providersWithBaseUrl.includes(formData.value.provider);
});

const isApiKeyRequired = computed(() => {
    return !providersWithoutApiKey.includes(formData.value.provider);
});

onMounted(() => {
    axiosAdmin.get(getUrlByAppType("settings/ai")).then((response) => {
        allSettings.value = response.data.settings;
        openaiModels.value = response.data.openai_models;
        claudeModels.value = response.data.claude_models;
        perplexityModels.value = response.data.perplexity_models;
        ollamaModels.value = response.data.ollama_models || {};
        openaiCompatibleModels.value = response.data.openai_compatible_models || {};
        isLocalEnv.value = response.data.is_local_env || false;

        // Set active provider
        if (response.data.active_provider) {
            formData.value.provider = response.data.active_provider;
            const providerSettings = allSettings.value[response.data.active_provider];
            if (providerSettings) {
                formData.value.api_key = providerSettings.api_key || "";
                formData.value.model = providerSettings.model || "";
                formData.value.max_tokens = providerSettings.max_tokens || 2000;
                formData.value.base_url = providerSettings.base_url || "";
            }
        }
    });
});

const handleProviderChange = (provider) => {
    // Load saved settings for the selected provider
    const providerSettings = allSettings.value[provider];
    if (providerSettings) {
        formData.value.api_key = providerSettings.api_key || "";
        formData.value.model = providerSettings.model || "";
        formData.value.max_tokens = providerSettings.max_tokens || 2000;
        formData.value.base_url = providerSettings.base_url || "";
    } else {
        formData.value.api_key = "";
        formData.value.model = "";
        formData.value.max_tokens = 2000;
        formData.value.base_url = "";
    }

    // Set default model and base_url if not set
    if (!formData.value.model) {
        if (provider === "openai") {
            formData.value.model = "gpt-5.2";
        } else if (provider === "claude") {
            formData.value.model = "claude-sonnet-4-5-20250929";
        } else if (provider === "perplexity") {
            formData.value.model = "sonar";
        } else if (provider === "ollama") {
            formData.value.model = "qwen2.5:7b";
        } else if (provider === "openai_compatible") {
            formData.value.model = "";
        }
    }

    // Set default base_url for self-hosted providers
    if (!formData.value.base_url && provider === "ollama") {
        formData.value.base_url = "http://localhost:11434";
    }
};

const onSubmit = () => {
    addEditRequestAdmin({
        url: getUrlByAppType(`settings/ai/update`),
        data: formData.value,
        successMessage: t("ai_settings.updated"),
        success: (res) => {
            // Update local settings cache
            if (!allSettings.value[formData.value.provider]) {
                allSettings.value[formData.value.provider] = {};
            }
            allSettings.value[formData.value.provider].api_key = formData.value.api_key;
            allSettings.value[formData.value.provider].model = formData.value.model;
            allSettings.value[formData.value.provider].max_tokens =
                formData.value.max_tokens;
            allSettings.value[formData.value.provider].base_url = formData.value.base_url;
        },
    });
};

const testConnection = async () => {
    testLoading.value = true;

    try {
        const response = await axiosAdmin.post(
            getUrlByAppType("settings/ai/test-connection"),
            {
                provider: formData.value.provider,
                api_key: formData.value.api_key,
                model: formData.value.model,
                base_url: formData.value.base_url,
            }
        );

        if (response.data.status === "success") {
            message.success(response.data.message || t("ai_settings.connection_success"));
        } else {
            message.error(response.data.message || t("ai_settings.connection_failed"));
        }
    } catch (error) {
        message.error(
            error.response?.data?.message || t("ai_settings.connection_failed")
        );
    } finally {
        testLoading.value = false;
    }
};

const showInstructionsModal = () => {
    instructionsVisible.value = true;
};
</script>
