using System;
using Tornado3_2026Election.Common;
using Tornado3_2026Election.Domain;

namespace Tornado3_2026Election.ViewModels;

public sealed class PreElectionHistoryTurnoutEditRowViewModel : ObservableObject
{
    private string _electorsText;
    private string _votesText;

    public PreElectionHistoryTurnoutEditRowViewModel(int electionOrder, int year, PreElectionHistoricalTurnoutEntry? entry = null)
    {
        ElectionOrder = electionOrder;
        Year = year;
        _electorsText = entry?.Electors > 0 ? entry.Electors.ToString() : string.Empty;
        _votesText = entry?.Votes > 0 ? entry.Votes.ToString() : string.Empty;
    }

    public int ElectionOrder { get; }

    public int Year { get; }

    public string ElectorsText
    {
        get => _electorsText;
        set
        {
            if (SetProperty(ref _electorsText, value ?? string.Empty))
            {
                OnPropertyChanged(nameof(TurnoutRateDisplay));
            }
        }
    }

    public string VotesText
    {
        get => _votesText;
        set
        {
            if (SetProperty(ref _votesText, value ?? string.Empty))
            {
                OnPropertyChanged(nameof(TurnoutRateDisplay));
            }
        }
    }

    public string TurnoutRateDisplay
    {
        get
        {
            var electors = ParsePositiveInt(ElectorsText);
            var votes = ParsePositiveInt(VotesText);
            if (electors <= 0 || votes <= 0)
            {
                return "-";
            }

            return $"{Math.Round(votes * 100d / electors, 1, MidpointRounding.AwayFromZero):0.0}%";
        }
    }

    public PreElectionHistoricalTurnoutEntry? ToEntry()
    {
        var electors = ParsePositiveInt(ElectorsText);
        var votes = ParsePositiveInt(VotesText);
        if (electors <= 0 || votes <= 0)
        {
            return null;
        }

        return new PreElectionHistoricalTurnoutEntry
        {
            ElectionOrder = ElectionOrder,
            Year = Year,
            Electors = electors,
            Votes = votes,
            TurnoutRate = Math.Round(votes * 100d / electors, 1, MidpointRounding.AwayFromZero)
        };
    }

    private static int ParsePositiveInt(string? value)
    {
        if (string.IsNullOrWhiteSpace(value))
        {
            return 0;
        }

        var digits = value.Trim().Replace(",", string.Empty, StringComparison.Ordinal);
        return int.TryParse(digits, out var parsed) && parsed > 0
            ? parsed
            : 0;
    }
}
