using QtCNETAPI.Services.ApiService;
using QtCNETAPI.Dtos.User;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace qtc_net_client_2.Forms
{
    public partial class Login : Form
    {
        private IApiService _apiService;
        public Login(IApiService apiService)
        {
            _apiService = apiService;

            InitializeComponent();
        }

        private async void frmLogin_Load(object sender, EventArgs e)
        {
            if (File.Exists("./session.token"))
            {
                ToggleControls(false, false);

                // try logging in with the token in the file
                string token = File.ReadAllText("./session.token");

                var result = await _apiService.RefreshLogin(token);
                if (result.Success)
                {
                    DialogResult = DialogResult.OK;
                    Close();
                }
                else
                    ToggleControls(true, false);
            }
        }

        private async void btnLogin_Click(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(tbEmail.Text) && !string.IsNullOrEmpty(tbPassword.Text))
            {
                ToggleControls(false, false);

                var result = await _apiService.LoginAsync(new UserLoginDto
                {
                    Email = tbEmail.Text,
                    Password = tbPassword.Text,
                    RememberMe = cbRememberMe.Checked
                });

                if (result.Success)
                {
                    DialogResult = DialogResult.OK;
                    Close();
                }
                else
                {
                    ToggleControls(true, true);
                    MessageBox.Show(result.Message, "Login Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
        }

        private void ToggleControls(bool enable, bool clearText)
        {
            tbEmail.Enabled = enable;
            tbPassword.Enabled = enable;
            btnLogin.Enabled = enable;
            llblRegister.Enabled = enable;

            if (clearText)
            {
                tbEmail.Text = string.Empty;
                tbPassword.Text = string.Empty;
            }
        }

        private void llblRegister_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            Register frmRegister = new Register(_apiService);
            frmRegister.ShowDialog();
        }
    }
}
