using Microsoft.AspNetCore.Components;
using MudBlazor;
using System.Globalization;
using System.Reflection;

namespace BackOffice.Common.BaseComponents;

public partial class DateRangePicker
{
    private DateRange _dateRange = new();

    private MudDateRangePicker _picker;
    [Parameter] public string Label { get; set; } = "انتخاب بازه زمانی";
    [Parameter] public DateTime? DefaultStart { get; set; }
    [Parameter] public DateTime? DefaultEnd { get; set; }
    [Parameter] public EventCallback<DateRange> OnChanged { get; set; }
    protected override void OnInitialized()
    {
        base.OnInitialized();
        if (DefaultStart.HasValue)
            _dateRange.Start = DefaultStart.Value.Date;

        if (DefaultEnd.HasValue)
            _dateRange.End = DefaultEnd.Value.Date;
    }
    public CultureInfo GetPersianCulture()
    {
        var culture = new CultureInfo("fa-IR");
        DateTimeFormatInfo formatInfo = culture.DateTimeFormat;
        formatInfo.AbbreviatedDayNames = new[] { "ی", "د", "س", "چ", "پ", "ج", "ش" };
        formatInfo.DayNames = new[] { "یکشنبه", "دوشنبه", "سه شنبه", "چهار شنبه", "پنجشنبه", "جمعه", "شنبه" };
        var monthNames = new[]
        {
            "فروردین", "اردیبهشت", "خرداد", "تیر", "مرداد", "شهریور", "مهر", "آبان", "آذر", "دی", "بهمن",
            "اسفند",
            "",
        };
        formatInfo.AbbreviatedMonthNames =
            formatInfo.MonthNames =
                formatInfo.MonthGenitiveNames = formatInfo.AbbreviatedMonthGenitiveNames = monthNames;
        formatInfo.AMDesignator = "ق.ظ";
        formatInfo.PMDesignator = "ب.ظ";
        formatInfo.ShortDatePattern = "yyyy/MM/dd";
        formatInfo.LongDatePattern = "dddd, dd MMMM,yyyy";
        formatInfo.FirstDayOfWeek = DayOfWeek.Saturday;
        Calendar cal = new PersianCalendar();
        FieldInfo fieldInfo = culture.GetType().GetField("calendar", BindingFlags.NonPublic | BindingFlags.Instance);
        fieldInfo?.SetValue(culture, cal);
        FieldInfo info = formatInfo.GetType().GetField("calendar", BindingFlags.NonPublic | BindingFlags.Instance);
        info?.SetValue(formatInfo, cal);
        culture.NumberFormat.NumberDecimalSeparator = "/";
        culture.NumberFormat.DigitSubstitution = DigitShapes.NativeNational;
        culture.NumberFormat.NumberNegativePattern = 0;
        return culture;
    }
    private async Task OnClickOK()
    {
        if (_picker.DateRange is not null)
        {
            await OnChanged.InvokeAsync(_picker.DateRange);
        }

        await _picker.CloseAsync();
    }
    private async Task OnClickClear()
    {
        _dateRange = new DateRange();
        await OnChanged.InvokeAsync(_dateRange);
        await _picker.CloseAsync();
    }
}
