@page "/layers/{id:guid}"
@using DiunaBI.UI.Shared.Services
@using DiunaBI.Application.DTOModels
@using MudBlazor
@implements IDisposable

<MudCard>
    <MudCardHeader>
        <CardHeaderContent>
            <MudText Typo="Typo.h5">Layer Details</MudText>
        </CardHeaderContent>
        <CardHeaderActions>
            @if (layer != null && layer.Type == LayerType.Administration && IsWorkerLayer())
            {
                <MudButton Variant="Variant.Filled"
                           Color="Color.Primary"
                           OnClick="RunNow"
                           Disabled="isRunningJob"
                           StartIcon="@Icons.Material.Filled.PlayArrow">
                    @if (isRunningJob)
                    {
                        <MudProgressCircular Size="Size.Small" Indeterminate="true"/>
                        <span style="margin-left: 8px;">Creating Job...</span>
                    }
                    else
                    {
                        <span>Run Now</span>
                    }
                </MudButton>
            }
            <MudButton Variant="Variant.Text" OnClick="GoBack" StartIcon="@Icons.Material.Filled.ArrowBack">Back to List</MudButton>
        </CardHeaderActions>
    </MudCardHeader>
    <MudCardContent>
        @if (isLoading)
        {
            <MudProgressLinear Color="Color.Primary" Indeterminate="true" />
        }
        else if (layer == null)
        {
            <MudAlert Severity="Severity.Error">Layer not found</MudAlert>
        }
        else
        {
            <MudGrid>
                <MudItem xs="12" md="6">
                    <MudTextField @bind-Value="layer.Name"
                                  Label="Name"
                                  Variant="Variant.Outlined"
                                  ReadOnly="true"
                                  FullWidth="true"/>
                </MudItem>
                <MudItem xs="12" md="6">
                    @if (layer.IsCancelled)
                    {
                        <MudAlert Severity="Severity.Warning" Dense="true">
                            This layer is cancelled. Will not be used in any further processing.
                        </MudAlert>
                    }
                </MudItem>
                <MudItem xs="12" md="6">
                    <MudTextField Value="@DateTimeHelper.FormatDateTime(layer.CreatedAt, "yyyy-MM-dd HH:mm")"
                                  Label="Created"
                                  Variant="Variant.Outlined"
                                  ReadOnly="true"
                                  FullWidth="true"
                                  Adornment="Adornment.End"
                                  AdornmentText="@(layer.CreatedBy?.Username ?? "")"/>
                </MudItem>
                <MudItem xs="12" md="6">
                    <MudTextField Value="@DateTimeHelper.FormatDateTime(layer.ModifiedAt, "yyyy-MM-dd HH:mm")"
                                  Label="Modified"
                                  Variant="Variant.Outlined"
                                  ReadOnly="true"
                                  FullWidth="true"
                                  Adornment="Adornment.End"
                                  AdornmentText="@(layer.ModifiedBy?.Username ?? "")"/>
                </MudItem>
            </MudGrid>

            <MudDivider Class="my-4"/>

            <MudTabs Elevation="0" Rounded="true" ApplyEffectsToContainer="true" PanelClass="pt-4">
                <MudTabPanel Text="Details" Icon="@Icons.Material.Filled.TableChart">

            <MudTable Items="@records"
                      Dense="true"
                      Striped="true"
                      FixedHeader="true"
                      FixedFooter="true"
                      Height="600px">
                <HeaderContent>
                    <MudTh>Code</MudTh>
                    @foreach (var column in displayedColumns)
                    {
                        <MudTh>@column</MudTh>
                    }
                    @if (isEditable)
                    {
                        <MudTh>Actions</MudTh>
                    }
                </HeaderContent>
                <RowTemplate>
                    @if (editingRecordId == context.Id)
                    {
                        <MudTd DataLabel="Code">
                            <MudTextField @bind-Value="editingRecord.Code"
                                          Variant="Variant.Outlined"
                                          Margin="Margin.Dense"
                                          FullWidth="true"/>
                        </MudTd>
                        @foreach (var column in displayedColumns)
                        {
                            @if (column == "Description1")
                            {
                                <MudTd DataLabel="@column">
                                    <MudTextField @bind-Value="editingRecord.Desc1"
                                                  Variant="Variant.Outlined"
                                                  Margin="Margin.Dense"
                                                  FullWidth="true"/>
                                </MudTd>
                            }
                            else
                            {
                                <MudTd DataLabel="@column">@GetRecordValue(context, column)</MudTd>
                            }
                        }
                        <MudTd>
                            <MudIconButton Icon="@Icons.Material.Filled.Check"
                                           Color="Color.Success"
                                           Size="Size.Small"
                                           OnClick="SaveEdit"
                                           Title="Save"/>
                            <MudIconButton Icon="@Icons.Material.Filled.Close"
                                           Color="Color.Default"
                                           Size="Size.Small"
                                           OnClick="CancelEdit"
                                           Title="Cancel"/>
                        </MudTd>
                    }
                    else
                    {
                        <MudTd DataLabel="Code">@context.Code</MudTd>
                        @foreach (var column in displayedColumns)
                        {
                            <MudTd DataLabel="@column">@GetRecordValue(context, column)</MudTd>
                        }
                        @if (isEditable)
                        {
                            <MudTd>
                                <MudIconButton Icon="@Icons.Material.Filled.Edit"
                                               Color="Color.Primary"
                                               Size="Size.Small"
                                               OnClick="() => StartEdit(context)"
                                               Title="Edit"/>
                                <MudIconButton Icon="@Icons.Material.Filled.Delete"
                                               Color="Color.Error"
                                               Size="Size.Small"
                                               OnClick="() => DeleteRecord(context)"
                                               Title="Delete"/>
                            </MudTd>
                        }
                    }
                </RowTemplate>
                <FooterContent>
                    @if (showSummary)
                    {
                        <MudTd><b>@NumberFormatHelper.FormatNumber(totalSum)</b></MudTd>
                        @foreach (var column in displayedColumns)
                        {
                            @if (column.StartsWith("Value") && columnSums.ContainsKey(column))
                            {
                                <MudTd><b>@NumberFormatHelper.FormatNumber(columnSums[column])</b></MudTd>
                            }
                            else
                            {
                                <MudTd></MudTd>
                            }
                        }
                        @if (isEditable)
                        {
                            <MudTd></MudTd>
                        }
                    }
                </FooterContent>
            </MudTable>

            @if (isEditable)
            {
                @if (isAddingNew)
                {
                    <MudPaper Class="mt-4 pa-4" Outlined="true">
                        <MudGrid>
                            <MudItem xs="12" md="6">
                                <MudTextField @bind-Value="newRecord.Code"
                                              Label="Code"
                                              Variant="Variant.Outlined"
                                              FullWidth="true"/>
                            </MudItem>
                            <MudItem xs="12" md="6">
                                <MudTextField @bind-Value="newRecord.Desc1"
                                              Label="Description"
                                              Variant="Variant.Outlined"
                                              FullWidth="true"/>
                            </MudItem>
                            <MudItem xs="12" Class="d-flex justify-end">
                                <MudButton Variant="Variant.Filled"
                                           Color="Color.Success"
                                           OnClick="SaveNewRecord"
                                           StartIcon="@Icons.Material.Filled.Check"
                                           Class="mr-2">
                                    Save
                                </MudButton>
                                <MudButton Variant="Variant.Outlined"
                                           Color="Color.Default"
                                           OnClick="CancelAddNew"
                                           StartIcon="@Icons.Material.Filled.Close">
                                    Cancel
                                </MudButton>
                            </MudItem>
                        </MudGrid>
                    </MudPaper>
                }
                else
                {
                    <MudButton Variant="Variant.Outlined"
                               Color="Color.Primary"
                               OnClick="StartAddNew"
                               StartIcon="@Icons.Material.Filled.Add"
                               Class="mt-4">
                        Add New Record
                    </MudButton>
                }
            }
                </MudTabPanel>

                @if (showHistoryTab)
                {
                    <MudTabPanel Text="History" Icon="@Icons.Material.Filled.History">
                    @if (isLoadingHistory)
                    {
                        <MudProgressLinear Color="Color.Primary" Indeterminate="true" />
                    }
                    else if (selectedRecordForHistory != null || selectedDeletedRecordForHistory != null)
                    {
                        <MudPaper Class="pa-4 mb-4" Outlined="true">
                            <MudText Typo="Typo.h6">
                                History for Record:
                                @if (selectedDeletedRecordForHistory != null)
                                {
                                    <MudText Typo="Typo.h6" Inline="true" Color="Color.Error">@selectedDeletedRecordForHistory.Code (Deleted)</MudText>
                                }
                                else
                                {
                                    @selectedRecordForHistory?.Code
                                }
                            </MudText>
                            <MudButton Variant="Variant.Text"
                                       Color="Color.Primary"
                                       OnClick="ClearHistorySelection"
                                       StartIcon="@Icons.Material.Filled.ArrowBack"
                                       Size="Size.Small">
                                Back to list
                            </MudButton>
                        </MudPaper>

                        @if (!recordHistory.Any())
                        {
                            <MudAlert Severity="Severity.Info">No history available for this record.</MudAlert>
                        }
                        else
                        {
                            <MudTimeline TimelineOrientation="TimelineOrientation.Vertical" TimelinePosition="TimelinePosition.Start">
                                @foreach (var history in recordHistory)
                                {
                                    <MudTimelineItem Color="@GetHistoryColor(history.ChangeType)" Size="Size.Small">
                                        <ItemOpposite>
                                            <MudText Color="Color.Default" Typo="Typo.body2">
                                                @history.ChangedAt.ToString("g")
                                            </MudText>
                                        </ItemOpposite>
                                        <ItemContent>
                                            <MudPaper Elevation="3" Class="pa-3">
                                                <MudText Typo="Typo.body1">
                                                    <strong>@history.ChangeType</strong> by @history.ChangedByName
                                                </MudText>
                                                <MudText Typo="Typo.body2" Class="mt-2">
                                                    @history.FormattedChange
                                                </MudText>
                                            </MudPaper>
                                        </ItemContent>
                                    </MudTimelineItem>
                                }
                            </MudTimeline>
                        }
                    }
                    else
                    {
                        <MudText Typo="Typo.h6" Class="mb-3">Active Records</MudText>
                        <MudText Typo="Typo.body2" Class="mb-2">Select a record to view its history:</MudText>

                        <MudTable Items="@records"
                                  Dense="true"
                                  Striped="true"
                                  Hover="true"
                                  FixedHeader="true"
                                  Height="300px"
                                  OnRowClick="@((TableRowClickEventArgs<RecordDto> args) => OnRecordClickForHistory(args))"
                                  T="RecordDto"
                                  Style="cursor: pointer;">
                            <HeaderContent>
                                <MudTh>Code</MudTh>
                                <MudTh>Description</MudTh>
                                <MudTh>Modified</MudTh>
                                <MudTh>Modified By</MudTh>
                            </HeaderContent>
                            <RowTemplate>
                                <MudTd DataLabel="Code">@context.Code</MudTd>
                                <MudTd DataLabel="Description">@context.Desc1</MudTd>
                                <MudTd DataLabel="Modified">@DateTimeHelper.FormatDateTime(context.ModifiedAt, "yyyy-MM-dd HH:mm")</MudTd>
                                <MudTd DataLabel="Modified By">@GetModifiedByUsername(context.ModifiedById)</MudTd>
                            </RowTemplate>
                        </MudTable>

                        <MudDivider Class="my-4"/>

                        <MudText Typo="Typo.h6" Class="mb-3">Deleted Records</MudText>
                        <MudText Typo="Typo.body2" Class="mb-2">Select a deleted record to view its history:</MudText>

                        @if (deletedRecords.Any())
                        {
                            <MudTable Items="@deletedRecords"
                                      Dense="true"
                                      Striped="true"
                                      Hover="true"
                                      FixedHeader="true"
                                      Height="200px"
                                      OnRowClick="@((TableRowClickEventArgs<DeletedRecordDto> args) => OnDeletedRecordClickForHistory(args))"
                                      T="DeletedRecordDto"
                                      Style="cursor: pointer;">
                                <HeaderContent>
                                    <MudTh>Code</MudTh>
                                    <MudTh>Description</MudTh>
                                    <MudTh>Deleted</MudTh>
                                    <MudTh>Deleted By</MudTh>
                                </HeaderContent>
                                <RowTemplate>
                                    <MudTd DataLabel="Code">
                                        <MudText Color="Color.Error">@context.Code</MudText>
                                    </MudTd>
                                    <MudTd DataLabel="Description">@context.Desc1</MudTd>
                                    <MudTd DataLabel="Deleted">@context.DeletedAt.ToString("g")</MudTd>
                                    <MudTd DataLabel="Deleted By">@context.DeletedByName</MudTd>
                                </RowTemplate>
                            </MudTable>
                        }
                        else
                        {
                            <MudAlert Severity="Severity.Info" Dense="true">No deleted records found.</MudAlert>
                        }
                    }
                </MudTabPanel>
                }
            </MudTabs>
        }
    </MudCardContent>
</MudCard>
