using VoiceCat.Interop;

namespace VoiceCat.App.Forms;

/// <summary>
/// Prompt the moderator to pick a destination channel for a user move.
/// </summary>
public sealed class MoveUserDialog : Form
{
    private readonly ComboBox _cboChannel;

    public uint SelectedChannelId { get; private set; }

    public MoveUserDialog(IEnumerable<ChannelInfo> channels, uint currentChannelId)
    {
        Text = "Move user to channel";
        FormBorderStyle = FormBorderStyle.FixedDialog;
        MaximizeBox = false;
        MinimizeBox = false;
        StartPosition = FormStartPosition.CenterParent;
        AutoScaleMode = AutoScaleMode.Font;
        ClientSize = new Size(384, 120);

        var lbl = new Label
        {
            Text = "&Destination channel:",
            Location = new Point(12, 12),
            AutoSize = true,
        };

        _cboChannel = new ComboBox
        {
            Location = new Point(12, 36),
            Size = new Size(360, 23),
            DropDownStyle = ComboBoxStyle.DropDownList,
            TabIndex = 1,
        };

        foreach (var ch in channels.OrderBy(c => c.Name))
        {
            _cboChannel.Items.Add(new ChannelItem(ch.Name, ch.Id));
            if (ch.Id == currentChannelId) _cboChannel.SelectedIndex = _cboChannel.Items.Count - 1;
        }
        if (_cboChannel.SelectedIndex < 0 && _cboChannel.Items.Count > 0)
            _cboChannel.SelectedIndex = 0;

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

        AcceptButton = btnOk;
        CancelButton = btnCancel;
        Controls.AddRange([lbl, _cboChannel, btnOk, btnCancel]);

        btnOk.Click += (_, _) =>
        {
            SelectedChannelId = (_cboChannel.SelectedItem as ChannelItem)?.Id ?? 0;
        };
    }

    private sealed class ChannelItem(string name, uint id)
    {
        public uint Id { get; } = id;
        public override string ToString() => name;
    }
}
