@implements IDisposable

@inject IHttpClientFactory HttpClientFactory
@inject ISnackbar Snackbar

@foreach (var zone in Models)
{
    <Zone Model="@zone" IsSetting="@IsSetting" DoubleClick="ZoneDoubleClick" IsShow="IsShow" />
}

<MudDialog @bind-Visible="@UpdateZoneVisiable">
    <TitleContent>
        <MudText Typo="Typo.h6">
            Update zone @UpdateModel.Id
        </MudText>
    </TitleContent>
    <DialogContent>
        <MudSelect Class="mt-2" @bind-Value="UpdateModel.Type" Label="Type" Variant="Variant.Outlined" AnchorOrigin="Origin.BottomLeft" Margin="Margin.Dense" Dense ReadOnly=@(MapIsActive)>
            <MudSelectItem Value="@(ZoneType.Operating)" />
            <MudSelectItem Value="@(ZoneType.OperatingHazard)" />
            <MudSelectItem Value="@(ZoneType.Restricted)" />
            <MudSelectItem Value="@(ZoneType.LoadTransfer)" />
            <MudSelectItem Value="@(ZoneType.Confined)" />
            <MudSelectItem Value="@(ZoneType.Forbidden)" />
        </MudSelect>
        <MudTextField Class="mt-2" @bind-Value="UpdateModel.Name" Label="Name" ShrinkLabel Variant="Variant.Outlined" Margin="Margin.Dense" ReadOnly=@(MapIsActive) />
        <div class="d-flex flex-row mt-5">
            <div class="d-flex flex-column me-2 w-50">
                <div class="mb-4">
                    <MudNumericField Class="mb-3" @bind-Value="UpdateModel.X1" Label="X1" ShrinkLabel Variant="Variant.Outlined" Margin="Margin.Dense" ReadOnly=@(MapIsActive) />
                    <MudNumericField @bind-Value="UpdateModel.Y1" Label="Y1" ShrinkLabel Variant="Variant.Outlined" Margin="Margin.Dense" ReadOnly=@(MapIsActive) />
                </div>
                <div>
                    <MudNumericField Class="mb-3" @bind-Value="UpdateModel.X2" Label="X2" ShrinkLabel Variant="Variant.Outlined" Margin="Margin.Dense" ReadOnly=@(MapIsActive) />
                    <MudNumericField @bind-Value="UpdateModel.Y2" Label="Y2" ShrinkLabel Variant="Variant.Outlined" Margin="Margin.Dense" ReadOnly=@(MapIsActive) />
                </div>
            </div>
            <div class="d-flex flex-column ms-2 w-50">
                <div class="mb-4">
                    <MudNumericField Class="mb-3" @bind-Value="UpdateModel.X3" Label="X3" ShrinkLabel Variant="Variant.Outlined" Margin="Margin.Dense" ReadOnly=@(MapIsActive) />
                    <MudNumericField @bind-Value="UpdateModel.Y3" Label="Y3" ShrinkLabel Variant="Variant.Outlined" Margin="Margin.Dense" ReadOnly=@(MapIsActive) />
                </div>
                <div>
                    <MudNumericField Class="mb-3" @bind-Value="UpdateModel.X4" Label="X4" ShrinkLabel Variant="Variant.Outlined" Margin="Margin.Dense" ReadOnly=@(MapIsActive) />
                    <MudNumericField @bind-Value="UpdateModel.Y4" Label="Y4" ShrinkLabel Variant="Variant.Outlined" Margin="Margin.Dense" ReadOnly=@(MapIsActive) />
                </div>
            </div>
        </div>
    </DialogContent>
    <DialogActions>
        <MudButton OnClick="CancelUpdateZone" Class="px-10" Variant="Variant.Filled">Cancel</MudButton>
        <MudButton OnClick="UpdateZone" Variant="Variant.Filled" Color="Color.Primary" Class="px-10" Disabled=@(MapIsActive)>Update</MudButton>
    </DialogActions>
</MudDialog>

@code {
    [Parameter, EditorRequired]
    public MapZoneModel Models { get; set; } = null!;

    [Parameter]
    public bool IsShow { get; set; }

    [Parameter]
    public bool IsSetting { get; set; }

    [CascadingParameter]
    protected bool MapIsActive { get; set; }

    [Parameter]
    public EditorState EditorState { get; set; }

    [Parameter]
    public EventCallback<(ZoneModel, bool)> ActivedZoneChanged { get; set; }

    private ZoneUpdateModel UpdateModel = new();
    private bool UpdateZoneVisiable = false;
    private HttpClient Http = default!;


    protected override async Task OnAfterRenderAsync(bool firstRender)
    {
        await base.OnAfterRenderAsync(firstRender);
        if (!firstRender) return;

        Http = HttpClientFactory.CreateClient("MapManagerAPI");
        Models.Changed += StateHasChanged;
        Models.ActivedZoneChanged += OnActivedZoneChanged;
    }

    private void OnActivedZoneChanged(ZoneModel model, bool state)
    {
        _ = ActivedZoneChanged.InvokeAsync((model, state));
    }

    private void ZoneDoubleClick(ZoneModel model)
    {
        if (model == null || EditorState != EditorState.SettingZone) return;

        UpdateModel.Id = model.Id;
        UpdateModel.Type = model.Type;
        UpdateModel.Name = model.Name;
        UpdateModel.X1 = model.X1;
        UpdateModel.Y1 = model.Y1;
        UpdateModel.X2 = model.X2;
        UpdateModel.Y2 = model.Y2;
        UpdateModel.X3 = model.X3;
        UpdateModel.Y3 = model.Y3;
        UpdateModel.X4 = model.X4;
        UpdateModel.Y4 = model.Y4;

        UpdateZoneVisiable = true;
        StateHasChanged();
    }

    private void CancelUpdateZone()
    {
        UpdateZoneVisiable = false;
        StateHasChanged();
    }

    private async Task UpdateZone()
    {
        var selectedModel = Models.FirstOrDefault(e => e.Id == UpdateModel.Id);

        if (selectedModel == null)
        {
            UpdateZoneVisiable = false;
            StateHasChanged();
            return;
        }

        var result = await (await Http.PutAsJsonAsync($"api/Zones", UpdateModel)).Content.ReadFromJsonAsync<MessageResult>();
        if (result is null)
        {
            Snackbar.Add("Lỗi giao tiếp với hệ thống", Severity.Error);
            return;
        }
        else if (!result.IsSuccess)
        {
            Snackbar.Add(result.Message, Severity.Error);
            return;
        }

        selectedModel.UpdateData(UpdateModel);
        UpdateZoneVisiable = false;
        Snackbar.Add("Cập nhật thành công", Severity.Success);
        StateHasChanged();
    }

    public void Dispose()
    {
        Models.Changed -= StateHasChanged;
        Models.ActivedZoneChanged -= OnActivedZoneChanged;
        GC.SuppressFinalize(this);
    }
}
