using TravelAgencyWinForms.Data;
using TravelAgencyWinForms.Services;
using TravelAgencyWinForms.Utils;

namespace TravelAgencyWinForms.Forms;

public partial class LoginForm : Form
{
    public LoginForm()
    {
        InitializeComponent();
        ApplyStyle();
        LoadIllustration();
        loginTextBox.Text = "admin";
    }

    private void ApplyStyle()
    {
        AppTheme.ApplyForm(this, true);
        AppTheme.StyleTextBox(loginTextBox);
        AppTheme.StyleTextBox(passwordTextBox);
        AppTheme.StylePrimaryButton(loginButton);
        AppTheme.StyleSecondaryButton(exitButton);

        titleLabel.ForeColor = AppTheme.Text;
        subtitleLabel.ForeColor = AppTheme.Muted;
        loginLabel.ForeColor = AppTheme.Text;
        passwordLabel.ForeColor = AppTheme.Text;
        statusLabel.ForeColor = AppTheme.Muted;
        rootPanel.BackColor = AppTheme.Background;
        imagePanel.BackColor = AppTheme.Surface;
        authPanel.BackColor = AppTheme.Surface;
    }

    private void LoadIllustration()
    {
        var image = AppTheme.LoadImage("login_welcome.png");
        if (image != null)
            welcomePictureBox.Image = image;
    }

    private void LoginButton_Click(object? sender, EventArgs e)
    {
        TryLogin();
    }

    private void ExitButton_Click(object? sender, EventArgs e)
    {
        Close();
    }

    private void PasswordTextBox_KeyDown(object? sender, KeyEventArgs e)
    {
        if (e.KeyCode != Keys.Enter)
            return;

        e.SuppressKeyPress = true;
        TryLogin();
    }

    private void TryLogin()
    {
        if (string.IsNullOrWhiteSpace(loginTextBox.Text) || string.IsNullOrWhiteSpace(passwordTextBox.Text))
        {
            statusLabel.Text = "Заполните логин и пароль.";
            return;
        }

        Cursor = Cursors.WaitCursor;
        try
        {
            if (AuthService.Login(loginTextBox.Text, passwordTextBox.Text, out var error))
            {
                DialogResult = DialogResult.OK;
                Close();
            }
            else
            {
                statusLabel.Text = error;
            }
        }
        finally
        {
            Cursor = Cursors.Default;
        }
    }
}
