using System;
using System.Drawing;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace KeycloakDemo
{
    /// <summary>
    /// 主窗体 - 演示 Keycloak SSO 登录
    /// </summary>
    public class MainForm : Form
    {
        private readonly KeycloakAuthService _authService;

        // UI 控件
        private Panel _loginPanel;
        private Panel _userPanel;
        private Button _btnLogin;
        private Button _btnLogout;
        private Button _btnRefresh;
        private Label _lblStatus;
        private Label _lblUserName;
        private Label _lblEmail;
        private Label _lblTokenExpires;
        private TextBox _txtAccessToken;
        private RichTextBox _txtLog;

        public MainForm()
        {
            _authService = new KeycloakAuthService();
            InitializeComponent();
            CheckCachedLogin();
        }

        private void InitializeComponent()
        {
            this.Text = "WinForm Keycloak SSO Demo";
            this.Size = new Size(800, 600);
            this.StartPosition = FormStartPosition.CenterScreen;
            this.Font = new Font("Microsoft YaHei UI", 9F);

            // === 登录面板 ===
            _loginPanel = new Panel
            {
                Dock = DockStyle.Top,
                Height = 100,
                Padding = new Padding(20)
            };

            _btnLogin = new Button
            {
                Text = "🔐 使用 Keycloak 登录",
                Size = new Size(200, 45),
                Location = new Point(20, 25),
                BackColor = Color.FromArgb(52, 152, 219),
                ForeColor = Color.White,
                FlatStyle = FlatStyle.Flat,
                Cursor = Cursors.Hand
            };
            _btnLogin.Click += async (s, e) => await LoginAsync();
            _loginPanel.Controls.Add(_btnLogin);

            _lblStatus = new Label
            {
                Text = "未登录",
                Location = new Point(240, 35),
                Size = new Size(500, 25),
                ForeColor = Color.Gray
            };
            _loginPanel.Controls.Add(_lblStatus);

            this.Controls.Add(_loginPanel);

            // === 用户信息面板 ===
            _userPanel = new Panel
            {
                Location = new Point(0, 100),
                Size = new Size(780, 150),
                Visible = false,
                Padding = new Padding(20)
            };

            var lblNameTitle = new Label { Text = "用户名：", Location = new Point(20, 10), AutoSize = true };
            _lblUserName = new Label { Text = "-", Location = new Point(100, 10), AutoSize = true, Font = new Font(this.Font, FontStyle.Bold) };

            var lblEmailTitle = new Label { Text = "邮箱：", Location = new Point(20, 35), AutoSize = true };
            _lblEmail = new Label { Text = "-", Location = new Point(100, 35), AutoSize = true };

            var lblExpiresTitle = new Label { Text = "Token 过期：", Location = new Point(20, 60), AutoSize = true };
            _lblTokenExpires = new Label { Text = "-", Location = new Point(100, 60), AutoSize = true };

            _btnRefresh = new Button
            {
                Text = "🔄 刷新 Token",
                Size = new Size(120, 35),
                Location = new Point(20, 95),
                BackColor = Color.FromArgb(46, 204, 113),
                ForeColor = Color.White,
                FlatStyle = FlatStyle.Flat
            };
            _btnRefresh.Click += async (s, e) => await RefreshTokenAsync();

            _btnLogout = new Button
            {
                Text = "🚪 登出",
                Size = new Size(100, 35),
                Location = new Point(150, 95),
                BackColor = Color.FromArgb(231, 76, 60),
                ForeColor = Color.White,
                FlatStyle = FlatStyle.Flat
            };
            _btnLogout.Click += async (s, e) => await LogoutAsync();

            _userPanel.Controls.AddRange(new Control[] {
                lblNameTitle, _lblUserName, lblEmailTitle, _lblEmail,
                lblExpiresTitle, _lblTokenExpires, _btnRefresh, _btnLogout
            });

            this.Controls.Add(_userPanel);

            // === Access Token 显示 ===
            var lblTokenTitle = new Label
            {
                Text = "Access Token:",
                Location = new Point(20, 260),
                AutoSize = true
            };
            this.Controls.Add(lblTokenTitle);

            _txtAccessToken = new TextBox
            {
                Location = new Point(20, 280),
                Size = new Size(740, 60),
                Multiline = true,
                ReadOnly = true,
                ScrollBars = ScrollBars.Vertical,
                BackColor = Color.FromArgb(245, 245, 245)
            };
            this.Controls.Add(_txtAccessToken);

            // === 日志面板 ===
            var lblLogTitle = new Label
            {
                Text = "操作日志:",
                Location = new Point(20, 350),
                AutoSize = true
            };
            this.Controls.Add(lblLogTitle);

            _txtLog = new RichTextBox
            {
                Location = new Point(20, 370),
                Size = new Size(740, 170),
                ReadOnly = true,
                BackColor = Color.FromArgb(40, 44, 52),
                ForeColor = Color.FromArgb(171, 178, 191),
                Font = new Font("Consolas", 9F)
            };
            this.Controls.Add(_txtLog);
        }

        /// <summary>
        /// 检查缓存登录状态
        /// </summary>
        private void CheckCachedLogin()
        {
            if (TokenStorage.HasCachedTokens())
            {
                Log("检测到缓存的登录信息，尝试自动登录...");
            }
        }

        /// <summary>
        /// 执行登录
        /// </summary>
        private async Task LoginAsync()
        {
            _btnLogin.Enabled = false;
            _btnLogin.Text = "登录中...";
            _lblStatus.Text = "正在打开浏览器...";
            _lblStatus.ForeColor = Color.Blue;

            Log("开始登录流程...");
            Log($"  Authority: {KeycloakConfig.Authority}");
            Log($"  ClientId: {KeycloakConfig.ClientId}");
            Log($"  RedirectUri: {KeycloakConfig.RedirectUri}");

            try
            {
                var result = await _authService.LoginAsync();

                if (result.IsSuccess)
                {
                    Log($"✅ {result.Message}");
                    Log($"  用户: {result.UserInfo?.Name ?? result.UserInfo?.Username}");
                    Log($"  邮箱: {result.UserInfo?.Email}");
                    Log($"  Token 过期时间: {result.ExpiresAt:yyyy-MM-dd HH:mm:ss}");

                    UpdateUIForLoggedIn(result);
                }
                else
                {
                    Log($"❌ 登录失败: {result.Message}");
                    _lblStatus.Text = result.Message;
                    _lblStatus.ForeColor = Color.Red;
                }
            }
            catch (Exception ex)
            {
                Log($"❌ 登录异常: {ex.Message}");
                _lblStatus.Text = $"登录异常: {ex.Message}";
                _lblStatus.ForeColor = Color.Red;
            }
            finally
            {
                _btnLogin.Enabled = true;
                _btnLogin.Text = "🔐 使用 Keycloak 登录";
            }
        }

        /// <summary>
        /// 刷新 Token
        /// </summary>
        private async Task RefreshTokenAsync()
        {
            _btnRefresh.Enabled = false;
            Log("刷新 Token...");

            try
            {
                var result = await _authService.RefreshTokenAsync();

                if (result.IsSuccess)
                {
                    Log($"✅ {result.Message}");
                    Log($"  新的过期时间: {result.ExpiresAt:yyyy-MM-dd HH:mm:ss}");
                    UpdateUIForLoggedIn(result);
                }
                else
                {
                    Log($"❌ 刷新失败: {result.Message}");
                    MessageBox.Show(result.Message, "刷新失败", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }
            }
            catch (Exception ex)
            {
                Log($"❌ 刷新异常: {ex.Message}");
            }
            finally
            {
                _btnRefresh.Enabled = true;
            }
        }

        /// <summary>
        /// 登出
        /// </summary>
        private async Task LogoutAsync()
        {
            Log("执行登出...");

            var success = await _authService.LogoutAsync();
            
            if (success)
            {
                Log("✅ 已登出");
            }

            // 更新 UI
            _userPanel.Visible = false;
            _txtAccessToken.Text = "";
            _lblStatus.Text = "已登出";
            _lblStatus.ForeColor = Color.Gray;
            _btnLogin.Visible = true;
        }

        /// <summary>
        /// 更新 UI 为已登录状态
        /// </summary>
        private void UpdateUIForLoggedIn(LoginResult result)
        {
            _btnLogin.Visible = false;
            _userPanel.Visible = true;
            
            _lblUserName.Text = result.UserInfo?.Name ?? result.UserInfo?.Username ?? "-";
            _lblEmail.Text = result.UserInfo?.Email ?? "-";
            _lblTokenExpires.Text = result.ExpiresAt.ToString("yyyy-MM-dd HH:mm:ss");
            
            _txtAccessToken.Text = result.AccessToken;
            
            _lblStatus.Text = "✅ 已登录";
            _lblStatus.ForeColor = Color.Green;
        }

        /// <summary>
        /// 记录日志
        /// </summary>
        private void Log(string message)
        {
            if (_txtLog.InvokeRequired)
            {
                _txtLog.Invoke(new Action<string>(Log), message);
                return;
            }

            _txtLog.AppendText($"[{DateTime.Now:HH:mm:ss}] {message}\n");
            _txtLog.ScrollToCaret();
        }

        protected override void OnFormClosing(FormClosingEventArgs e)
        {
            _authService?.Dispose();
            base.OnFormClosing(e);
        }
    }
}
