@*
    EN: Return/Exchange Dialog — Reusable MudDialog for processing returns and exchanges.
        Search original order, select items to return, choose return or exchange mode,
        scan new items for exchange, calculate refund/price difference.
    VI: Dialog Tra/Doi hang — MudDialog tai su dung de xu ly tra va doi hang.
        Tim don goc, chon san pham tra, chon che do tra hoac doi,
        quet san pham moi de doi, tinh hoan tien/chenh lech.
*@
@using WebClientTpos.Client.Services
@inject PosDataService DataService
@inject ISnackbar Snackbar

<MudDialog>
    <TitleContent>
        <div style="display:flex;align-items:center;gap:10px;">
            <i data-lucide="rotate-ccw" style="width:20px;height:20px;color:var(--pos-orange-primary);"></i>
            <span style="font-weight:700;">Tra hang / Doi hang</span>
        </div>
    </TitleContent>
    <DialogContent>
        <div style="min-width:700px;max-height:70vh;overflow-y:auto;">

            @* ═══ ORDER LOOKUP / TRA CUU DON HANG ═══ *@
            <div style="margin-bottom:16px;">
                <MudTextField @bind-Value="_orderIdInput" Label="Ma don goc" Placeholder="Nhap ma don hang..."
                              Variant="Variant.Outlined" Adornment="Adornment.End" AdornmentIcon="@Icons.Material.Filled.Search"
                              OnAdornmentClick="LookupOrder" OnKeyDown="OnOrderKeyDown"
                              FullWidth="true" Margin="Margin.Dense" />
            </div>

            @if (_isSearching)
            {
                <div style="text-align:center;padding:20px;">
                    <MudProgressCircular Indeterminate="true" Size="Size.Small" Color="Color.Warning" />
                    <div style="margin-top:8px;font-size:13px;color:var(--pos-text-tertiary);">Dang tim don hang...</div>
                </div>
            }
            else if (_orderNotFound)
            {
                <MudAlert Severity="Severity.Warning" Dense="true" Class="mb-3">
                    Khong tim thay don hang voi ma nay
                </MudAlert>
            }
            else if (_orderDetail != null)
            {
                @* ═══ ORDER INFO / THONG TIN DON HANG ═══ *@
                <MudPaper Outlined="true" Class="pa-3 mb-3">
                    <div style="display:flex;justify-content:space-between;align-items:center;">
                        <div>
                            <MudText Typo="Typo.subtitle1" Style="font-weight:700;">Don hang #@_orderDetail.Order?.Id.ToString()[..8]</MudText>
                            <MudText Typo="Typo.caption" Color="Color.Default">@_orderDetail.Order?.CreatedAt.ToString("dd/MM/yyyy HH:mm") - @_orderDetail.Order?.Status</MudText>
                        </div>
                        <MudText Typo="Typo.subtitle1" Color="Color.Warning" Style="font-weight:700;">
                            @FormatPrice(_orderDetail.Order?.TotalAmount ?? 0)
                        </MudText>
                    </div>
                </MudPaper>

                @* ═══ MODE TOGGLE / CHUYEN CHE DO ═══ *@
                <div style="display:flex;gap:8px;margin-bottom:16px;">
                    <MudButton Variant="@(_mode == ReturnMode.Return ? Variant.Filled : Variant.Outlined)"
                               Color="Color.Warning" OnClick="@(() => _mode = ReturnMode.Return)"
                               StartIcon="@Icons.Material.Filled.AssignmentReturn" Size="Size.Small">
                        Tra hang
                    </MudButton>
                    <MudButton Variant="@(_mode == ReturnMode.Exchange ? Variant.Filled : Variant.Outlined)"
                               Color="Color.Info" OnClick="@(() => _mode = ReturnMode.Exchange)"
                               StartIcon="@Icons.Material.Filled.SwapHoriz" Size="Size.Small">
                        Doi hang
                    </MudButton>
                </div>

                @* ═══ SELECT RETURN ITEMS / CHON SAN PHAM TRA ═══ *@
                <MudText Typo="Typo.subtitle2" Class="mb-2" Style="font-weight:600;">Chon san pham tra lai</MudText>
                <MudSimpleTable Dense="true" Hover="true" Class="mb-3" Style="background:transparent;">
                    <thead>
                        <tr>
                            <th style="width:40px;"></th>
                            <th>San pham</th>
                            <th style="width:80px;text-align:center;">SL goc</th>
                            <th style="width:100px;text-align:center;">So luong tra</th>
                            <th style="width:120px;text-align:right;">Thanh tien</th>
                        </tr>
                    </thead>
                    <tbody>
                        @if (_orderDetail.Items != null)
                        {
                            @foreach (var item in _returnItems)
                            {
                                <tr>
                                    <td>
                                        <MudCheckBox @bind-Value="item.Selected" Color="Color.Warning" Dense="true" />
                                    </td>
                                    <td>
                                        <MudText Typo="Typo.body2">@item.ProductName</MudText>
                                    </td>
                                    <td style="text-align:center;">@item.OriginalQty</td>
                                    <td style="text-align:center;">
                                        @if (item.Selected)
                                        {
                                            <MudNumericField @bind-Value="item.ReturnQty" Min="1" Max="item.OriginalQty"
                                                             Variant="Variant.Outlined" Margin="Margin.Dense"
                                                             Style="max-width:80px;" HideSpinButtons="false" />
                                        }
                                    </td>
                                    <td style="text-align:right;font-weight:600;color:var(--pos-danger);">
                                        @if (item.Selected)
                                        {
                                            <span>-@FormatPrice(item.UnitPrice * item.ReturnQty)</span>
                                        }
                                    </td>
                                </tr>
                            }
                        }
                    </tbody>
                </MudSimpleTable>

                @* ═══ EXCHANGE: NEW ITEMS SCANNER / DOI: QUET SAN PHAM MOI ═══ *@
                @if (_mode == ReturnMode.Exchange)
                {
                    <MudDivider Class="my-3" />
                    <MudText Typo="Typo.subtitle2" Class="mb-2" Style="font-weight:600;">San pham doi moi</MudText>

                    <div style="display:flex;gap:8px;margin-bottom:12px;">
                        <MudTextField @bind-Value="_exchangeBarcodeInput" Label="Quet ma vach san pham moi"
                                      Variant="Variant.Outlined" Margin="Margin.Dense" FullWidth="true"
                                      OnKeyDown="OnExchangeBarcodeKeyDown" />
                        <MudButton Variant="Variant.Filled" Color="Color.Info" OnClick="SearchExchangeProduct"
                                   StartIcon="@Icons.Material.Filled.Search" Size="Size.Small">
                            Tim
                        </MudButton>
                    </div>

                    @if (_exchangeItems.Any())
                    {
                        <MudSimpleTable Dense="true" Hover="true" Class="mb-3" Style="background:transparent;">
                            <thead>
                                <tr>
                                    <th>San pham moi</th>
                                    <th style="width:100px;text-align:center;">So luong</th>
                                    <th style="width:120px;text-align:right;">Don gia</th>
                                    <th style="width:120px;text-align:right;">Thanh tien</th>
                                    <th style="width:40px;"></th>
                                </tr>
                            </thead>
                            <tbody>
                                @foreach (var item in _exchangeItems)
                                {
                                    <tr>
                                        <td><MudText Typo="Typo.body2">@item.Name</MudText></td>
                                        <td style="text-align:center;">
                                            <MudNumericField @bind-Value="item.Qty" Min="1"
                                                             Variant="Variant.Outlined" Margin="Margin.Dense"
                                                             Style="max-width:80px;" HideSpinButtons="false" />
                                        </td>
                                        <td style="text-align:right;">@FormatPrice(item.UnitPrice)</td>
                                        <td style="text-align:right;font-weight:600;color:var(--pos-success);">
                                            +@FormatPrice(item.UnitPrice * item.Qty)
                                        </td>
                                        <td>
                                            <MudIconButton Icon="@Icons.Material.Filled.Delete" Size="Size.Small"
                                                           Color="Color.Error" OnClick="@(() => _exchangeItems.Remove(item))" />
                                        </td>
                                    </tr>
                                }
                            </tbody>
                        </MudSimpleTable>
                    }
                }

                @* ═══ REASON / LY DO ═══ *@
                <MudTextField @bind-Value="_reason" Label="Ly do tra/doi hang *" Placeholder="Nhap ly do..."
                              Variant="Variant.Outlined" FullWidth="true" Margin="Margin.Dense" Required="true"
                              Lines="2" Class="mb-3" />

                @* ═══ SUMMARY / TOM TAT ═══ *@
                <MudPaper Outlined="true" Class="pa-3" Style="background:var(--pos-bg-interactive);">
                    <div style="display:flex;justify-content:space-between;margin-bottom:8px;">
                        <MudText Typo="Typo.body2" Color="Color.Default">Tong tra:</MudText>
                        <MudText Typo="Typo.body2" Color="Color.Error" Style="font-weight:700;">
                            -@FormatPrice(ReturnTotal)
                        </MudText>
                    </div>
                    @if (_mode == ReturnMode.Exchange)
                    {
                        <div style="display:flex;justify-content:space-between;margin-bottom:8px;">
                            <MudText Typo="Typo.body2" Color="Color.Default">Tong doi moi:</MudText>
                            <MudText Typo="Typo.body2" Color="Color.Success" Style="font-weight:700;">
                                +@FormatPrice(ExchangeTotal)
                            </MudText>
                        </div>
                    }
                    <MudDivider Class="my-2" />
                    <div style="display:flex;justify-content:space-between;">
                        <MudText Typo="Typo.subtitle1" Style="font-weight:700;">
                            @(_mode == ReturnMode.Return ? "Hoan tien:" : (Difference >= 0 ? "Khach tra them:" : "Hoan tien:"))
                        </MudText>
                        <MudText Typo="Typo.subtitle1" Style="font-weight:800;font-size:20px;"
                                 Color="@(Difference >= 0 ? Color.Warning : Color.Error)">
                            @(Difference >= 0 ? "" : "-")@FormatPrice(Math.Abs(Difference))
                        </MudText>
                    </div>
                </MudPaper>
            }
        </div>
    </DialogContent>
    <DialogActions>
        <MudButton OnClick="Cancel" Variant="Variant.Text">Huy</MudButton>
        <MudButton OnClick="Confirm" Variant="Variant.Filled" Color="Color.Warning"
                   Disabled="@(!CanConfirm)" StartIcon="@Icons.Material.Filled.Check">
            Xac nhan @(_mode == ReturnMode.Return ? "tra hang" : "doi hang")
        </MudButton>
    </DialogActions>
</MudDialog>

@code {
    [CascadingParameter] private IMudDialogInstance MudDialog { get; set; } = default!;

    /// <summary>
    /// EN: Shop ID for API calls.
    /// VI: ID cua hang cho cac cuoc goi API.
    /// </summary>
    [Parameter] public Guid ShopId { get; set; }

    // EN: State / VI: Trang thai
    private string _orderIdInput = "";
    private bool _isSearching;
    private bool _orderNotFound;
    private bool _isProcessing;
    private ReturnMode _mode = ReturnMode.Return;
    private string _reason = "";
    private string _exchangeBarcodeInput = "";

    private PosDataService.OrderDetailResponse? _orderDetail;
    private List<ReturnItemModel> _returnItems = new();
    private readonly List<ExchangeItemModel> _exchangeItems = new();

    // EN: Calculated totals / VI: Tong tinh toan
    private decimal ReturnTotal => _returnItems.Where(i => i.Selected).Sum(i => i.UnitPrice * i.ReturnQty);
    private decimal ExchangeTotal => _exchangeItems.Sum(i => i.UnitPrice * i.Qty);
    private decimal Difference => _mode == ReturnMode.Return ? -ReturnTotal : ExchangeTotal - ReturnTotal;

    private bool CanConfirm =>
        _orderDetail != null &&
        _returnItems.Any(i => i.Selected) &&
        !string.IsNullOrWhiteSpace(_reason) &&
        !_isProcessing &&
        (_mode == ReturnMode.Return || _exchangeItems.Any());

    private static string FormatPrice(decimal price) => price.ToString("N0") + "d";

    private async Task OnOrderKeyDown(KeyboardEventArgs e)
    {
        if (e.Key == "Enter") await LookupOrder();
    }

    private async Task OnExchangeBarcodeKeyDown(KeyboardEventArgs e)
    {
        if (e.Key == "Enter") await SearchExchangeProduct();
    }

    /// <summary>
    /// EN: Lookup original order by ID.
    /// VI: Tra cuu don hang goc theo ma.
    /// </summary>
    private async Task LookupOrder()
    {
        if (string.IsNullOrWhiteSpace(_orderIdInput)) return;

        _isSearching = true;
        _orderNotFound = false;
        _orderDetail = null;
        _returnItems.Clear();
        StateHasChanged();

        try
        {
            // EN: Try to parse as GUID first / VI: Thu parse thanh GUID truoc
            Guid orderId;
            if (!Guid.TryParse(_orderIdInput, out orderId))
            {
                _orderNotFound = true;
                return;
            }

            var detail = await DataService.GetOrderDetailAsync(orderId, ShopId);
            if (detail?.Order == null)
            {
                _orderNotFound = true;
                return;
            }

            _orderDetail = detail;
            _returnItems = detail.Items?.Select(i => new ReturnItemModel
            {
                OrderItemId = i.Id,
                ProductName = i.ProductName ?? "San pham",
                OriginalQty = i.Quantity,
                UnitPrice = i.UnitPrice,
                ReturnQty = i.Quantity,
                Selected = false
            }).ToList() ?? new();
        }
        catch
        {
            _orderNotFound = true;
            Snackbar.Add("Loi khi tra cuu don hang", Severity.Error);
        }
        finally
        {
            _isSearching = false;
        }
    }

    /// <summary>
    /// EN: Search and add a product for exchange.
    /// VI: Tim va them san pham de doi.
    /// </summary>
    private async Task SearchExchangeProduct()
    {
        if (string.IsNullOrWhiteSpace(_exchangeBarcodeInput)) return;

        try
        {
            var product = await DataService.LookupProductByBarcodeAsync(ShopId, _exchangeBarcodeInput);
            if (product != null)
            {
                var existing = _exchangeItems.FirstOrDefault(i => i.ProductId == product.Id);
                if (existing != null)
                {
                    existing.Qty++;
                }
                else
                {
                    _exchangeItems.Add(new ExchangeItemModel
                    {
                        ProductId = product.Id,
                        Name = product.Name,
                        UnitPrice = product.Price,
                        Qty = 1
                    });
                }
                _exchangeBarcodeInput = "";
            }
            else
            {
                Snackbar.Add("Khong tim thay san pham", Severity.Warning);
            }
        }
        catch
        {
            Snackbar.Add("Loi khi tim san pham", Severity.Error);
        }
    }

    /// <summary>
    /// EN: Confirm return or exchange.
    /// VI: Xac nhan tra hoac doi hang.
    /// </summary>
    private async Task Confirm()
    {
        if (!CanConfirm) return;

        _isProcessing = true;
        StateHasChanged();

        try
        {
            var selectedItems = _returnItems.Where(i => i.Selected).Select(i =>
                new PosDataService.ReturnItemInfo(i.OrderItemId, i.ReturnQty, _reason)).ToList();

            if (_mode == ReturnMode.Return)
            {
                var (ok, error) = await DataService.CreateReturnAsync(ShopId, _orderDetail!.Order!.Id, selectedItems, _reason);
                if (ok)
                {
                    Snackbar.Add("Tra hang thanh cong!", Severity.Success);
                    MudDialog.Close(DialogResult.Ok(true));
                }
                else
                {
                    Snackbar.Add(error ?? "Khong the xu ly tra hang", Severity.Error);
                }
            }
            else
            {
                var newItems = _exchangeItems.Select(i =>
                    new PosDataService.ExchangeItemInfo(i.ProductId, i.Qty, i.UnitPrice)).ToList();

                var (ok, error) = await DataService.CreateExchangeAsync(ShopId, _orderDetail!.Order!.Id,
                    selectedItems, newItems, _reason);
                if (ok)
                {
                    Snackbar.Add("Doi hang thanh cong!", Severity.Success);
                    MudDialog.Close(DialogResult.Ok(true));
                }
                else
                {
                    Snackbar.Add(error ?? "Khong the xu ly doi hang", Severity.Error);
                }
            }
        }
        catch
        {
            Snackbar.Add("Loi he thong khi xu ly", Severity.Error);
        }
        finally
        {
            _isProcessing = false;
        }
    }

    private void Cancel() => MudDialog.Cancel();

    // EN: Models / VI: Mo hinh du lieu
    private enum ReturnMode { Return, Exchange }

    private class ReturnItemModel
    {
        public Guid OrderItemId { get; set; }
        public string ProductName { get; set; } = "";
        public int OriginalQty { get; set; }
        public decimal UnitPrice { get; set; }
        public int ReturnQty { get; set; }
        public bool Selected { get; set; }
    }

    private class ExchangeItemModel
    {
        public Guid ProductId { get; set; }
        public string Name { get; set; } = "";
        public decimal UnitPrice { get; set; }
        public int Qty { get; set; } = 1;
    }
}
