using ComputerSalesApp.Models;
using ComputerSalesApp.Services;

namespace ComputerSalesApp.UI;

internal sealed class LoginForm : Form
{
    private readonly TextBox _loginTextBox = new();
    private readonly TextBox _passwordTextBox = new();
    private readonly Button _loginButton = new();
    private readonly Button _exitButton = new();
    private readonly AuthService _authService = new();

    public UserSession? Session { get; private set; }

    public LoginForm()
    {
        Text = "Авторизация | Продажа компьютерной техники";
        StartPosition = FormStartPosition.CenterScreen;
        MinimumSize = new Size(520, 430);
        MaximumSize = new Size(520, 430);
        BackColor = AppTheme.Background;
        FormBorderStyle = FormBorderStyle.FixedSingle;
        MaximizeBox = false;
        BuildUi();
    }

    private void BuildUi()
    {
        var root = new TableLayoutPanel
        {
            Dock = DockStyle.Fill,
            RowCount = 3,
            ColumnCount = 1
        };
        root.RowStyles.Add(new RowStyle(SizeType.Absolute, 100));
        root.RowStyles.Add(new RowStyle(SizeType.Percent, 100));
        root.RowStyles.Add(new RowStyle(SizeType.Absolute, 80));
        Controls.Add(root);

        var header = new Panel
        {
            Dock = DockStyle.Fill,
            BackColor = AppTheme.Header,
            Padding = new Padding(35, 20, 20, 10)
        };
        root.Controls.Add(header, 0, 0);

        var title = new Label
        {
            Text = "Вход в систему",
            ForeColor = Color.White,
            Font = AppTheme.Bold(18f),
            AutoSize = true,
            Location = new Point(35, 20)
        };
        header.Controls.Add(title);

        var subtitle = new Label
        {
            Text = "Продажа компьютерной техники",
            ForeColor = Color.WhiteSmoke,
            Font = AppTheme.Regular(10f),
            AutoSize = true,
            Location = new Point(38, 60)
        };
        header.Controls.Add(subtitle);

        var formPanel = new TableLayoutPanel
        {
            Dock = DockStyle.Fill,
            Padding = new Padding(45, 30, 45, 10),
            BackColor = AppTheme.Background,
            RowCount = 4,
            ColumnCount = 1
        };
        formPanel.RowStyles.Add(new RowStyle(SizeType.Absolute, 32));
        formPanel.RowStyles.Add(new RowStyle(SizeType.Absolute, 50));
        formPanel.RowStyles.Add(new RowStyle(SizeType.Absolute, 32));
        formPanel.RowStyles.Add(new RowStyle(SizeType.Absolute, 50));
        root.Controls.Add(formPanel, 0, 1);

        formPanel.Controls.Add(new Label
        {
            Text = "Логин:",
            Dock = DockStyle.Fill,
            TextAlign = ContentAlignment.BottomLeft,
            Font = AppTheme.Regular(10f)
        }, 0, 0);

        _loginTextBox.Dock = DockStyle.Top;
        _loginTextBox.Font = AppTheme.Regular(10f);
        _loginTextBox.Margin = new Padding(0, 5, 0, 0);
        formPanel.Controls.Add(_loginTextBox, 0, 1);

        formPanel.Controls.Add(new Label
        {
            Text = "Пароль:",
            Dock = DockStyle.Fill,
            TextAlign = ContentAlignment.BottomLeft,
            Font = AppTheme.Regular(10f)
        }, 0, 2);

        _passwordTextBox.Dock = DockStyle.Top;
        _passwordTextBox.Font = AppTheme.Regular(10f);
        _passwordTextBox.UseSystemPasswordChar = true;
        _passwordTextBox.Margin = new Padding(0, 5, 0, 0);
        formPanel.Controls.Add(_passwordTextBox, 0, 3);

        var buttonPanel = new FlowLayoutPanel
        {
            Dock = DockStyle.Fill,
            FlowDirection = FlowDirection.RightToLeft,
            Padding = new Padding(45, 15, 45, 10),
            BackColor = AppTheme.Background
        };
        root.Controls.Add(buttonPanel, 0, 2);

        _exitButton.Text = "Выход";
        _exitButton.Width = 130;
        _exitButton.Height = 42;
        _exitButton.Font = AppTheme.Bold(10f);
        AppTheme.StyleSecondaryButton(_exitButton);
        _exitButton.Click += (_, _) => Close();
        buttonPanel.Controls.Add(_exitButton);

        _loginButton.Text = "Войти";
        _loginButton.Width = 130;
        _loginButton.Height = 42;
        _loginButton.Font = AppTheme.Bold(10f);
        AppTheme.StylePrimaryButton(_loginButton);
        _loginButton.Click += LoginButton_Click;
        buttonPanel.Controls.Add(_loginButton);

        AcceptButton = _loginButton;
        CancelButton = _exitButton;

        _loginTextBox.Text = "admin";
        _passwordTextBox.Text = "admin123";
    }

    private async void LoginButton_Click(object? sender, EventArgs e)
    {
        string login = _loginTextBox.Text.Trim();
        string password = _passwordTextBox.Text;

        if (string.IsNullOrWhiteSpace(login) || string.IsNullOrWhiteSpace(password))
        {
            MessageBox.Show("Введите логин и пароль.", "Авторизация", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            return;
        }

        SetBusy(true);
        try
        {
            Session = await _authService.AuthenticateAsync(login, password);
            if (Session == null)
            {
                MessageBox.Show(
                    "Пользователь не найден, отключён или пароль введён неверно.",
                    "Ошибка авторизации",
                    MessageBoxButtons.OK,
                    MessageBoxIcon.Warning);
                return;
            }

            DialogResult = DialogResult.OK;
            Close();
        }
        catch (Exception ex)
        {
            ErrorHandler.Show("Ошибка авторизации", "Не удалось выполнить вход.", ex);
        }
        finally
        {
            SetBusy(false);
        }
    }

    private void SetBusy(bool busy)
    {
        _loginButton.Enabled = !busy;
        _exitButton.Enabled = !busy;
        _loginTextBox.Enabled = !busy;
        _passwordTextBox.Enabled = !busy;
        _loginButton.Text = busy ? "Проверка..." : "Войти";
        Cursor = busy ? Cursors.WaitCursor : Cursors.Default;
    }
}
