@page "/settings"
@attribute [Authorize]
@inject ISettingsService SettingsService
@inject IThemeService ThemeService
@inject IOllamaService OllamaService
@inject NavigationManager Navigation
@inject IJSRuntime JSRuntime
@inject IProjectService ProjectService

<PageTitle>@T("Einstellungen", "Settings") - Author Buddy</PageTitle>

<div class="settings-page">

    <div class="settings-section">
        <h3 class="settings-section-title">@T("Benutzer", "User")</h3>
        <div class="form-group">
            <label for="userSelect">@T("Aktiver Benutzer:", "Active user:")</label>
            <select id="userSelect" value="@selectedUserId" @onchange="SwitchUser">
                @foreach (var u in users)
                {
                    <option value="@u.Id">@u.Name</option>
                }
            </select>
        </div>
        <div class="form-group">
            <label for="newUserName">@T("Neuer Benutzer:", "New user:")</label>
            <div style="display: flex; gap: 8px;">
                <input id="newUserName" @bind="newUserName" placeholder="@T("Name", "Name")" style="flex: 1;" />
                <button class="btn btn-secondary" @onclick="AddUser">@T("Hinzuf\u00fcgen", "Add")</button>
            </div>
        </div>
    </div>

    <div class="settings-section" style="margin-bottom:16px;">
        <button class="btn btn-secondary" @onclick='() => Navigation.NavigateTo("/setup-2fa")'>@T("2FA einrichten", "Set up 2FA")</button>
    </div>

    <div class="settings-layout">

        <div class="settings-column" >
            <div class="settings-section">
                <h3 class="settings-section-title">@T("Modelle", "Models")</h3>
                <div class="form-group">
                    <label for="ragModel">@T("RAG-Modell (Faktenabfrage):", "RAG model (facts):")</label>
                    <select id="ragModel" @bind="ragModel">
                        @if (availableModels.Count == 0)
                        {
                            <option value="">@T("Keine Modelle gefunden", "No models found")</option>
                        }
                        @foreach (var m in availableModels)
                        {
                            <option value="@m.Name">@m.Name</option>
                        }
                    </select>
                </div>
                <div class="form-group">
                    <label for="styleModel">@T("Stil-Modell (Lektorat):", "Style model (editing):")</label>
                    <select id="styleModel" @bind="styleModel">
                        @if (availableModels.Count == 0)
                        {
                            <option value="">@T("Keine Modelle gefunden", "No models found")</option>
                        }
                        @foreach (var m in availableModels)
                        {
                            <option value="@m.Name">@m.Name</option>
                        }
                    </select>
                </div>
                <div class="form-group">
                    <label for="spellingModel">@T("Rechtschreibpr\u00fcfungs-Modell:", "Spell check model:")</label>
                    <select id="spellingModel" @bind="spellingModel">
                        @if (availableModels.Count == 0)
                        {
                            <option value="">@T("Keine Modelle gefunden", "No models found")</option>
                        }
                        @foreach (var m in availableModels)
                        {
                            <option value="@m.Name">@m.Name</option>
                        }
                    </select>
                </div>
            </div>

            <div class="settings-section">
                <h3 class="settings-section-title">@T("Ollama Server", "Ollama Server")</h3>
                <div class="form-group">
                    <label for="ollamaUrl">@T("Server-URL:", "Server URL:")</label>
                    <input id="ollamaUrl" @bind="ollamaUrl" placeholder="http://localhost:11434" />
                    <div class="form-hint">@T("Adresse des Ollama-Servers", "Ollama server address")</div>
                </div>
            </div>

            <div class="settings-section">
                <h3 class="settings-section-title">@T("Design", "Appearance")</h3>
                <div class="form-group">
                    <label for="themeSelect">@T("Theme:", "Theme:")</label>
                    <select id="themeSelect" @bind="selectedTheme">
                        <option value="light">@T("Hell", "Light")</option>
                        <option value="dark">@T("Dunkel", "Dark")</option>
                        <option value="w95">W95 @T("(Retro)", "(Retro)")</option>
                    </select>
                </div>
            </div>

            <div class="settings-section">
                <h3 class="settings-section-title">@T("Sprache", "Language")</h3>
                <div class="form-group">
                    <label for="languageSelect">@T("Sprache:", "Language:")</label>
                    <select id="languageSelect" @bind="selectedLanguage">
                        <option value="de">Deutsch</option>
                        <option value="en">English</option>
                    </select>
                </div>
            </div>
        </div>

        <div class="settings-column" >
            <div class="settings-section">
                <h3 class="settings-section-title">@T("Lektor-System-Prompt", "Editor system prompt")</h3>
                <div class="form-group">
                    <textarea id="lektorPrompt" @bind="lektorPrompt" rows="6"></textarea>
                </div>
            </div>

            <div class="settings-section">
                <h3 class="settings-section-title">@T("Fact-Check-Vorlage", "Fact check template")</h3>
                <div class="form-group">
                    <textarea id="factCheckTemplate" @bind="factCheckTemplate" rows="6"></textarea>
                </div>
            </div>

            <div class="settings-section">
                <h3 class="settings-section-title">@T("Rechtschreibpr\u00fcfungs-Prompt", "Spell check prompt")</h3>
                <div class="form-group">
                    <textarea id="spellingPrompt" @bind="spellingPrompt" rows="6"></textarea>
                </div>
            </div>
        </div>

        <div class="settings-column" >
            <div class="settings-section">
                <h3 class="settings-section-title">@T("Advocatus Diaboli", "Advocatus Diaboli")</h3>
                <div class="form-group">
                    <textarea id="advocatusDiaboliPrompt" @bind="advocatusDiaboliPrompt" rows="6"></textarea>
                </div>
            </div>

            <div class="settings-section">
                <h3 class="settings-section-title">@T("Hook-Finder", "Hook finder")</h3>
                <div class="form-group">
                    <textarea id="hookFinderPrompt" @bind="hookFinderPrompt" rows="6"></textarea>
                </div>
            </div>

            <div class="settings-section">
                <h3 class="settings-section-title">@T("ELI5-Vereinfachung", "ELI5-Simplification")</h3>
                <div class="form-group">
                    <textarea id="eli5Prompt" @bind="eli5Prompt" rows="6"></textarea>
                </div>
            </div>
        </div>

    </div>

    <div class="settings-actions">
        <button class="btn btn-primary" @onclick="SaveSettings">@T("Speichern", "Save")</button>
        @if (!string.IsNullOrEmpty(statusMessage))
        {
            <span class="settings-status">@statusMessage</span>
        }
    </div>

</div>

@code {
    private string ragModel = "llama3.2";
    private string styleModel = "llama3.2";
    private string spellingModel = "phi3:mini";
    private string selectedTheme = "light";
    private string ollamaUrl = "http://localhost:11434";
    private string lektorPrompt = string.Empty;
    private string factCheckTemplate = string.Empty;
    private string spellingPrompt = string.Empty;
    private string advocatusDiaboliPrompt = string.Empty;
    private string hookFinderPrompt = string.Empty;
    private string eli5Prompt = string.Empty;
    private string selectedLanguage = "de";
    private string newProjectName = string.Empty;
    private string newUserName = string.Empty;
    private string statusMessage = string.Empty;
    private List<LLM_Model> availableModels = new();
    private List<UserEntity> users = new();
    private int selectedUserId;

    private string T(string de, string en) => selectedLanguage == "en" ? en : de;

    protected override async Task OnInitializedAsync()
    {
        users = await SettingsService.GetUsersAsync();
        var current = await SettingsService.GetCurrentUserAsync();
        selectedUserId = current.Id;

        await LoadUserSettings();

        try
        {
            var models = await OllamaService.GetLocalModelsAsync();
            availableModels = models.ToList();
        }
        catch
        {
            availableModels = new();
        }
    }

    private async Task LoadUserSettings()
    {
        ragModel = await SettingsService.GetRagModelAsync() ?? "llama3.2";
        styleModel = await SettingsService.GetStyleModelAsync() ?? "llama3.2";
        spellingModel = await SettingsService.GetSpellingModelAsync() ?? "phi3:mini";
        selectedTheme = await SettingsService.GetThemeAsync() ?? "light";
        ollamaUrl = await SettingsService.GetOllamaUrlAsync() ?? "http://localhost:11434";
        lektorPrompt = await SettingsService.GetLektorSystemPromptAsync() ?? string.Empty;
        factCheckTemplate = await SettingsService.GetFactCheckTemplateAsync() ?? string.Empty;
        spellingPrompt = await SettingsService.GetSpellingPromptAsync() ?? string.Empty;
        advocatusDiaboliPrompt = await SettingsService.GetAdvocatusDiaboliPromptAsync() ?? string.Empty;
        hookFinderPrompt = await SettingsService.GetHookFinderPromptAsync() ?? string.Empty;
        eli5Prompt = await SettingsService.GetEli5PromptAsync() ?? string.Empty;
        selectedLanguage = await SettingsService.GetLanguageAsync() ?? "de";
    }

    private async Task SwitchUser(ChangeEventArgs e)
    {
        var userId = int.Parse(e.Value?.ToString() ?? "0");
        await SettingsService.SetCurrentUserAsync(userId);
        selectedUserId = userId;

        await LoadUserSettings();
    }

    private async Task AddUser()
    {
        if (string.IsNullOrWhiteSpace(newUserName)) return;

        var user = await SettingsService.CreateUserAsync(newUserName);
        users.Add(user);
        newUserName = string.Empty;
        statusMessage = T($"Benutzer '{user.Name}' erstellt.", $"User '{user.Name}' created.");
    }

    private async Task SaveSettings()
    {
        await SettingsService.SaveOllamaUrlAsync(ollamaUrl);
        OllamaService.Reconfigure(ollamaUrl);

        if (!string.IsNullOrWhiteSpace(ragModel))
        {
            var ok = await OllamaService.TestEmbeddingAsync(ragModel);
            if (!ok)
            {
                statusMessage = selectedLanguage == "en"
                    ? $"Model '{ragModel}' does not support embeddings. RAG model not saved."
                    : $"Modell '{ragModel}' unterstützt keine Embeddings. RAG-Modell nicht gespeichert.";
                return;
            }
        }
        await SettingsService.SaveRagModelAsync(ragModel);
        await SettingsService.SaveStyleModelAsync(styleModel);
        await SettingsService.SaveSpellingModelAsync(spellingModel);
        await SettingsService.SaveThemeAsync(selectedTheme);
        await SettingsService.SaveLektorSystemPromptAsync(lektorPrompt);
        await SettingsService.SaveFactCheckTemplateAsync(factCheckTemplate);
        await SettingsService.SaveSpellingPromptAsync(spellingPrompt);
        await SettingsService.SaveAdvocatusDiaboliPromptAsync(advocatusDiaboliPrompt);
        await SettingsService.SaveHookFinderPromptAsync(hookFinderPrompt);
        await SettingsService.SaveEli5PromptAsync(eli5Prompt);
        await SettingsService.SaveLanguageAsync(selectedLanguage);

        statusMessage = T("Einstellungen gespeichert.", "Settings saved.");
        await ThemeService.ApplyTheme(selectedTheme);
    }
}
