@using Indotalent.ConfigBackEnd.Extensions
@using Indotalent.Features.Setting.SystemUser
@using Indotalent.Features.Setting.SystemUser.Cqrs
@using Microsoft.AspNetCore.Components.Forms
@using MudBlazor
@using System.IO
@inject SystemUserService SystemUserService
@inject ISnackbar Snackbar

<MudPaper Elevation="0" Square="true" Class="pa-6 mb-3 d-flex align-center justify-space-between" Style="border: 1px solid #DCEBFA;">
    <div class="d-flex align-center gap-4">
        <MudIconButton Icon="@Icons.Material.Filled.ArrowBack" OnClick="() => OnCancel.InvokeAsync()" />
        <div>
            <MudText Typo="Typo.h5" Style="font-weight: 900; color: #1a1a1a;">Update Profile Picture</MudText>
            <MudText Typo="Typo.body2" Style="color: #64748b;">Change avatar for user: @Data.FullName</MudText>
        </div>
    </div>
</MudPaper>

<MudGrid Spacing="3">
    <MudItem xs="12" sm="5">
        <MudPaper Elevation="0" Outlined="true" Class="pa-8 d-flex flex-column align-center" Style="border-radius: 4px; border: 1px solid #DCEBFA; background-color: #F8FAFC;">
            <MudText Typo="Typo.button" Color="Color.Primary" Class="mb-4" Style="font-weight: 800;">Preview Avatar</MudText>
            
            @if (_isLoading)
            {
                <MudProgressCircular Color="Color.Primary" Indeterminate="true" Size="Size.Large" />
            }
            else if (!string.IsNullOrEmpty(_previewUrl))
            {
                <div style="width:180px; height:180px; 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:180px; height:180px; font-size: 4rem; font-weight: 800;">
                    @Data.FullName.ToInitial()
                </MudAvatar>
            }
            
            <MudText Typo="Typo.caption" Class="mt-4" Style="color: #64748b; text-align: center;">
                Allowed: JPG, JPEG, PNG. Max: 2MB.
            </MudText>
        </MudPaper>
    </MudItem>

    <MudItem xs="12" sm="7">
        <MudPaper Elevation="0" Outlined="true" Class="pa-8" Style="border-radius: 4px; border: 1px solid #DCEBFA; height: 100%;">
            <MudText Typo="Typo.button" Color="Color.Primary" Style="font-weight: 800;">Upload New Image</MudText>
            <MudDivider Class="mt-2 mb-6" />

            <MudFileUpload T="IBrowserFile" FilesChanged="HandleFileSelected" Accept=".jpg, .jpeg, .png">
                <MudButton Variant="Variant.Outlined"
                           Color="Color.Primary"
                           StartIcon="@Icons.Material.Filled.CloudUpload"
                           FullWidth="true"
                           Style="height: 120px; border-style: dashed; border-width: 2px; text-transform: none; font-weight: 700;border: 1px solid #e0e0e0;">
                    @(_selectedFile == null ? "Click or Drag Image Here" : _selectedFile.Name)
                </MudButton>
            </MudFileUpload>

            <div class="d-flex justify-end gap-2 mt-10">
                <MudButton OnClick="() => OnCancel.InvokeAsync()"
                           Variant="Variant.Outlined"
                           Disabled="_processing"
                           Style="border-radius: 4px; text-transform: none; font-weight: 700;border: 1px solid #e0e0e0;">
                    Cancel
                </MudButton>
                <MudButton Color="Color.Primary"
                           Variant="Variant.Filled"
                           OnClick="SubmitAvatar"
                           Disabled="@(_selectedFile == null || _processing)"
                           Style="border-radius: 4px; text-transform: none; 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>Update Avatar</MudText>
                    }
                </MudButton>
            </div>
        </MudPaper>
    </MudItem>
</MudGrid>

@code {
    [Parameter] public UpdateSystemUserRequest Data { get; set; } = new();
    [Parameter] public EventCallback OnCancel { get; set; }
    [Parameter] public EventCallback OnSuccess { get; set; }

    private IBrowserFile? _selectedFile;
    private string? _previewUrl;
    private bool _processing = false;
    private bool _isLoading = false;

    protected override async Task OnInitializedAsync()
    {
        if (!string.IsNullOrEmpty(Data.AvatarFile))
        {
            _isLoading = true;
            try 
            {
                var bytes = await SystemUserService.GetAvatarBlobAsync(Data.AvatarFile);
                if (bytes != null && bytes.Length > 0)
                {
                    _previewUrl = $"data:image/png;base64,{Convert.ToBase64String(bytes)}";
                }
            }
            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;

        _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 = Data.Id ?? string.Empty,
                FileData = ms.ToArray(),
                FileName = _selectedFile.Name
            };

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