@using Indotalent.ConfigBackEnd.Extensions
@using Indotalent.Features.Inventory.PositiveAdjustment
@using Indotalent.Features.Inventory.PositiveAdjustment.Cqrs
@using Microsoft.AspNetCore.Components.Web
@using Microsoft.JSInterop
@using MudBlazor
@using Features.Root.Shared
@using ClosedXML.Excel
@using System.IO
@inject PositiveAdjustmentService PositiveAdjustmentService
@inject IDialogService DialogService
@inject ISnackbar Snackbar
@inject IJSRuntime JSRuntime

<MudPaper Elevation="0" 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;">Positive Adjustment</MudText>
        <MudText Typo="Typo.body2" Style="color: #9CA3AF;">Record stock additions and inventory corrections.</MudText>
    </div>
    <div class="d-flex align-center gap-2">
        <MudIcon Icon="@Icons.Material.Filled.Home" Size="Size.Small" Color="Color.Default" />
        <MudText Typo="Typo.caption" Style="color: #9CA3AF;">/</MudText>
        <MudText Typo="Typo.caption" Style="color: #9CA3AF;">Inventory</MudText>
        <MudText Typo="Typo.caption" Style="color: #9CA3AF;">/</MudText>
        <MudText Typo="Typo.caption" Style="font-weight: 600; color: #111827;">Positive Adjustment</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;">
                Search
            </MudButton>
        </div>

        <div style="display: flex; gap: 8px; align-items: center;">
            <MudButton Variant="Variant.Outlined"
                       Color="Color.Success"
                       OnClick="ExportToExcel"
                       Size="Size.Small"
                       Disabled="_isExporting"
                       StartIcon="@(_isExporting ? null : Icons.Custom.FileFormats.FileExcel)"
                       Style="background:white; font-weight: 500; border-radius: 6px; text-transform: none; height: 34px; border: 1px solid #D1D5DB;">
                @if (_isExporting)
                {
                    <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 Typo="Typo.button" Style="text-transform: none !important;">Excel</MudText>
                }
            </MudButton>

            <MudButton Variant="Variant.Outlined"
                       Color="Color.Primary"
                       OnClick="LoadData"
                       Size="Size.Small"
                       StartIcon="@(_isRefreshing ? null : Icons.Material.Filled.Refresh)"
                       Disabled="_isRefreshing"
                       Style="background:white; font-weight: 500; border-radius: 6px; text-transform: none; 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 (_selectedItem != null)
            {
                <MudButton Variant="Variant.Outlined" Color="Color.Info" StartIcon="@Icons.Material.Filled.Visibility" OnClick="InvokeView" Size="Size.Small" Style="text-transform: none; font-weight: 500; border-radius: 6px; background-color: white; border: 1px solid #D1D5DB;">View</MudButton>
                <MudButton Variant="Variant.Outlined" Color="Color.Primary" StartIcon="@Icons.Material.Filled.Edit" OnClick="InvokeEdit" Size="Size.Small" Style="text-transform: none; font-weight: 500; border-radius: 6px; background-color: white; border: 1px solid #D1D5DB;">Edit</MudButton>
                <MudButton Variant="Variant.Outlined" Color="Color.Error" StartIcon="@Icons.Material.Filled.Delete" OnClick="OnDelete" Size="Size.Small" Style="background: white; border: 1px solid #FCA5A5; color: #EF4444; text-transform: none; font-weight: 500; border-radius: 6px;">Remove</MudButton>
                <MudIconButton Icon="@Icons.Material.Filled.Close" Size="Size.Small" OnClick="() => _selectedItem = null" />
            }
            else
            {
                <MudButton Variant="Variant.Filled" Color="Color.Primary" StartIcon="@Icons.Material.Filled.Add" OnClick="() => OnAdd.InvokeAsync()" Size="Size.Small" Style="text-transform: none; font-weight: 500; border-radius: 6px; height: 34px;">
                    Add Positive Adjustment
                </MudButton>
            }
        </div>
    </div>

    <MudTable Class="mud-table-styled" Striped="true" Items="@GetPagedData()" Hover="true" Elevation="0" CustomHeader="true" Dense="true" T="GetPositiveAdjustmentListResponse" OnRowClick="@((args) => _selectedItem = args.Item)" Loading="@_isRefreshing">
        <HeaderContent>
            <MudTh Style="width: 50px; background-color: #F9FAFB; border-bottom: 1px solid #E5E7EB; letter-spacing: 0.05em;"></MudTh>
            <MudTh Style="font-weight: 600; color: #6B7280; text-transform: uppercase; font-size: 0.6875rem; background-color: #F9FAFB; border-bottom: 1px solid #E5E7EB; white-space: nowrap; letter-spacing: 0.05em;">
                <MudTableSortLabel SortBy="new Func<GetPositiveAdjustmentListResponse, object>(x => x.AutoNumber!)">Number</MudTableSortLabel>
            </MudTh>
            <MudTh Style="font-weight: 600; color: #6B7280; text-transform: uppercase; font-size: 0.6875rem; background-color: #F9FAFB; border-bottom: 1px solid #E5E7EB; white-space: nowrap; letter-spacing: 0.05em;">
                <MudTableSortLabel SortBy="new Func<GetPositiveAdjustmentListResponse, object>(x => x.AdjustmentDate!)">Adjustment Date</MudTableSortLabel>
            </MudTh>
            <MudTh Style="font-weight: 600; color: #6B7280; text-transform: uppercase; font-size: 0.6875rem; background-color: #F9FAFB; border-bottom: 1px solid #E5E7EB; white-space: nowrap; letter-spacing: 0.05em;">
                <MudTableSortLabel SortBy="new Func<GetPositiveAdjustmentListResponse, object>(x => x.Description!)">Description</MudTableSortLabel>
            </MudTh>
            <MudTh Style="font-weight: 600; color: #6B7280; text-transform: uppercase; font-size: 0.6875rem; background-color: #F9FAFB; border-bottom: 1px solid #E5E7EB; white-space: nowrap; letter-spacing: 0.05em;">
                <MudTableSortLabel SortBy="new Func<GetPositiveAdjustmentListResponse, object>(x => x.Status)">Status</MudTableSortLabel>
            </MudTh>
        </HeaderContent>
        <RowTemplate>
            <MudTd>
                <MudCheckBox T="bool" Value="@(_selectedItem?.Id == context.Id)" Color="Color.Primary" Dense="true" Size="Size.Small" ReadOnly="true" />
            </MudTd>
            <MudTd>@context.AutoNumber</MudTd>
            <MudTd>@context.AdjustmentDate?.ToString("yyyy-MM-dd")</MudTd>
            <MudTd>@context.Description</MudTd>
            <MudTd>
                <MudChip T="string" Color="Color.Info" Size="Size.Small" Variant="Variant.Text" Style="font-weight: 600;">@context.Status.ToString().ToUpper()</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="color: #9CA3AF; font-size: 0.75rem; font-weight: 500;">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 ? "background: transparent; color: #D1D5DB; border: none;" : "background-color: white; border: 1px solid #D1D5DB; color: #6B7280; 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 ? "text-transform: none; font-weight: 500; color: #D1D5DB;" : "text-transform: none; font-weight: 500; color: #6B7280; background: white; border: 1px solid #D1D5DB; border-radius: 6px;")">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 ? "text-transform: none; font-weight: 500; color: #D1D5DB;" : "text-transform: none; font-weight: 500; color: #6B7280; background: white; border: 1px solid #D1D5DB; border-radius: 6px;")">Next</MudButton>
            <MudIconButton Icon="@Icons.Material.Filled.LastPage" Size="Size.Small" OnClick="@(() => OnPageChanged(_totalPage))" Disabled="@(_currentPage == _totalPage || _totalPage == 0)" Style="@(_currentPage == _totalPage || _totalPage == 0 ? "background: transparent; color: #D1D5DB; border: none;" : "background-color: white; border: 1px solid #D1D5DB; color: #6B7280; border-radius: 6px;")" />
        </div>
    </div>
</MudPaper>

<script>
    function downloadFile(fileName, contentType, base64String) {
        const link = document.createElement('a');
        link.download = fileName;
        link.href = `data:${contentType};base64,${base64String}`;
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
    }
</script>

<style>
    .mud-table-styled .mud-table-row:hover { background-color: #F9FAFB !important; }
    .mud-table-styled .mud-table-cell { padding-top: 0.75rem; padding-bottom: 0.75rem; color: #6B7280; font-size: 0.875rem; }
    .mud-table-styled .mud-table-cell .mud-text-body2 { font-weight: 600; color: #374151; }
    .mud-input-outlined-border { border-radius: 8px !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>

@code {
    [Parameter] public EventCallback OnAdd { get; set; }
    [Parameter] public EventCallback<UpdatePositiveAdjustmentRequest> OnEdit { get; set; }
    [Parameter] public EventCallback<UpdatePositiveAdjustmentRequest> OnView { get; set; }

    private List<GetPositiveAdjustmentListResponse> _items = new();
    private GetPositiveAdjustmentListResponse? _selectedItem;
    private string _searchString = "";
    private bool _isRefreshing = false;
    private bool _isExporting = false;

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

    protected override async Task OnInitializedAsync() => await LoadData();

    private async Task LoadData()
    {
        _isRefreshing = true;
        _selectedItem = null;
        StateHasChanged();
        try
        {
            var response = await PositiveAdjustmentService.GetPositiveAdjustmentListAsync();
            await Task.Delay(500);
            if (response != null && response.IsSuccess)
            {
                _items = response.Value ?? new();
            }
        }
        finally
        {
            _isRefreshing = false;
            StateHasChanged();
        }
    }

    private IEnumerable<GetPositiveAdjustmentListResponse> GetFilteredData()
    {
        if (string.IsNullOrWhiteSpace(_searchString)) return _items;
        return _items.Where(x =>
            (x.AutoNumber?.Contains(_searchString, StringComparison.OrdinalIgnoreCase) ?? false) ||
            (x.Description?.Contains(_searchString, StringComparison.OrdinalIgnoreCase) ?? false)
        );
    }

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

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

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

    private async Task ExportToExcel()
    {
        _isExporting = true;
        StateHasChanged();
        try
        {
            await Task.Delay(1000);
            using (var workbook = new XLWorkbook())
            {
                var worksheet = workbook.Worksheets.Add("PositiveAdjustments");
                var currentRow = 1;

                worksheet.Cell(currentRow, 1).Value = "Number";
                worksheet.Cell(currentRow, 2).Value = "Adjustment Date";
                worksheet.Cell(currentRow, 3).Value = "Description";
                worksheet.Cell(currentRow, 4).Value = "Status";

                var headerRange = worksheet.Range(1, 1, 1, 4);
                headerRange.Style.Font.Bold = true;
                headerRange.Style.Fill.BackgroundColor = XLColor.FromHtml("#0D47A1");
                headerRange.Style.Font.FontColor = XLColor.White;

                foreach (var item in GetFilteredData())
                {
                    currentRow++;
                    worksheet.Cell(currentRow, 1).Value = item.AutoNumber;
                    worksheet.Cell(currentRow, 2).Value = item.AdjustmentDate?.ToString("yyyy-MM-dd");
                    worksheet.Cell(currentRow, 3).Value = item.Description;
                    worksheet.Cell(currentRow, 4).Value = item.Status.ToString();
                }

                worksheet.Columns().AdjustToContents();

                using (var stream = new MemoryStream())
                {
                    workbook.SaveAs(stream);
                    var content = Convert.ToBase64String(stream.ToArray());
                    await JSRuntime.InvokeVoidAsync("downloadFile", "PositiveAdjustment_List.xlsx", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", content);
                    Snackbar.Add("Excel exported successfully", Severity.Success);
                }
            }
        }
        catch (Exception ex)
        {
            Snackbar.Add($"Export failed: {ex.Message}", Severity.Error);
        }
        finally
        {
            _isExporting = false;
            StateHasChanged();
        }
    }

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

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

    private async Task InvokeEdit()
    {
        if (_selectedItem == null) return;
        var request = await MapToUpdateRequest(_selectedItem.Id!);
        if (request != null) await OnEdit.InvokeAsync(request);
    }

    private async Task InvokeView()
    {
        if (_selectedItem == null) return;
        var request = await MapToUpdateRequest(_selectedItem.Id!);
        if (request != null) await OnView.InvokeAsync(request);
    }

    private async Task<UpdatePositiveAdjustmentRequest?> MapToUpdateRequest(string id)
    {
        var response = await PositiveAdjustmentService.GetPositiveAdjustmentByIdAsync(id);
        if (response != null && response.IsSuccess && response.Value != null)
        {
            var detail = response.Value;
            return new UpdatePositiveAdjustmentRequest
            {
                Id = detail.Id,
                AdjustmentDate = detail.AdjustmentDate,
                Status = detail.Status,
                Description = detail.Description,
                CreatedAt = detail.CreatedAt,
                CreatedBy = detail.CreatedBy,
                UpdatedAt = detail.UpdatedAt,
                UpdatedBy = detail.UpdatedBy,
                AutoNumber = detail.AutoNumber
            };
        }
        return null;
    }

    private async Task OnDelete()
    {
        if (_selectedItem == null) return;

        var parameters = new DialogParameters<_DeleteConfirmation> { { x => x.ContentText, _selectedItem.AutoNumber } };
        var options = new DialogOptions { CloseButton = false, MaxWidth = MaxWidth.ExtraSmall, FullWidth = true };

        var dialog = await DialogService.ShowAsync<_DeleteConfirmation>("", parameters, options);
        var result = await dialog.Result;

        if (result != null && !result.Canceled)
        {
            var isSuccess = await PositiveAdjustmentService.DeletePositiveAdjustmentByIdAsync(_selectedItem.Id!);
            if (isSuccess)
            {
                _selectedItem = null;
                await LoadData();
                Snackbar.Add("Deleted successfully", Severity.Success);
            }
        }
    }
}