@page "/profile/avatar"
@using System.ComponentModel.DataAnnotations
@using Microsoft.AspNetCore.Components.Forms
@using MudBlazor
@using System.IO
@using Indotalent.Features.Profile.Avatar
@using Indotalent.Features.Profile.Avatar.Cqrs
@using Indotalent.ConfigBackEnd.Interfaces
@inject ISnackbar Snackbar
@inject AvatarService AvatarService
@inject ICurrentUserService CurrentUserService

<MudPaper Elevation="0" Square="true" Class="pa-6 mb-3 d-flex align-center justify-space-between">
    <div>
        <MudText Typo="Typo.h5" Style="font-weight: 900; color: #1a1a1a;">Profile Picture</MudText>
        <MudText Typo="Typo.body2" Style="color: #64748b;">Update your avatar and how you appear to other members.</MudText>
    </div>

    <div class="d-flex align-center gap-2">
        <MudIcon Icon="@Icons.Material.Filled.Home" Size="Size.Small" Color="Color.Default" />
        <MudText Typo="Typo.caption" Style="color: #94a3b8;">/</MudText>
        <MudText Typo="Typo.caption" Style="color: #94a3b8;">Profile</MudText>
        <MudText Typo="Typo.caption" Style="color: #94a3b8;">/</MudText>
        <MudText Typo="Typo.caption" Style="font-weight: 600; color: #1a1a1a;">Avatar</MudText>
    </div>
</MudPaper>

<MudPaper Elevation="0" Outlined="true" Class="pa-8" Style="border-radius: 0px; background-color: #ffffff;">
    <MudStack Spacing="8">
        <MudGrid>
            <MudItem xs="12" md="4">
                <MudText Typo="Typo.h6" Class="fw-bold">Your Avatar</MudText>
                <MudText Typo="Typo.body2">Recommended size: 200x200px. Supported formats: JPG, JPEG, PNG. (max 2MB).</MudText>
            </MudItem>
            
            <MudItem xs="12" md="8">
                <div style="border: 2px dashed #e2e8f0; border-radius: 8px; background-color: #f8fafc;" class="pa-10">
                    <MudStack Spacing="6" AlignItems="AlignItems.Center">
                        
                        @if (_isLoading)
                        {
                            <MudProgressCircular Color="Color.Primary" Indeterminate="true" Style="width: 150px; height: 150px;" />
                        }
                        else if (!string.IsNullOrEmpty(_previewUrl))
                        {
                            <div style="width:150px; height:150px; border-radius: 50%; overflow: hidden; border: 4px solid white; box-shadow: 0 4px 12px rgba(0,0,0,0.1);">
                                <img src="@_previewUrl" style="width: 100%; height: 100%; object-fit: cover;" />
                            </div>
                        }
                        else
                        {
                            <MudAvatar Color="Color.Primary" Variant="Variant.Filled" Style="width:150px; height:150px; font-size: 3rem; font-weight: 800;">
                                @(CurrentUserService.FullName?.Substring(0, 1).ToUpper() ?? "U")
                            </MudAvatar>
                        }
                        
                        <div class="text-center">
                            <MudText Typo="Typo.subtitle1" Class="fw-bold">Avatar Preview</MudText>
                            <MudText Typo="Typo.body2" Class="text-muted">This is how your photo will look.</MudText>
                        </div>

                        <MudFileUpload T="IBrowserFile" FilesChanged="HandleFileSelected" Accept=".jpg, .jpeg, .png" Class="w-100">
                            <MudButton HtmlTag="label"
                                       Variant="Variant.Filled"
                                       Color="Color.Primary"
                                       Size="Size.Large"
                                       FullWidth="true"
                                       StartIcon="@Icons.Material.Filled.CloudUpload"
                                       Style="text-transform: none; height: 50px; font-weight: 700;">
                                @(_selectedFile == null ? "Browse File" : _selectedFile.Name)
                            </MudButton>
                        </MudFileUpload>
                    </MudStack>
                </div>
            </MudItem>
        </MudGrid>

        <div class="d-flex justify-end align-center gap-4 mt-4">
            <MudButton Variant="Variant.Filled"
                       Color="Color.Primary"
                       OnClick="SubmitAvatar"
                       Disabled="@(_selectedFile == null || _processing)"
                       Class="px-10"
                       Style="height: 45px; font-weight: 700;">
                @if (_processing)
                {
                    <MudProgressCircular Class="ms-n1" Size="Size.Small" Indeterminate="true" />
                    <MudText Class="ms-2" Typo="Typo.button" Style="text-transform: none !important;">Processing...</MudText>
                }
                else
                {
                    <MudText>Save Changes</MudText>
                }
            </MudButton>
        </div>
    </MudStack>
</MudPaper>

@code {
    private IBrowserFile? _selectedFile;
    private string? _previewUrl;
    private bool _processing = false;
    private bool _isLoading = false;
    private string? _fullName;

    protected override async Task OnInitializedAsync()
    {
        await LoadExistingAvatar();
    }

    private async Task LoadExistingAvatar()
    {
        var userId = CurrentUserService.UserId;
        if (string.IsNullOrEmpty(userId)) return;

        _isLoading = true;
        try
        {
            var response = await AvatarService.GetAvatarInfoAsync(userId);
            
            if (response != null && response.IsSuccess && response.Value != null)
            {
                _fullName = response.Value.FullName;

                if (!string.IsNullOrEmpty(response.Value.AvatarFile))
                {
                    var bytes = await AvatarService.GetAvatarBlobAsync(response.Value.AvatarFile);
                    if (bytes != null && bytes.Length > 0)
                    {
                        _previewUrl = $"data:image/png;base64,{Convert.ToBase64String(bytes)}";
                    }
                }
            }
        }
        catch (Exception) { }
        finally
        {
            _isLoading = false;
            StateHasChanged();
        }
    }

    private async Task HandleFileSelected(IBrowserFile file)
    {
        if (file == null) return;
        if (file.Size > 2 * 1024 * 1024)
        {
            Snackbar.Add("File too large. Max 2MB allowed.", Severity.Warning);
            return;
        }
        _selectedFile = file;
        using var stream = file.OpenReadStream(2 * 1024 * 1024);
        using var ms = new MemoryStream();
        await stream.CopyToAsync(ms);
        _previewUrl = $"data:{file.ContentType};base64,{Convert.ToBase64String(ms.ToArray())}";
        StateHasChanged();
    }

    private async Task SubmitAvatar()
    {
        if (_selectedFile == null) return;
        var userId = CurrentUserService.UserId;
        if (string.IsNullOrEmpty(userId)) return;

        _processing = true;
        try
        {
            using var stream = _selectedFile.OpenReadStream(2 * 1024 * 1024);
            using var ms = new MemoryStream();
            await stream.CopyToAsync(ms);

            var request = new ChangeAvatarRequest
            {
                UserId = userId,
                FileData = ms.ToArray(),
                FileName = _selectedFile.Name
            };

            var response = await AvatarService.ChangeAvatarAsync(request);
            await Task.Delay(500);
            if (response != null && response.IsSuccess)
            {
                Snackbar.Add("Avatar updated successfully", Severity.Success);
                _selectedFile = null;
                await LoadExistingAvatar();
            }
        }
        catch (Exception ex)
        {
            Snackbar.Add($"Upload failed: {ex.Message}", Severity.Error);
        }
        finally
        {
            _processing = false;
            StateHasChanged();
        }
    }
}