using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using FairyView;
using StandardScene.Utils;

namespace StandardScene.Charge
{
    /// <summary>
    /// 报警配置管理界面（CycleGUI 版，替代原 WinForms 窗体）。
    /// </summary>
    public class AlarmConfigManagementForm
    {
        private const string TableId = "alarm-config-list";

        private readonly string[] LevelNames = { "无", "低", "中", "高", "严重" };
        private readonly string[] LevelFilterNames = { "全部", "无", "低", "中", "高", "严重" };

        private readonly Color CriticalRowColor = Color.FromArgb(255, 235, 238);
        private readonly Color HighRowColor = Color.FromArgb(255, 243, 224);
        private readonly Color MediumRowColor = Color.FromArgb(255, 249, 196);
        private readonly Color LowRowColor = Color.FromArgb(232, 245, 233);
        private readonly Color DisabledRowColor = Color.FromArgb(238, 238, 238);

        private readonly AlarmConfigDataService DataService = AlarmConfigDataService.Instance;

        private Panel _panel;
        private Panel _dialog;
        private List<AlarmConfig> _allAlarms = new List<AlarmConfig>();
        private int _levelFilterIdx;
        private string _status = "";

        /// <summary>打开（或置前）报警配置管理面板。兼容原 <c>new AlarmConfigManagementForm().Show()</c> 调用方式。</summary>
        public void Show() => Open();

        /// <summary>打开（或置前）报警配置管理面板。</summary>
        public static void Open() => (_instance ??= new AlarmConfigManagementForm()).OpenCore();

        private static AlarmConfigManagementForm _instance;

        private void OpenCore()
        {
            if (_panel != null)
            {
                try
                {
                    _panel.BringToFront();
                    return;
                }
                catch
                {
                    _panel = null;
                }
            }

            LoadAlarms();

            var panel = GUI.DeclarePanel()
                .ShowTitle("报警配置管理")
                .ForceFloat()
                .InitSize(1100, 680)
                .InitPos(false, 0, 0, 0.5f, 0.5f, 0.5f, 0.5f);
            _panel = panel;
            panel.IfTerminalQuit(() => _panel = null);

            panel.Define(pb =>
            {
                if (pb.Closing())
                {
                    panel.Exit();
                    _panel = null;
                    return;
                }

                if (pb.Button("新增", distinct: "alarm-add"))
                    OpenEditDialog(null);
                pb.SameLine(12);
                if (pb.Button("刷新", distinct: "alarm-refresh"))
                {
                    DataService.Reload();
                    LoadAlarms();
                    _status = "数据已刷新";
                }
                pb.SameLine(12);
                if (pb.Button("关闭", distinct: "alarm-close"))
                {
                    panel.Exit();
                    _panel = null;
                    return;
                }

                pb.Separator();
                pb.DropdownBox("级别筛选", LevelFilterNames, ref _levelFilterIdx);

                var filtered = GetFilteredAlarms();
                var totalCount = _allAlarms.Count;
                if (_levelFilterIdx > 0)
                    pb.Label($"显示: {filtered.Count}/{totalCount} ({LevelFilterNames[_levelFilterIdx]})");
                else
                    pb.Label($"总数: {totalCount} | {GetStatisticsText()}");

                pb.Table(TableId,
                    new[] { "报警编码", "报警内容", "级别", "启用", "备注", "操作" },
                    filtered.Count, (row, i) =>
                    {
                        var alarm = filtered[i];
                        if (!alarm.Enabled)
                            row.SetColor(DisabledRowColor);
                        else if (alarm.Level == AlarmLevel.Critical)
                            row.SetColor(CriticalRowColor);
                        else if (alarm.Level == AlarmLevel.High)
                            row.SetColor(HighRowColor);
                        else if (alarm.Level == AlarmLevel.Medium)
                            row.SetColor(MediumRowColor);
                        else if (alarm.Level == AlarmLevel.Low)
                            row.SetColor(LowRowColor);

                        row.Label($"{alarm.AlarmCode}");
                        row.Label(alarm.AlarmContent ?? "");
                        row.Label(GetLevelText(alarm.Level));
                        row.Label(alarm.Enabled ? "是" : "否");
                        row.Label(alarm.Remarks ?? "");

                        if (row.ButtonGroup(new[] { "编辑" }, new[] { "编辑该报警配置" }) == 0)
                            OpenEditDialog(alarm);
                    }, height: FairyUiHelper.TableHeightPx(16), enableSearch: true);

                if (!string.IsNullOrEmpty(_status))
                {
                    pb.Separator();
                    pb.Label(_status);
                }

                pb.Panel.Repaint(repaintTimeMs: 500);
            });
        }

        private void OpenEditDialog(AlarmConfig existing)
        {
            if (_dialog != null)
            {
                try
                {
                    _dialog.BringToFront();
                    return;
                }
                catch
                {
                    _dialog = null;
                }
            }

            bool isAdd = existing == null;
            var draft = isAdd ? new AlarmConfig() : existing;

            int levelIdx = (int)draft.Level;
            if (levelIdx < 0 || levelIdx >= LevelNames.Length)
                levelIdx = 2;

            string codeText = draft.AlarmCode.ToString();
            string contentText = draft.AlarmContent ?? "";
            string remarksText = draft.Remarks ?? "";
            bool enabled = draft.Enabled;
            string err = "";

            var dlg = GUI.DeclarePanel()
                .ShowTitle(isAdd ? "新增报警配置" : $"编辑报警配置 [{draft.AlarmCode}]")
                .ForceFloat()
                .InitSize(460, 420)
                .InitPos(false, 0, 0, 0.5f, 0.5f, 0.5f, 0.5f);
            _dialog = dlg;
            dlg.IfTerminalQuit(() => _dialog = null);

            dlg.Define(pb =>
            {
                if (pb.Closing())
                {
                    dlg.Exit();
                    _dialog = null;
                    return;
                }

                if (isAdd)
                    pb.Label("编号: (新增时自动生成)");
                else
                    pb.Label($"编号: {draft.AlarmId}");

                var (code, _) = pb.TextInput("1. 报警编码 (0~99999)", codeText, alwaysReturnString: true);
                codeText = code;
                var (content, _) = pb.TextInput("2. 报警内容", contentText, alwaysReturnString: true);
                contentText = content;
                pb.DropdownBox("3. 报警级别", LevelNames, ref levelIdx);
                pb.CheckBox("4. 启用", ref enabled);
                var (remarks, _) = pb.TextInput("5. 备注", remarksText, alwaysReturnString: true);
                remarksText = remarks;

                if (!string.IsNullOrEmpty(err))
                {
                    pb.Separator();
                    pb.Label(err);
                }

                pb.Separator();
                if (pb.Button(isAdd ? "新增" : "保存", distinct: "alarm-edit-save"))
                {
                    if (!int.TryParse(codeText?.Trim(), out var alarmCode) || alarmCode < 0 || alarmCode > 99999)
                    {
                        err = "报警编码需为 0~99999 的整数";
                        return;
                    }

                    if (string.IsNullOrWhiteSpace(contentText))
                    {
                        err = "报警内容不能为空";
                        return;
                    }

                    draft.AlarmCode = alarmCode;
                    draft.AlarmContent = contentText.Trim();
                    draft.Level = (AlarmLevel)levelIdx;
                    draft.Enabled = enabled;
                    draft.Remarks = remarksText?.Trim() ?? "";

                    bool success;
                    string errorMessage;
                    if (isAdd)
                        success = DataService.AddAlarmConfig(draft, out errorMessage);
                    else
                        success = DataService.UpdateAlarmConfig(draft, out errorMessage);

                    if (success)
                    {
                        FairyUiHelper.Alert("成功", "保存成功！");
                        LoadAlarms();
                        _status = isAdd ? "已新增报警配置" : $"已保存报警配置 [{draft.AlarmCode}]";
                        dlg.Exit();
                        _dialog = null;
                        _panel?.Repaint();
                    }
                    else
                    {
                        err = $"保存失败: {errorMessage}";
                    }
                }

                if (!isAdd)
                {
                    pb.SameLine(8);
                    if (pb.Button("删除", distinct: "alarm-edit-delete"))
                    {
                        var toDelete = draft;
                        FairyUiHelper.ConfirmThen(
                            $"确定要删除报警配置 [{toDelete.AlarmCode}] {toDelete.AlarmContent} 吗？",
                            () =>
                            {
                                if (DataService.DeleteAlarmConfig(toDelete.AlarmId, out string errorMessage))
                                {
                                    FairyUiHelper.Alert("成功", "删除成功！");
                                    LoadAlarms();
                                    _status = $"已删除报警配置 [{toDelete.AlarmCode}]";
                                    dlg.Exit();
                                    _dialog = null;
                                    _panel?.Repaint();
                                }
                                else
                                {
                                    FairyUiHelper.Alert("错误", $"删除失败: {errorMessage}");
                                }
                            });
                    }
                }

                pb.SameLine(8);
                if (pb.Button("取消", distinct: "alarm-edit-cancel"))
                {
                    dlg.Exit();
                    _dialog = null;
                }
            });
        }

        private void LoadAlarms()
        {
            try
            {
                _allAlarms = DataService.GetAllAlarmConfigs() ?? new List<AlarmConfig>();
            }
            catch (Exception ex)
            {
                _allAlarms = new List<AlarmConfig>();
                FairyUiHelper.Alert("错误", $"加载数据失败: {ex.Message}");
            }
        }

        private List<AlarmConfig> GetFilteredAlarms()
        {
            IEnumerable<AlarmConfig> query = _allAlarms;
            if (_levelFilterIdx > 0)
                query = query.Where(a => a.Level == (AlarmLevel)(_levelFilterIdx - 1));
            return query.ToList();
        }

        private string GetStatisticsText()
        {
            var total = _allAlarms.Count;
            var enabled = _allAlarms.Count(a => a.Enabled);
            var disabled = total - enabled;
            var critical = _allAlarms.Count(a => a.Level == AlarmLevel.Critical);
            var high = _allAlarms.Count(a => a.Level == AlarmLevel.High);
            return $"启用: {enabled} | 禁用: {disabled} | 严重: {critical} | 高级: {high}";
        }

        private string GetLevelText(AlarmLevel level)
        {
            switch (level)
            {
                case AlarmLevel.None: return "无";
                case AlarmLevel.Low: return "低";
                case AlarmLevel.Medium: return "中";
                case AlarmLevel.High: return "高";
                case AlarmLevel.Critical: return "严重";
                default: return "未知";
            }
        }

    }
}
