@page "/serilogs/file"
@using System.IO
@using Microsoft.AspNetCore.Components.Web
@using Microsoft.AspNetCore.Hosting
@using Microsoft.JSInterop
@using MudBlazor
@using System.Linq
@inject IWebHostEnvironment Env
@inject IJSRuntime JS
@inject IConfiguration Configuration
@inject ISnackbar Snackbar

<MudPaper Elevation="0" Square="true" Class="pa-6 mb-3 d-flex align-center justify-space-between" Style="border: 1px solid #E5E7EB; border-radius: 12px;">
    <div>
        <MudText Typo="Typo.h5" Style="font-weight: 700; color: #111827;">File Logs</MudText>
        <MudText Typo="Typo.body2" Style="color: #9CA3AF;">Browse and download log files stored on the local server storage.</MudText>
    </div>

    <div class="d-flex align-center gap-2">
        <MudIcon Icon="@Icons.Material.Filled.Description" Size="Size.Small" Color="Color.Default" />
        <MudText Typo="Typo.caption" Style="color: #9CA3AF;">/</MudText>
        <MudText Typo="Typo.caption" Style="color: #9CA3AF;">Serilogs</MudText>
        <MudText Typo="Typo.caption" Style="color: #9CA3AF;">/</MudText>
        <MudText Typo="Typo.caption" Style="font-weight: 700; color: #111827;">File</MudText>
    </div>
</MudPaper>

<MudPaper Elevation="0" Outlined="true" Style="border-radius: 12px; overflow: hidden; background-color: #ffffff; border: 1px solid #E5E7EB;">

    <div style="padding: 20px 24px; border-bottom: 1px solid #E5E7EB; display: flex; justify-content: space-between; align-items: center; background-color: #ffffff; min-height: 80px;">
        
        <div style="display: flex; align-items: center; gap: 8px;">
            <MudTextField @bind-Value="_searchString" 
                          Placeholder="Search..." 
                          Adornment="Adornment.Start" 
                          AdornmentIcon="@Icons.Material.Filled.Search" 
                          IconSize="Size.Small" 
                          Class="mt-0"
                          Variant="Variant.Outlined"
                          Margin="Margin.Dense"
                          Style="background-color: white; width: 280px; border-radius: 8px;"
                          OnKeyDown="@HandleSearchKeyDown" />
            
            <MudButton Variant="Variant.Filled" 
                       Color="Color.Primary" 
                       OnClick="OnSearchClick" 
                       Size="Size.Small" 
                       Style="text-transform: none; font-weight: 500; border-radius: 6px; height: 34px; box-shadow: none;">
                Search
            </MudButton>
        </div>

        <div style="display: flex; gap: 8px; align-items: center;">
            <MudButton Variant="Variant.Outlined"
                       Color="Color.Primary"
                       StartIcon="@(_isRefreshing ? null : Icons.Material.Filled.Refresh)"
                       Size="Size.Small"
                       OnClick="HandleRefresh"
                       Disabled="_isRefreshing"
                       Style="text-transform: none; font-weight: 500; border-radius: 6px; background: white; height: 34px; border: 1px solid #D1D5DB;">
                @if (_isRefreshing)
                {
                    <MudProgressCircular Class="ms-n1" Size="Size.Small" Indeterminate="true" />
                    <MudText Class="ms-2" Typo="Typo.button" Style="text-transform: none !important;">Refreshing...</MudText>
                }
                else
                {
                    <MudText Typo="Typo.button" Style="text-transform: none !important;">Refresh</MudText>
                }
            </MudButton>

            @if (_selectedFile != null)
            {
                <MudButton Variant="Variant.Filled"
                           Color="Color.Success"
                           StartIcon="@(_isDownloading ? null : Icons.Material.Filled.Download)"
                           Size="Size.Small"
                           OnClick="DownloadFile"
                           Disabled="_isDownloading"
                           Style="text-transform: none; font-weight: 500; border-radius: 6px; height: 34px;">
                    @if (_isDownloading)
                    {
                        <MudProgressCircular Class="ms-n1" Size="Size.Small" Indeterminate="true" />
                        <MudText Class="ms-2" Typo="Typo.button" Style="text-transform: none !important;">Downloading...</MudText>
                    }
                    else
                    {
                        <MudText>Download File</MudText>
                    }
                </MudButton>
                <MudIconButton Icon="@Icons.Material.Filled.Close" Size="Size.Small" OnClick="() => _selectedFile = null" />
            }
        </div>
    </div>

    <MudTable Striped="true" Items="@GetPagedData()"
              Hover="true"
              Elevation="0"
              Dense="true"
              T="LogFileInfo"
              OnRowClick="@HandleRowClick"
              RowStyle="cursor: pointer;"
              Class="mud-width-full"
              Loading="@_isRefreshing">
        <HeaderContent>
            <MudTh Style="width: 50px; border-bottom: 1px solid #E5E7EB;"></MudTh>
            <MudTh Style="font-weight: 600; color: #6B7280; border-bottom: 1px solid #E5E7EB; white-space: nowrap;">
                <MudTableSortLabel SortBy="new Func<LogFileInfo, object>(x => x.FileName)">File Name</MudTableSortLabel>
            </MudTh>
            <MudTh Style="font-weight: 600; color: #6B7280; border-bottom: 1px solid #E5E7EB; white-space: nowrap;">
                <MudTableSortLabel SortBy="new Func<LogFileInfo, object>(x => x.LastModified)">Last Modified</MudTableSortLabel>
            </MudTh>
            <MudTh Style="font-weight: 600; color: #6B7280; border-bottom: 1px solid #E5E7EB; white-space: nowrap;">
                <MudTableSortLabel SortBy="new Func<LogFileInfo, object>(x => x.SizeInBytes)">Size</MudTableSortLabel>
            </MudTh>
        </HeaderContent>
        <RowTemplate>
            <MudTd Style="padding-top: 0.75rem; padding-bottom: 0.75rem;">
                <MudCheckBox T="bool" Value="@(_selectedFile?.FullPath == context.FullPath)" Color="Color.Primary" Dense="true" Size="Size.Small" ReadOnly="true" />
            </MudTd>
            <MudTd Style="padding-top: 0.75rem; padding-bottom: 0.75rem;">
                <div class="d-flex align-center gap-2">
                    <MudIcon Icon="@Icons.Custom.FileFormats.FileDocument" Color="Color.Info" Size="Size.Small" />
                    <MudText Typo="Typo.body2" Style="font-weight: 600;">@context.FileName</MudText>
                </div>
            </MudTd>
            <MudTd Style="padding-top: 0.75rem; padding-bottom: 0.75rem;">
                <MudText Typo="Typo.body2">@context.LastModified.ToString("yyyy-MM-dd HH:mm:ss")</MudText>
            </MudTd>
            <MudTd Style="padding-top: 0.75rem; padding-bottom: 0.75rem;">
                <MudChip T="string" Size="Size.Small" Variant="Variant.Text" Style="background-color: #F9FAFB; font-weight: 600; border-radius: 6px; color: #374151;">@context.FileSize</MudChip>
            </MudTd>
        </RowTemplate>
    </MudTable>

    <div style="display: flex; justify-content: space-between; align-items: center; padding: 12px 24px; background-color: #F9FAFB; border-top: 1px solid #E5E7EB;">
        <div style="display: flex; align-items: center; gap: 12px;">
            <MudText Typo="Typo.caption" Style="font-weight: 500; color: #9CA3AF; font-size: 0.75rem;">Rows per page:</MudText>
            
            <MudSelect T="int" 
                       Value="@_top" 
                       ValueChanged="OnPageSizeChanged" 
                       Dense="true" 
                       Margin="Margin.Dense" 
                       Style="width: 80px; background-color: white; font-size: 12px; font-weight: 600;" 
                       Variant="Variant.Outlined"
                       Class="mt-0 custom-select-dense">
                <MudSelectItem Value="5" />
                <MudSelectItem Value="10" />
                <MudSelectItem Value="50" />
                <MudSelectItem Value="500" />
                <MudSelectItem Value="1000" />
            </MudSelect>

            <MudText Typo="Typo.caption" Style="color: #9CA3AF; font-size: 0.75rem; font-weight: 500; margin-left: 12px;">
                Showing @(GetFilteredData().Count() == 0 ? 0 : _skip + 1) - @Math.Min(_skip + _top, GetFilteredData().Count()) of @GetFilteredData().Count()
            </MudText>
        </div>

        <div style="display: flex; gap: 8px; align-items: center;">
            <MudIconButton Icon="@Icons.Material.Filled.FirstPage" Size="Size.Small" OnClick="@(() => OnPageChanged(1))" Disabled="@(_currentPage == 1)" Style="@(_currentPage == 1 ? "color: #D1D5DB; background: transparent;" : "color: #6B7280; background: white; border: 1px solid #D1D5DB; border-radius: 6px;")" />
            <MudButton OnClick="@(() => OnPageChanged(_currentPage - 1))" Disabled="@(_currentPage == 1)" Variant="Variant.Text" StartIcon="@Icons.Material.Filled.ChevronLeft" Size="Size.Small" Style="@(_currentPage == 1 ? "min-width: 34px; padding: 4px 8px; font-size: 0.75rem; font-weight: 500; color: #D1D5DB; border-radius: 6px; text-transform: none;" : "min-width: 34px; padding: 4px 8px; font-size: 0.75rem; font-weight: 500; color: #6B7280; background: white; border: 1px solid #D1D5DB; border-radius: 6px; text-transform: none;")">Prev</MudButton>
            @{
    var totalPages = _totalPage == 0 ? 1 : _totalPage;
    var maxVisible = 5;
    var startPage = Math.Max(1, _currentPage - maxVisible / 2);
    var endPage = Math.Min(totalPages, startPage + maxVisible - 1);
    if (endPage - startPage < maxVisible - 1) { startPage = Math.Max(1, endPage - maxVisible + 1); }
}
@for (int i = startPage; i <= endPage; i++)
{
    var pageNum = i;
    var isActive = pageNum == _currentPage;
    <MudButton OnClick="@(() => OnPageChanged(pageNum))"
               Variant="Variant.Text" Size="Size.Small"
               Style="@(isActive ? "min-width: 34px; padding: 4px 8px; font-size: 0.75rem; font-weight: 600; background: #3B82F6; color: white; border: 1px solid #3B82F6; border-radius: 6px; text-transform: none;" : "min-width: 34px; padding: 4px 8px; font-size: 0.75rem; font-weight: 500; color: #374151; background: white; border: 1px solid #D1D5DB; border-radius: 6px; text-transform: none;")">@pageNum</MudButton>
}
            <MudButton OnClick="@(() => OnPageChanged(_currentPage + 1))" Disabled="@(_currentPage == _totalPage || _totalPage == 0)" Variant="Variant.Text" EndIcon="@Icons.Material.Filled.ChevronRight" Size="Size.Small" Style="@(_currentPage == _totalPage || _totalPage == 0 ? "min-width: 34px; padding: 4px 8px; font-size: 0.75rem; font-weight: 500; color: #D1D5DB; border-radius: 6px; text-transform: none;" : "min-width: 34px; padding: 4px 8px; font-size: 0.75rem; font-weight: 500; color: #6B7280; background: white; border: 1px solid #D1D5DB; border-radius: 6px; text-transform: none;")">Next</MudButton>
            <MudIconButton Icon="@Icons.Material.Filled.LastPage" Size="Size.Small" OnClick="@(() => OnPageChanged(_totalPage))" Disabled="@(_currentPage == _totalPage || _totalPage == 0)" Style="@(_currentPage == _totalPage || _totalPage == 0 ? "color: #D1D5DB; background: transparent;" : "color: #6B7280; background: white; border: 1px solid #D1D5DB; border-radius: 6px;")" />
        </div>
    </div>
</MudPaper>

<style>
    .mud-input-outlined-border { border-radius: 0px !important; }
    .custom-select-dense .mud-input-control { margin-top: 0 !important; }
    .custom-select-dense .mud-input-slot { padding-top: 4px !important; padding-bottom: 4px !important; padding-left: 8px !important; font-size: 12px !important; }
</style>
<style>
    .mud-table-styled .mud-table-row:hover { background-color: #F9FAFB !important; }
</style>

@code {
    private List<LogFileInfo> _allLogFiles = new();
    private LogFileInfo? _selectedFile;
    private string _searchString = "";
    private bool _isRefreshing = false;
    private bool _isDownloading = false;

    private int _skip = 0;
    private int _top = 5;
    private int _totalPage => GetFilteredData().Count() == 0 ? 0 : (int)Math.Ceiling((double)GetFilteredData().Count() / _top);
    private int _currentPage => (_skip / _top) + 1;

    public class LogFileInfo
    {
        public string FileName { get; set; } = "";
        public string FullPath { get; set; } = "";
        public DateTime LastModified { get; set; }
        public string FileSize { get; set; } = "";
        public long SizeInBytes { get; set; }
    }

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

    private async Task HandleRefresh()
    {
        _selectedFile = null;
        _skip = 0;
        StateHasChanged();
        await LoadFilesAsync();
        StateHasChanged();
    }

    private async Task LoadFilesAsync()
    {
        _isRefreshing = true;
        _allLogFiles.Clear();
        string configPath = Configuration["LoggerSettings:File:Path"] ?? "wwwroot/xlogs/app-log-.txt";
        string? directoryPath = Path.GetDirectoryName(configPath);
        if (string.IsNullOrEmpty(directoryPath)) directoryPath = "wwwroot/xlogs";
        string fullDirectoryPath = Path.Combine(Env.ContentRootPath, directoryPath);

        if (Directory.Exists(fullDirectoryPath))
        {
            var files = new DirectoryInfo(fullDirectoryPath).GetFiles("*.txt");
            foreach (var file in files.OrderByDescending(f => f.LastWriteTime))
            {
                _allLogFiles.Add(new LogFileInfo
                {
                    FileName = file.Name,
                    FullPath = file.FullName,
                    LastModified = file.LastWriteTime,
                    SizeInBytes = file.Length,
                    FileSize = GetFriendlyFileSize(file.Length)
                });
            }            
            await Task.Delay(500);
        }        
        _isRefreshing = false;
    }

    private IEnumerable<LogFileInfo> GetFilteredData()
    {
        if (string.IsNullOrWhiteSpace(_searchString)) return _allLogFiles;
        return _allLogFiles.Where(x => x.FileName.Contains(_searchString, StringComparison.OrdinalIgnoreCase));
    }

    private IEnumerable<LogFileInfo> GetPagedData() => GetFilteredData().Skip(_skip).Take(_top);

    private void OnSearchClick()
    {
        _skip = 0;
        _selectedFile = null;
        StateHasChanged();
    }

    private void HandleSearchKeyDown(KeyboardEventArgs e)
    {
        if (e.Key == "Enter") OnSearchClick();
    }

    private void OnPageChanged(int page)
    {
        if (page >= 1 && page <= _totalPage)
        {
            _skip = (page - 1) * _top;
            _selectedFile = null;
            StateHasChanged();
        }
    }

    private void OnPageSizeChanged(int size)
    {
        _top = size;
        _skip = 0;
        _selectedFile = null;
        StateHasChanged();
    }

    private void HandleRowClick(TableRowClickEventArgs<LogFileInfo> args)
    {
        _selectedFile = (_selectedFile?.FullPath == args.Item.FullPath) ? null : args.Item;
    }

    private async Task DownloadFile()
    {
        if (_selectedFile == null) return;

        _isDownloading = true;
        StateHasChanged();

        try
        {
            await Task.Delay(1000);
            var bytes = await File.ReadAllBytesAsync(_selectedFile.FullPath);
            using var stream = new MemoryStream(bytes);
            using var streamRef = new DotNetStreamReference(stream);

            await JS.InvokeVoidAsync("downloadFileFromStream", _selectedFile.FileName, streamRef);
            Snackbar.Add("Log file downloaded successfully", Severity.Success);
        }
        catch (Exception ex)
        {
            Snackbar.Add($"Download failed: {ex.Message}", Severity.Error);
        }
        finally
        {
            _isDownloading = false;
            StateHasChanged();
        }
    }

    private string GetFriendlyFileSize(long bytes)
    {
        string[] suffix = { "B", "KB", "MB", "GB" };
        int i;
        double dblSByte = bytes;
        for (i = 0; i < suffix.Length && bytes >= 1024; i++, bytes /= 1024)
        {
            dblSByte = bytes / 1024.0;
        }
        return $"{dblSByte:0.##} {suffix[i]}";
    }
}

<script>
    window.downloadFileFromStream = async (fileName, contentStreamReference) => {
        const arrayBuffer = await contentStreamReference.arrayBuffer();
        const blob = new Blob([arrayBuffer]);
        const url = URL.createObjectURL(blob);
        const anchorElement = document.createElement('a');
        anchorElement.href = url;
        anchorElement.download = fileName ?? '';
        anchorElement.click();
        anchorElement.remove();
        URL.revokeObjectURL(url);
    }
</script>