namespace VoiceCat.App.Forms;

/// <summary>
/// Prompt for a ban reason and duration.
/// </summary>
public sealed class BanUserDialog : Form
{
    private readonly TextBox _txtReason;
    private readonly ComboBox _cboDuration;

    public string Reason => _txtReason.Text.Trim();
    public ulong ExpiresUnixMs { get; private set; }

    public BanUserDialog(string nickname)
    {
        Text = $"Ban {nickname}";
        FormBorderStyle = FormBorderStyle.FixedDialog;
        MaximizeBox = false;
        MinimizeBox = false;
        StartPosition = FormStartPosition.CenterParent;
        AutoScaleMode = AutoScaleMode.Font;
        ClientSize = new Size(384, 160);

        var lblReason = new Label
        {
            Text = "&Reason:",
            Location = new Point(12, 12),
            AutoSize = true,
        };
        _txtReason = new TextBox
        {
            Location = new Point(12, 34),
            Size = new Size(360, 23),
            TabIndex = 1,
        };

        var lblDuration = new Label
        {
            Text = "&Duration:",
            Location = new Point(12, 66),
            AutoSize = true,
        };
        _cboDuration = new ComboBox
        {
            Location = new Point(12, 88),
            Size = new Size(200, 23),
            DropDownStyle = ComboBoxStyle.DropDownList,
            TabIndex = 2,
        };
        _cboDuration.Items.AddRange(new object[]
        {
            new DurationItem("1 hour", TimeSpan.FromHours(1)),
            new DurationItem("1 day", TimeSpan.FromDays(1)),
            new DurationItem("1 week", TimeSpan.FromDays(7)),
            new DurationItem("Permanent", TimeSpan.Zero),
        });
        _cboDuration.SelectedIndex = 1;

        var btnOk = new Button
        {
            Text = "&Ban",
            DialogResult = DialogResult.OK,
            Location = new Point(216, 126),
            Size = new Size(75, 27),
            TabIndex = 3,
        };
        var btnCancel = new Button
        {
            Text = "&Cancel",
            DialogResult = DialogResult.Cancel,
            Location = new Point(297, 126),
            Size = new Size(75, 27),
            TabIndex = 4,
        };

        AcceptButton = btnOk;
        CancelButton = btnCancel;
        Controls.AddRange([lblReason, _txtReason, lblDuration, _cboDuration, btnOk, btnCancel]);

        btnOk.Click += (_, _) =>
        {
            var selected = _cboDuration.SelectedItem as DurationItem;
            ExpiresUnixMs = selected?.Duration == TimeSpan.Zero
                ? 0
                : (ulong)DateTimeOffset.UtcNow.Add(selected!.Duration).ToUnixTimeMilliseconds();
        };
    }

    private sealed class DurationItem(string label, TimeSpan duration)
    {
        public TimeSpan Duration { get; } = duration;
        public override string ToString() => label;
    }
}
