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

<PageTitle>Einstellungen - Author Buddy</PageTitle>

<div class="settings-page">

    <div class="settings-section">
        <h3 class="settings-section-title">Benutzer</h3>
        <div class="form-group">
            <label for="userSelect">Aktiver Benutzer:</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">Neuer Benutzer:</label>
            <div style="display: flex; gap: 8px;">
                <input id="newUserName" @bind="newUserName" placeholder="Name" style="flex: 1;" />
                <button class="btn btn-secondary" @onclick="AddUser">Hinzufügen</button>
            </div>
        </div>
    </div>

    <div class="settings-layout">

        <div class="settings-layout-left">
            <div class="settings-section">
                <h3 class="settings-section-title">Modelle</h3>
                <div class="form-group">
                    <label for="ragModel">RAG-Modell (Faktenabfrage):</label>
                    <select id="ragModel" @bind="ragModel">
                        @if (availableModels.Count == 0)
                        {
                            <option value="">Keine Modelle gefunden</option>
                        }
                        @foreach (var m in availableModels)
                        {
                            <option value="@m.Name">@m.Name</option>
                        }
                    </select>
                </div>
                <div class="form-group">
                    <label for="styleModel">Stil-Modell (Lektorat):</label>
                    <select id="styleModel" @bind="styleModel">
                        @if (availableModels.Count == 0)
                        {
                            <option value="">Keine Modelle gefunden</option>
                        }
                        @foreach (var m in availableModels)
                        {
                            <option value="@m.Name">@m.Name</option>
                        }
                    </select>
                </div>
                <div class="form-group">
                    <label for="spellingModel">Rechtschreibprüfungs-Modell:</label>
                    <select id="spellingModel" @bind="spellingModel">
                        @if (availableModels.Count == 0)
                        {
                            <option value="">Keine Modelle gefunden</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">Ollama Server</h3>
                <div class="form-group">
                    <label for="ollamaUrl">Server-URL:</label>
                    <input id="ollamaUrl" @bind="ollamaUrl" placeholder="http://localhost:11434" />
                    <div class="form-hint">Adresse des Ollama-Servers (z. B. http://192.168.1.100:11434)</div>
                </div>
            </div>

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

        <div class="settings-layout-right">
            <div class="settings-section">
                <h3 class="settings-section-title">Lektor-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">Fact-Check-Vorlage</h3>
                <div class="form-group">
                    <textarea id="factCheckTemplate" @bind="factCheckTemplate" rows="6"></textarea>
                </div>
            </div>

            <div class="settings-section">
                <h3 class="settings-section-title">Rechtschreibprüfungs-Prompt</h3>
                <div class="form-group">
                    <textarea id="spellingPrompt" @bind="spellingPrompt" rows="6"></textarea>
                </div>
            </div>
        </div>

    </div>

    <div class="settings-actions">
        <button class="btn btn-primary" @onclick="SaveSettings">Speichern</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 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;

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

        var userSettings = await LoadUserSettingsAsync();

        ragModel = userSettings.ragModel;
        styleModel = userSettings.styleModel;
        spellingModel = userSettings.spellingModel;
        selectedTheme = userSettings.selectedTheme;
        ollamaUrl = userSettings.ollamaUrl;
        lektorPrompt = userSettings.lektorPrompt;
        factCheckTemplate = userSettings.factCheckTemplate;
        spellingPrompt = userSettings.spellingPrompt;

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

    private async Task<(string ragModel, string styleModel, string spellingModel, string selectedTheme, string ollamaUrl, string lektorPrompt, string factCheckTemplate, string spellingPrompt)> LoadUserSettingsAsync()
    {
        return (
            await SettingsService.GetRagModelAsync() ?? "llama3.2",
            await SettingsService.GetStyleModelAsync() ?? "llama3.2",
            await SettingsService.GetSpellingModelAsync() ?? "phi3:mini",
            await SettingsService.GetThemeAsync() ?? "light",
            await SettingsService.GetOllamaUrlAsync() ?? "http://localhost:11434",
            await SettingsService.GetLektorSystemPromptAsync() ?? string.Empty,
            await SettingsService.GetFactCheckTemplateAsync() ?? string.Empty,
            await SettingsService.GetSpellingPromptAsync() ?? string.Empty
        );
    }

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

        var userSettings = await LoadUserSettingsAsync();
        ragModel = userSettings.ragModel;
        styleModel = userSettings.styleModel;
        spellingModel = userSettings.spellingModel;
        selectedTheme = userSettings.selectedTheme;
        ollamaUrl = userSettings.ollamaUrl;
        lektorPrompt = userSettings.lektorPrompt;
        factCheckTemplate = userSettings.factCheckTemplate;
        spellingPrompt = userSettings.spellingPrompt;
    }

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

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

    private async Task SaveSettings()
    {
        await SettingsService.SaveOllamaUrlAsync(ollamaUrl);
        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);
        OllamaService.Reconfigure(ollamaUrl);

        statusMessage = "Einstellungen gespeichert.";
        await ThemeService.ApplyTheme(selectedTheme);
    }
}
