using Microsoft.JSInterop;

namespace DiunaBI.UI.Shared.Services;

public class DateTimeHelper
{
    private readonly IJSRuntime _jsRuntime;
    private TimeZoneInfo? _userTimeZone;
    private bool _initialized = false;

    public DateTimeHelper(IJSRuntime jsRuntime)
    {
        _jsRuntime = jsRuntime;
    }

    public async Task InitializeAsync()
    {
        if (_initialized) return;

        try
        {
            // Get the user's timezone from JavaScript
            var timeZoneId = await _jsRuntime.InvokeAsync<string>("eval", "Intl.DateTimeFormat().resolvedOptions().timeZone");

            // Try to find the TimeZoneInfo
            try
            {
                _userTimeZone = TimeZoneInfo.FindSystemTimeZoneById(timeZoneId);
            }
            catch
            {
                // Fallback to local timezone if the IANA timezone ID is not found
                _userTimeZone = TimeZoneInfo.Local;
            }
        }
        catch
        {
            // Fallback to local timezone if JavaScript interop fails
            _userTimeZone = TimeZoneInfo.Local;
        }

        _initialized = true;
    }

    public string FormatDateTime(DateTime? dateTime, string format = "yyyy-MM-dd HH:mm:ss")
    {
        if (!dateTime.HasValue)
            return "-";

        if (!_initialized)
        {
            // If not initialized yet, just format as-is (will be UTC)
            return dateTime.Value.ToString(format);
        }

        // Convert UTC to user's timezone
        var localDateTime = TimeZoneInfo.ConvertTimeFromUtc(dateTime.Value, _userTimeZone ?? TimeZoneInfo.Local);
        return localDateTime.ToString(format);
    }

    public string FormatDate(DateTime? dateTime, string format = "yyyy-MM-dd")
    {
        return FormatDateTime(dateTime, format);
    }

    public string FormatTime(DateTime? dateTime, string format = "HH:mm:ss")
    {
        return FormatDateTime(dateTime, format);
    }

    public string GetTimeZoneAbbreviation()
    {
        if (!_initialized || _userTimeZone == null)
            return "UTC";

        return _userTimeZone.IsDaylightSavingTime(DateTime.Now)
            ? _userTimeZone.DaylightName
            : _userTimeZone.StandardName;
    }
}
