@using System.Net.Http.Headers
@inject IHttpClientFactory HttpFactory
@inject IJSRuntime JSRuntime
@inject ISnackbar Snackbar

<div class="d-flex flex-column">
    <span Class="title">@RobotModelName</span>
    <div class="d-flex flex-grow-1 w-100 flex-column">
        <div class="robot-item">
            <img src="@imageSrc" alt="robot model image" onerror="this.onerror=null; this.src='/images/Image-not-found.png';" />
        </div>
        <div class="d-flex flex-row m-3 align-items-center justify-content-between">
            <MudText Typo="Typo.h5">Image</MudText>
            <div class="d-flex flex-row">
                <MudIconButton Class="me-3" Size="Size.Small" Variant="Variant.Filled" Icon="@Icons.Material.Filled.Download" Color="Color.Primary" Disabled="@Disable" OnClick="@(async () => await DownloadImage())" />
                <MudIconButton Class="me-3" Size="Size.Small" Variant="Variant.Filled" Icon="@Icons.Material.Filled.Upload" Color="Color.Primary" Disabled="@Disable" OnClick="OpenUpdateRobotImage" />
            </div>
        </div>
    </div>
</div>

<MudDialog @bind-Visible="@IsUpdateRobotImageVisable">
    <TitleContent>
        <MudText Typo="Typo.h6">
            Update RobotModel's Image
        </MudText>
    </TitleContent>
    <DialogContent>
        <div class="d-flex flex-column w-100 h-100 px-3">
            <div class="d-flex flex-row mb-2">
                <InputFile id="fileRobotImageCreate" OnChange="RobotImageChanged" accept=".png" hidden />
                <MudButton HtmlTag="label"
                Variant="Variant.Filled"
                Color="Color.Primary"
                StartIcon="@Icons.Material.Filled.CloudUpload"
                for="fileRobotImageCreate">
                    Robot Model Image
                </MudButton>
            </div>
            <div class="d-flex mb-2">
                <div class="robot-update-item">
                    <img alt="Robot Model Image" src="@ImagePreview" style="image-rendering: pixelated;" />
                </div>
            </div>
        </div>
    </DialogContent>
    <DialogActions>
        <MudButton OnClick="@(() => IsUpdateRobotImageVisable = false)" Variant="Variant.Filled">Cancel</MudButton>
        <MudButton Color="Color.Primary" OnClick="UpdateRobotModelImage" Variant="Variant.Filled">Update</MudButton>
    </DialogActions>
</MudDialog>
@code {
    private bool Disable = true;
    private string imageSrc = "/images/Image-not-found.png";
    private string RobotModelName = "Robot Model preview";
    private Guid RobotModelId = Guid.Empty;

    private string ImagePreview = "";
    private IBrowserFile? RobotImageChange;

    private bool IsUpdateRobotImageVisable;

    public void SetRobotPreview(RobotModelDto? robotmodel)
    {
        if (robotmodel is null)
        {
            Disable = true;
            RobotModelName = "Robot Model preview";
            imageSrc = "/images/Image-not-found.png";
            RobotModelId = Guid.Empty;
        }
        else
        {
            using var Http = HttpFactory.CreateClient("RobotManagerAPI");
            imageSrc = $"{Http.BaseAddress}api/RobotModels/image/{robotmodel.Id}?t={DateTime.Now}";
            RobotModelName = robotmodel.ModelName;
            RobotModelId = robotmodel.Id;
            Disable = false;
        }
        StateHasChanged();
    }

    private async Task DownloadImage()
    {
        try
        {
            using var Http = HttpFactory.CreateClient("RobotManagerAPI");
            var response = await Http.GetAsync(imageSrc);

            if (response.IsSuccessStatusCode)
            {
                var fileBytes = await response.Content.ReadAsByteArrayAsync();

                var base64Data = Convert.ToBase64String(fileBytes);
                var mimeType = "image/png";
                var url = $"data:{mimeType};base64,{base64Data}";

                await JSRuntime.InvokeVoidAsync("DownloadImage", url, $"{RobotModelName}.png");
            }
            else Snackbar.Add("Không thể tải ảnh robot", Severity.Warning);
        }
        catch (Exception ex)
        {
            Snackbar.Add($"Không thể tải ảnh robot: {ex.Message}", Severity.Warning);
        }
    }

    private void OpenUpdateRobotImage()
    {
        ImagePreview = imageSrc;
        RobotImageChange = null;
        IsUpdateRobotImageVisable = true;
        StateHasChanged();
    }

    public async Task<string> UploadMedia(IBrowserFile file)
    {
        var path = Path.Combine(Path.GetTempPath(), RobotModelName);
        await using var fs = new FileStream(path, FileMode.Create);
        await file.OpenReadStream(file.Size).CopyToAsync(fs);
        var bytes = new byte[file.Size];
        fs.Position = 0;
        await fs.ReadAsync(bytes);
        fs.Close();
        File.Delete(path);
        return $"data:{file.ContentType};base64,{Convert.ToBase64String(bytes)}";
    }

    private async Task RobotImageChanged(InputFileChangeEventArgs e)
    {
        RobotImageChange = e.File;
        if (RobotImageChange is not null)
        {
            ImagePreview = await UploadMedia(RobotImageChange);
            StateHasChanged();
        }
    }

    private async Task UpdateRobotModelImage()
    {
        if (RobotImageChange is null) return;

        using var content = new MultipartFormDataContent();
        var fileContent = new StreamContent(RobotImageChange.OpenReadStream(maxAllowedSize: 20480000));
        fileContent.Headers.ContentType = new MediaTypeHeaderValue(RobotImageChange.ContentType);
        content.Add(fileContent, "image", RobotImageChange.Name);

        using var Http = HttpFactory.CreateClient("RobotManagerAPI");
        var result = await (await Http.PutAsync($"api/RobotModels/image/{RobotModelId}", content)).Content.ReadFromJsonAsync<MessageResult>();
        if (result is null) Snackbar.Add("Lỗi giao tiếp với hệ thống", Severity.Error);
        else if (!result.IsSuccess) Snackbar.Add(result.Message ?? "Lỗi chưa xác định.", Severity.Error);
        else
        {
            imageSrc = ImagePreview;
            IsUpdateRobotImageVisable = false;
            Snackbar.Add("Thay đổi thành công", Severity.Success);
        }
        StateHasChanged();
    }
}
