@page "/profile"
@using Microsoft.AspNetCore.Authorization
@using Microsoft.AspNetCore.Components.Authorization
@using Microsoft.Extensions.Configuration
@attribute [Authorize]
@inject ISessionStore SessionStore
@inject AuthorizedSessionService AuthorizedSessionService
@inject IConfiguration Configuration
@inject NavigationManager Navigation

<PageTitle>Профиль — GM-Relay</PageTitle>

<div class="page-container">
    <ul class="gm-breadcrumb animate-fade-in">
        <li><a href="/">Главная</a></li>
        <li class="active">Профиль</li>
    </ul>

    <div class="page-header animate-fade-in">
        <h2>Профиль</h2>
        <p>Управление публичным профилем мастера и связанными аккаунтами.</p>
    </div>

    @if (!string.IsNullOrWhiteSpace(errorMessage))
    {
        <div class="gm-alert gm-alert-danger animate-fade-in" style="margin-bottom: 1rem;">
            @errorMessage
        </div>
    }

    @if (!string.IsNullOrWhiteSpace(successMessage))
    {
        <div class="gm-alert gm-alert-success animate-fade-in" style="margin-bottom: 1rem;">
            @successMessage
        </div>
    }

    @if (masterProfile is null)
    {
        <div class="glass-card animate-fade-in" style="padding: 2rem; margin-bottom: 1rem;">
            <div class="skeleton skeleton-text" style="width: 60%; margin-bottom: 1rem;"></div>
            <div class="skeleton skeleton-text" style="width: 80%; margin-bottom: 0.75rem;"></div>
            <div class="skeleton skeleton-text" style="width: 40%;"></div>
        </div>
    }
    else
    {
        <div class="glass-card animate-slide-up" style="margin-bottom: 1rem;">
            <div class="profile-card-header">
                <div>
                    <h3>Публичный профиль мастера</h3>
                    <p>Показывается в каталоге, опубликованных играх и публичных страницах клуба.</p>
                </div>
                <span class="status-badge @(masterProfile.IsPublic ? "status-success" : "status-neutral")">
                    @(masterProfile.IsPublic ? "Публичный" : "Скрыт")
                </span>
            </div>

            <EditForm Model="@masterProfileModel" OnValidSubmit="SaveMasterProfile">
                <div class="gm-form-group public-toggle-field">
                    <label class="gm-checkbox-label">
                        <InputCheckbox @bind-Value="masterProfileModel.IsPublic" />
                        <span>Опубликовать профиль</span>
                    </label>
                </div>

                <div class="profile-form-grid">
                    <div class="gm-form-group">
                        <label class="gm-form-label">Имя в публичном профиле</label>
                        <InputText @bind-Value="masterProfileModel.DisplayName" class="gm-form-control" />
                    </div>
                    <div class="gm-form-group">
                        <label class="gm-form-label">Короткий адрес</label>
                        <InputText @bind-Value="masterProfileModel.PublicSlug" class="gm-form-control" />
                        <div class="gm-form-hint">Латиница, цифры и дефисы, например "night-city-gm".</div>
                    </div>
                </div>

                <div class="gm-form-group">
                    <label class="gm-form-label">Описание</label>
                    <InputTextArea @bind-Value="masterProfileModel.Bio" class="gm-form-control master-profile-bio" />
                </div>

                <div class="public-settings-actions">
                    <button type="submit" class="btn-gm btn-gm-primary" disabled="@savingMasterProfile">
                        @(savingMasterProfile ? "Сохраняем..." : "Сохранить профиль")
                    </button>
                    @if (PublicMasterProfileUrl is not null)
                    {
                        <a href="@PublicMasterProfileUrl" target="_blank" rel="noopener noreferrer" class="btn-gm btn-gm-outline">
                            Открыть публичный профиль
                        </a>
                    }
                </div>
            </EditForm>

            @if (PublicMasterProfileUrl is not null)
            {
                <div class="public-link-row">
                    <span>Ссылка профиля</span>
                    <a href="@PublicMasterProfileUrl" target="_blank" rel="noopener noreferrer">@PublicMasterProfileUrl</a>
                </div>
            }
        </div>
    }

    <div class="glass-card animate-slide-up" style="margin-bottom: 1rem;">
        <div class="batch-bulk-header">
            <div>
                <h3>Связанные аккаунты</h3>
                <p>Аккаунты Telegram и Discord, привязанные к вашему профилю.</p>
            </div>
        </div>

        @if (identities is null)
        {
            <div class="skeleton skeleton-text" style="width: 70%; margin-bottom: 0.75rem;"></div>
            <div class="skeleton skeleton-text" style="width: 50%;"></div>
        }
        else if (identities.Count == 0)
        {
            <div class="empty-state empty-state-compact">
                <div class="empty-state-title">Аккаунты не найдены</div>
                <p class="empty-state-text">Привяжите Telegram или Discord, чтобы управлять профилем.</p>
            </div>
        }
        else
        {
            <ul class="identity-list">
                @foreach (var id in identities)
                {
                    <li class="identity-item">
                        <div class="identity-info">
                            <span class="identity-platform">@id.Platform</span>
                            <span class="identity-name">@id.DisplayName</span>
                        </div>
                        @if (id.Platform != currentPlatform || id.ExternalUserId != currentExternalUserId)
                        {
                            <button class="btn-gm btn-gm-danger"
                                    @onclick="() => Unlink(id.Platform, id.ExternalUserId)"
                                    disabled="@isUnlinking">
                                Отвязать
                            </button>
                        }
                        else
                        {
                            <span class="status-badge status-success">Текущий</span>
                        }
                    </li>
                }
            </ul>
        }
    </div>

    <div class="glass-card animate-slide-up">
        <div class="batch-bulk-header">
            <div>
                <h3>Добавить аккаунт</h3>
                <p>Привяжите дополнительные платформы для входа.</p>
            </div>
        </div>

        @if (!HasLinkedPlatform("Discord"))
        {
            <a href="/auth/discord" class="login-btn-discord" style="margin-bottom: 0.75rem;">
                <svg class="login-btn-icon" viewBox="0 0 24 24" fill="currentColor">
                    <path d="M20.317 4.37a19.791 19.791 0 0 0-4.885-1.515.074.074 0 0 0-.079.037c-.21.375-.444.864-.608 1.25a18.27 18.27 0 0 0-5.487 0 12.64 12.64 0 0 0-.617-1.25.077.077 0 0 0-.079-.037A19.736 19.736 0 0 0 3.677 4.37a.07.07 0 0 0-.032.027C.533 9.046-.32 13.58.099 18.057a.082.082 0 0 0 .031.057 19.9 19.9 0 0 0 5.993 3.03.078.078 0 0 0 .084-.028c.462-.63.874-1.295 1.226-1.994a.076.076 0 0 0-.041-.106 13.107 13.107 0 0 1-1.872-.892.077.077 0 0 1-.008-.128 10.2 10.2 0 0 0 .372-.292.074.074 0 0 1 .077-.01c3.928 1.793 8.18 1.793 12.062 0a.074.074 0 0 1 .078.01c.12.098.246.198.373.292a.077.077 0 0 1-.006.127 12.299 12.299 0 0 1-1.873.892.077.077 0 0 0-.041.107c.36.698.772 1.362 1.225 1.993a.076.076 0 0 0 .084.028 19.839 19.839 0 0 0 6.002-3.03.077.077 0 0 0 .032-.054c.5-5.177-.838-9.674-3.549-13.66a.061.061 0 0 0-.031-.03zM8.02 15.33c-1.183 0-2.157-1.085-2.157-2.419 0-1.333.956-2.419 2.157-2.419 1.21 0 2.176 1.096 2.157 2.42 0 1.333-.956 2.418-2.157 2.418zm7.975 0c-1.183 0-2.157-1.085-2.157-2.419 0-1.333.955-2.419 2.157-2.419 1.21 0 2.176 1.096 2.157 2.42 0 1.333-.946 2.418-2.157 2.418z"/>
                </svg>
                Привязать Discord
            </a>
        }
        else
        {
            <p style="color: var(--text-muted); margin-bottom: 0.75rem;">Discord уже привязан.</p>
        }

        @if (currentPlatform == "Discord" && !HasLinkedPlatform("Telegram"))
        {
            var botUsername = Configuration["Telegram__BotUsername"] ?? Configuration["Telegram:BotUsername"];
            if (!string.IsNullOrWhiteSpace(botUsername))
            {
                var authUrl = new Uri(new Uri(Navigation.BaseUri), "auth/telegram").ToString();
                var widgetHtml = $"<script async src=\"https://telegram.org/js/telegram-widget.js?22\" data-telegram-login=\"{botUsername}\" data-size=\"large\" data-auth-url=\"{authUrl}\" data-request-access=\"write\"></script>";
                <div class="telegram-widget-wrapper">
                    @((MarkupString)widgetHtml)
                </div>
            }
        }
    </div>
</div>

@code {
    private List<LinkedIdentity>? identities;
    private MasterProfileSettings? masterProfile;
    private string? currentPlatform;
    private string? currentExternalUserId;
    private bool isUnlinking;
    private bool savingMasterProfile;
    private string? errorMessage;
    private string? successMessage;
    private MasterProfileEditModel masterProfileModel = new();

    [CascadingParameter]
    private Task<AuthenticationState>? AuthenticationStateTask { get; set; }

    [SupplyParameterFromQuery]
    public string? Linked { get; set; }

    [SupplyParameterFromQuery(Name = "link_error")]
    public string? LinkError { get; set; }

    protected override async Task OnInitializedAsync()
    {
        if (AuthenticationStateTask is not null)
        {
            var authState = await AuthenticationStateTask;
            var user = authState.User;
            if (user.TryGetPlatformIdentity(out var plat, out var extId))
            {
                currentPlatform = plat;
                currentExternalUserId = extId;
            }
        }

        if (!string.IsNullOrWhiteSpace(Linked))
        {
            successMessage = $"{Linked} аккаунт успешно привязан!";
        }

        if (!string.IsNullOrWhiteSpace(LinkError))
        {
            errorMessage = $"Ошибка привязки: {Uri.UnescapeDataString(LinkError)}";
        }

        await LoadIdentities();
        await LoadMasterProfile();
    }

    private async Task LoadIdentities()
    {
        try
        {
            if (currentPlatform is not null && currentExternalUserId is not null)
            {
                identities = await SessionStore.GetLinkedIdentitiesAsync(currentPlatform, currentExternalUserId);
            }
            else
            {
                identities = [];
            }
        }
        catch (Exception ex)
        {
            errorMessage = $"Не удалось загрузить аккаунты: {ex.Message}";
        }
    }

    private async Task LoadMasterProfile()
    {
        try
        {
            masterProfile = await AuthorizedSessionService.GetMasterProfileSettingsForCurrentUserAsync();
            if (masterProfile is not null)
            {
                masterProfileModel = new MasterProfileEditModel
                {
                    DisplayName = masterProfile.DisplayName,
                    PublicSlug = masterProfile.PublicSlug ?? string.Empty,
                    IsPublic = masterProfile.IsPublic,
                    Bio = masterProfile.Bio ?? string.Empty
                };
            }
        }
        catch (Exception ex)
        {
            errorMessage = $"Не удалось загрузить профиль мастера: {ex.Message}";
        }
    }

    private string? PublicMasterProfileUrl =>
        masterProfile?.IsPublic == true && !string.IsNullOrWhiteSpace(masterProfile.PublicSlug)
            ? Navigation.ToAbsoluteUri($"/gm/{masterProfile.PublicSlug}").ToString()
            : null;

    private async Task SaveMasterProfile()
    {
        savingMasterProfile = true;
        errorMessage = null;
        successMessage = null;

        try
        {
            await AuthorizedSessionService.UpdateMasterProfileSettingsForCurrentUserAsync(
                masterProfileModel.PublicSlug,
                masterProfileModel.IsPublic,
                masterProfileModel.DisplayName,
                masterProfileModel.Bio);

            successMessage = "Публичный профиль мастера обновлён.";
            await LoadMasterProfile();
        }
        catch (Exception ex)
        {
            errorMessage = $"Не удалось сохранить профиль мастера: {ex.Message}";
        }
        finally
        {
            savingMasterProfile = false;
        }
    }

    private bool HasLinkedPlatform(string platform)
    {
        return identities?.Any(i => i.Platform == platform) ?? false;
    }

    private async Task Unlink(string platform, string externalUserId)
    {
        isUnlinking = true;
        errorMessage = null;
        successMessage = null;

        try
        {
            if (currentPlatform is null || currentExternalUserId is null)
            {
                errorMessage = "Не удалось определить текущего пользователя.";
                return;
            }

            await SessionStore.UnlinkIdentityAsync(currentPlatform, currentExternalUserId, platform, externalUserId);
            successMessage = $"{platform} аккаунт отвязан.";
            await LoadIdentities();
        }
        catch (InvalidOperationException ex)
        {
            errorMessage = $"Ошибка отвязки: {ex.Message}";
        }
        catch (Exception ex)
        {
            errorMessage = $"Ошибка отвязки: {ex.Message}";
        }
        finally
        {
            isUnlinking = false;
        }
    }

    private sealed class MasterProfileEditModel
    {
        public string DisplayName { get; set; } = string.Empty;
        public string PublicSlug { get; set; } = string.Empty;
        public bool IsPublic { get; set; }
        public string Bio { get; set; } = string.Empty;
    }
}
