using AMKronos.Models;
using Microsoft.AspNetCore.Components;

namespace AMKronos.Components.Pages;

public partial class Zeiterfassung : ComponentBase
{
    private MonthData CurrentMonth { get; set; } = new();

    protected override void OnInitialized()
    {
        var now = DateTime.Now;
        CurrentMonth.MonthKey = $"{now.Year:0000}-{now.Month:00}";
        GenerateDays(CurrentMonth.MonthKey);
    }

    private void GenerateDays(string monthKey)
    {
        if (string.IsNullOrWhiteSpace(monthKey) || !DateTime.TryParse($"{monthKey}-01", out var monthStart))
        {
            return;
        }

        var daysInMonth = DateTime.DaysInMonth(monthStart.Year, monthStart.Month);
        var existingDays = CurrentMonth.Days.ToDictionary(d => d.Date.Date);

        CurrentMonth.Days.Clear();

        for (int day = 1; day <= daysInMonth; day++)
        {
            var date = new DateTime(monthStart.Year, monthStart.Month, day);

            if (existingDays.TryGetValue(date.Date, out var existingDay))
            {
                CurrentMonth.Days.Add(existingDay);
            }
            else
            {
                CurrentMonth.Days.Add(new DayEntry
                {
                    Date = date
                });
            }
        }
    }

    private void OnMonthKeyChanged(ChangeEventArgs e)
    {
        if (e.Value != null)
        {
            CurrentMonth.MonthKey = e.Value.ToString() ?? "";
            GenerateDays(CurrentMonth.MonthKey);
        }
    }

    private void OnTimeChangedTyped(DayEntry day, string field, TimeSpan? value)
    {
        switch (field)
        {
            case "beginn":
                day.Beginn = value;
                break;
            case "ende":
                day.Ende = value;
                break;
            case "pause":
                day.Pause = value;
                break;
        }
    }

    private double GesamtDezimal
    {
        get
        {
            return CurrentMonth.Days.Sum(d => d.GesamtDezimal);
        }
    }

    private TimeSpan GesamtZeit
    {
        get
        {
            var totalMinutes = CurrentMonth.Days.Sum(d => d.Zeit.TotalMinutes);
            return TimeSpan.FromMinutes(totalMinutes);
        }
    }

    private string FormatZeit(TimeSpan zeit)
    {
        if (zeit == TimeSpan.Zero)
        {
            return "0:00";
        }

        var hours = (int)Math.Floor(zeit.TotalHours);
        var minutes = zeit.Minutes;
        return $"{hours}:{minutes:00}";
    }
}
