using FrontOffice.Main.Utilities;
using Microsoft.AspNetCore.Components;
using MudBlazor;

namespace FrontOffice.Main.Pages.Profile;

public partial class WithdrawalRequests : ComponentBase
{
    [Inject] private CommissionService CommissionService { get; set; } = default!;
    
    private long _minWithdrawalAmount = 1_000_000;
    private List<WalletWithdrawal> _withdrawals = new();
    private List<CommissionPayoutDto> _availablePayouts = new();
    private string _statusFilter = "all";
    private bool _isLoading = true;
    private bool _isSubmittingWithdrawal;
    private CommissionPayoutDto? _selectedPayout;
    private WithdrawalMethodClient _withdrawMethod = WithdrawalMethodClient.Cash;
    private string? _withdrawIban;

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

    private async Task LoadData()
    {
        _isLoading = true;
        try
        {
            _withdrawals = await WalletService.GetWithdrawalsAsync();
            _availablePayouts = await CommissionService.GetWithdrawablePayoutsAsync();
            var settings = await WalletService.GetWithdrawalSettingsAsync();
            if (settings.MinWithdrawalAmount > 0)
                _minWithdrawalAmount = settings.MinWithdrawalAmount;
        }
        finally
        {
            _isLoading = false;
        }
    }

    private static string FormatPrice(long price) => string.Format("{0:N0} تومان", price);

    private async Task SubmitWithdrawal()
    {
        if (_selectedPayout == null)
        {
            Snackbar.Add("لطفاً یک واریز را انتخاب کنید.", Severity.Warning);
            return;
        }
        if (_withdrawMethod == WithdrawalMethodClient.Cash && string.IsNullOrWhiteSpace(_withdrawIban))
        {
            Snackbar.Add("برای برداشت نقدی، شماره شبا لازم است.", Severity.Warning);
            return;
        }

        try
        {
            _isSubmittingWithdrawal = true;

            string? normalizedIban = null;
            if (_withdrawMethod == WithdrawalMethodClient.Cash)
            {
                normalizedIban = NormalizeIranianIban(_withdrawIban);
                if (normalizedIban is null)
                {
                    Snackbar.Add("فرمت شماره شبا معتبر نیست. باید IR و ۲۴ رقم باشد (خط تیره اختیاری است).", Severity.Warning);
                    return;
                }
            }

            await WalletService.RequestWithdrawalAsync(_selectedPayout.Id, _withdrawMethod, normalizedIban);
            Snackbar.Add("درخواست برداشت ثبت شد.", Severity.Success);
            
            // بروزرسانی لیست
            await LoadData();
            
            // ریست فرم
            _selectedPayout = null;
            _withdrawIban = null;
        }
        catch (Exception ex)
        {
            Snackbar.Add($"خطا در ثبت برداشت: {ex.Message}", Severity.Error);
        }
        finally
        {
            _isSubmittingWithdrawal = false;
        }
    }

    private async Task ApplyFilter()
    {
        _isLoading = true;
        try
        {
            int? status = _statusFilter switch
            {
                "pending" => 1,
                "requested" => 2,
                "withdrawn" => 3,
                "cancelled" => 4,
                _ => null
            };
            _withdrawals = await WalletService.GetWithdrawalsAsync(status);
        }
        finally
        {
            _isLoading = false;
        }
    }

    private static string ResolveStatusText(int status) => status switch
    {
        0 => "ایجاد شده",
        1 => "در انتظار پرداخت",
        2 => "درخواست برداشت",
        3 => "برداشت شده",
        4 => "لغو شده",
        _ => status.ToString()
    };

    private static Color ResolveStatusColor(int status) => status switch
    {
        1 => Color.Info,
        2 => Color.Warning,
        3 => Color.Success,
        4 => Color.Error,
        _ => Color.Default
    };

    private static string ResolveMethodText(int? method) => method switch
    {
        0 => "نقدی (شبا)",
        1 => "الماس",
        _ => "-"
    };

    /// <summary>
    /// فاصله و خط تیره را حذف می‌کند و شبا را به شکل IR + ۲۴ رقم برمی‌گرداند.
    /// </summary>
    private static string? NormalizeIranianIban(string? iban)
    {
        if (string.IsNullOrWhiteSpace(iban))
            return null;

        var normalized = iban.Trim().ToUpperInvariant()
            .Replace(" ", "", StringComparison.Ordinal)
            .Replace("-", "", StringComparison.Ordinal);

        if (normalized.StartsWith("IR", StringComparison.Ordinal))
            normalized = normalized[2..];

        normalized = "IR" + normalized;

        return System.Text.RegularExpressions.Regex.IsMatch(normalized, @"^IR\d{24}$")
            ? normalized
            : null;
    }
}
