{% extends "layouts/app.html" %}
{% from "components/card.html" import stat_card %}

{% block title %}Settings - LLM Monitor{% endblock %}

{% block main_content %}
<div class="space-y-8" x-data="settingsApp()">
    <!-- Page Title -->
    <div class="flex items-center justify-between flex-wrap gap-4">
        <div>
            <h1 class="text-3xl font-bold text-gray-900">Settings</h1>
            <p class="mt-2 text-gray-600">Configure pricing and application settings</p>
        </div>

        <div class="flex gap-2">
            <!-- Refresh Button -->
            <button onclick="window.location.reload()"
                    class="px-4 py-2 bg-gray-200 text-gray-700 rounded-lg hover:bg-gray-300 transition-colors flex items-center gap-2">
                <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15"></path>
                </svg>
                Refresh
            </button>
        </div>
    </div>

    <!-- Pricing Configuration Section -->
    <div class="bg-white rounded-lg shadow-sm border border-gray-200">
        <div class="p-6 border-b border-gray-200">
            <h2 class="text-xl font-semibold text-gray-900">Model Pricing Configuration</h2>
            <p class="mt-1 text-sm text-gray-600">
                Set custom pricing per million tokens for each model. Changes will be applied to all cost calculations.
            </p>
        </div>

        <div class="p-6">
            <!-- Custom Pricing Notice -->
            <div x-show="hasCustomPricing" class="mb-6 bg-blue-50 border border-blue-200 rounded-lg p-4">
                <div class="flex items-start gap-3">
                    <svg class="w-5 h-5 text-blue-600 mt-0.5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"></path>
                    </svg>
                    <div>
                        <p class="text-sm font-medium text-blue-800">Custom Pricing Active</p>
                        <p class="text-sm text-blue-700 mt-1">
                            You have <span x-text="Object.keys(customPricing).length"></span> model(s) with custom pricing configured.
                        </p>
                    </div>
                </div>
            </div>

            <!-- Models Grid -->
            <div class="grid grid-cols-1 lg:grid-cols-2 gap-6">
                <template x-for="(pricing, modelId) in allPricing" :key="modelId">
                    <div class="border border-gray-200 rounded-lg p-4 hover:border-gray-300 transition-colors"
                         :class="customPricing[modelId] ? 'border-blue-300 bg-blue-50' : ''">
                        <div class="flex items-start justify-between mb-4">
                            <div class="flex-1">
                                <h3 class="font-medium text-gray-900" x-text="getModelDisplayName(modelId)"></h3>
                                <p class="text-xs text-gray-500 mt-1" x-text="modelId"></p>
                            </div>
                            <div class="flex items-center gap-2">
                                <span x-show="customPricing[modelId]"
                                      class="inline-flex items-center px-2 py-1 rounded text-xs font-medium bg-blue-100 text-blue-800">
                                    Custom
                                </span>
                                <button x-show="customPricing[modelId]"
                                        @click="resetModelPricing(modelId)"
                                        class="text-xs text-red-600 hover:text-red-800 font-medium">
                                    Reset to Default
                                </button>
                            </div>
                        </div>

                        <!-- Pricing Form -->
                        <div class="space-y-3">
                            <div>
                                <label class="block text-xs font-medium text-gray-700 mb-1">
                                    Input (per million tokens)
                                </label>
                                <div class="flex items-center gap-2">
                                    <span class="text-gray-500 text-sm">$</span>
                                    <input type="number"
                                           step="0.01"
                                           min="0"
                                           x-model="editablePricing[modelId].input_per_mtok"
                                           @change="updateModelPricing(modelId)"
                                           class="flex-1 rounded border-gray-300 border py-1.5 px-3 text-sm focus:ring-2 focus:ring-[#0770E3] focus:border-[#0770E3]">
                                </div>
                            </div>

                            <div>
                                <label class="block text-xs font-medium text-gray-700 mb-1">
                                    Output (per million tokens)
                                </label>
                                <div class="flex items-center gap-2">
                                    <span class="text-gray-500 text-sm">$</span>
                                    <input type="number"
                                           step="0.01"
                                           min="0"
                                           x-model="editablePricing[modelId].output_per_mtok"
                                           @change="updateModelPricing(modelId)"
                                           class="flex-1 rounded border-gray-300 border py-1.5 px-3 text-sm focus:ring-2 focus:ring-[#0770E3] focus:border-[#0770E3]">
                                </div>
                            </div>

                            <div>
                                <label class="block text-xs font-medium text-gray-700 mb-1">
                                    Cache Write (per million tokens)
                                </label>
                                <div class="flex items-center gap-2">
                                    <span class="text-gray-500 text-sm">$</span>
                                    <input type="number"
                                           step="0.01"
                                           min="0"
                                           x-model="editablePricing[modelId].cache_write_per_mtok"
                                           @change="updateModelPricing(modelId)"
                                           class="flex-1 rounded border-gray-300 border py-1.5 px-3 text-sm focus:ring-2 focus:ring-[#0770E3] focus:border-[#0770E3]">
                                </div>
                            </div>

                            <div>
                                <label class="block text-xs font-medium text-gray-700 mb-1">
                                    Cache Read (per million tokens)
                                </label>
                                <div class="flex items-center gap-2">
                                    <span class="text-gray-500 text-sm">$</span>
                                    <input type="number"
                                           step="0.01"
                                           min="0"
                                           x-model="editablePricing[modelId].cache_read_per_mtok"
                                           @change="updateModelPricing(modelId)"
                                           class="flex-1 rounded border-gray-300 border py-1.5 px-3 text-sm focus:ring-2 focus:ring-[#0770E3] focus:border-[#0770E3]">
                                </div>
                            </div>

                            <!-- Status Message -->
                            <div x-show="saveStatus[modelId]" class="text-xs">
                                <span x-show="saveStatus[modelId] === 'saving'"
                                      class="text-blue-600">Saving...</span>
                                <span x-show="saveStatus[modelId] === 'saved'"
                                      class="text-green-600">✓ Saved</span>
                                <span x-show="saveStatus[modelId] === 'error'"
                                      class="text-red-600">✗ Error saving</span>
                            </div>
                        </div>
                    </div>
                </template>
            </div>
        </div>
    </div>
</div>

<script>
function settingsApp() {
    return {
        allPricing: {{ pricing.all_pricing | tojson | safe }},
        customPricing: {{ pricing.custom_pricing | tojson | safe }},
        hasCustomPricing: {{ pricing.has_custom_pricing | lower }},
        editablePricing: {},
        saveStatus: {},

        init() {
            // Initialize editable pricing with current values
            this.editablePricing = JSON.parse(JSON.stringify(this.allPricing));
        },

        getModelDisplayName(modelId) {
            const displayNames = {
                'claude-opus-4-5-20251101': 'Claude Opus 4.5',
                'claude-opus-4-20250514': 'Claude Opus 4',
                'claude-sonnet-4-5-20250929': 'Claude Sonnet 4.5',
                'claude-sonnet-4-20250514': 'Claude Sonnet 4',
                'claude-haiku-4-5-20251001': 'Claude Haiku 4.5',
                'eu.anthropic.claude-sonnet-4-5-20250929-v1:0': 'Claude Sonnet 4.5 (Bedrock EU)',
                'us.anthropic.claude-sonnet-4-5-20250929-v1:0': 'Claude Sonnet 4.5 (Bedrock US)',
                'anthropic.claude-sonnet-4-5-20250929-v1:0': 'Claude Sonnet 4.5 (Bedrock)',
                'eu.anthropic.claude-opus-4-20250514-v1:0': 'Claude Opus 4 (Bedrock EU)',
                'us.anthropic.claude-opus-4-20250514-v1:0': 'Claude Opus 4 (Bedrock US)',
                'anthropic.claude-opus-4-20250514-v1:0': 'Claude Opus 4 (Bedrock)',
                'eu.anthropic.claude-opus-4-5-20251101-v1:0': 'Claude Opus 4.5 (Bedrock EU)',
                'us.anthropic.claude-opus-4-5-20251101-v1:0': 'Claude Opus 4.5 (Bedrock US)',
                'anthropic.claude-opus-4-5-20251101-v1:0': 'Claude Opus 4.5 (Bedrock)',
                'eu.anthropic.claude-haiku-4-5-20251001-v1:0': 'Claude Haiku 4.5 (Bedrock EU)',
                'us.anthropic.claude-haiku-4-5-20251001-v1:0': 'Claude Haiku 4.5 (Bedrock US)',
                'anthropic.claude-haiku-4-5-20251001-v1:0': 'Claude Haiku 4.5 (Bedrock)',
            };
            return displayNames[modelId] || modelId;
        },

        async updateModelPricing(modelId) {
            const pricing = this.editablePricing[modelId];
            this.saveStatus[modelId] = 'saving';

            try {
                const response = await fetch('/api/settings/pricing/update', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({
                        model: modelId,
                        input_per_mtok: parseFloat(pricing.input_per_mtok),
                        output_per_mtok: parseFloat(pricing.output_per_mtok),
                        cache_write_per_mtok: parseFloat(pricing.cache_write_per_mtok),
                        cache_read_per_mtok: parseFloat(pricing.cache_read_per_mtok),
                    }),
                });

                const data = await response.json();

                if (data.success) {
                    this.saveStatus[modelId] = 'saved';
                    // Update custom pricing tracking
                    if (!this.customPricing[modelId]) {
                        this.customPricing[modelId] = pricing;
                        this.hasCustomPricing = true;
                    }
                    // Clear status after delay
                    setTimeout(() => {
                        if (this.saveStatus[modelId] === 'saved') {
                            this.saveStatus[modelId] = null;
                        }
                    }, 2000);
                } else {
                    this.saveStatus[modelId] = 'error';
                }
            } catch (error) {
                console.error('Error updating pricing:', error);
                this.saveStatus[modelId] = 'error';
            }
        },

        async resetModelPricing(modelId) {
            if (!confirm(`Reset pricing for ${this.getModelDisplayName(modelId)} to default values?`)) {
                return;
            }

            try {
                const response = await fetch('/api/settings/pricing/reset', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({
                        model: modelId,
                    }),
                });

                const data = await response.json();

                if (data.success) {
                    // Update editable pricing to default
                    this.editablePricing[modelId] = {...data.pricing};
                    // Remove from custom pricing tracking
                    delete this.customPricing[modelId];
                    this.hasCustomPricing = Object.keys(this.customPricing).length > 0;
                } else {
                    alert('Failed to reset pricing: ' + (data.error || 'Unknown error'));
                }
            } catch (error) {
                console.error('Error resetting pricing:', error);
                alert('Failed to reset pricing. Please try again.');
            }
        },
    };
}
</script>
{% endblock %}
