package view;

import backend.dao.QuestionsDao;
import backend.dao.UserDao;
import backend.model.Charts;
import backend.model.Questions;
import backend.model.TestRecord;
import backend.model.enums.ScoreKey;
import backend.service.ChartsService;
import backend.service.QuestionsService;
import backend.service.TestRecordService;

import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.sql.Date;
import java.util.Vector;

public class ExamPanel extends JPanel {
    private QuestionsService questionsService = new QuestionsService();
    private Questions currentQuestion;
    private JButton startButton;
    private JButton submitButton;
    private JButton nextButton;
    private JButton exitButton;
    private JLabel questionLabel;
    private JLabel descriptionLabel;
    private JLabel progressLabel;
    private JTextField answerTextField;
    private JMenuBar menuBar;
    private String role = MainFrame.role;
    private int userId = MainFrame.userId;

    // 颜色常量定义
    private static final Color PRIMARY_COLOR = new Color(70, 130, 180);  // 钢蓝色
    private static final Color BACKGROUND_COLOR = new Color(248, 249, 250);  // 浅灰色背景
    private static final Color BORDER_COLOR = new Color(220, 220, 220);  // 边框颜色
    private static final Color HIGHLIGHT_COLOR = new Color(255, 255, 204);  // 高亮背景

    public ExamPanel() {
        initializeComponents();
        initView();
        initListener();
    }

    // 初始化所有UI组件
    private void initializeComponents() {
        // 题目标题标签
        questionLabel = new JLabel("点击开始测试获取题目");
        questionLabel.setFont(new Font("微软雅黑", Font.BOLD, 18));
        questionLabel.setForeground(new Color(50, 50, 50));
        questionLabel.setHorizontalAlignment(JLabel.CENTER);
        questionLabel.setVerticalAlignment(JLabel.TOP);

        // 题目描述标签
        descriptionLabel = new JLabel("描述将在这里显示");
        descriptionLabel.setFont(new Font("微软雅黑", Font.PLAIN, 14));
        descriptionLabel.setForeground(new Color(100, 100, 100));
        descriptionLabel.setHorizontalAlignment(JLabel.CENTER);
        descriptionLabel.setVerticalAlignment(JLabel.TOP);

        // 进度标签
        progressLabel = new JLabel("题目进度: 0/0");
        progressLabel.setFont(new Font("微软雅黑", Font.PLAIN, 12));
        progressLabel.setForeground(new Color(120, 120, 120));
        progressLabel.setHorizontalAlignment(JLabel.RIGHT);

        // 答案输入框
        answerTextField = new JTextField(20);
        answerTextField.setFont(new Font("微软雅黑", Font.PLAIN, 14));
        answerTextField.setHorizontalAlignment(JLabel.CENTER);
        answerTextField.setPreferredSize(new Dimension(250, 35));

        // 初始化按钮
        startButton = new JButton("开始测试");
        submitButton = new JButton("提交");
        nextButton = new JButton("下一题");
        exitButton = new JButton("退出");

        // 设置按钮样式
        setButtonStyle(startButton);
        setButtonStyle(submitButton);
        setButtonStyle(nextButton);
        setButtonStyle(exitButton);

        // 隐藏非初始按钮
        submitButton.setVisible(false);
        nextButton.setVisible(false);
        exitButton.setVisible(false);
    }

    // 设置按钮样式
    private void setButtonStyle(JButton button) {
        button.setFont(new Font("微软雅黑", Font.BOLD, 14));
        button.setPreferredSize(new Dimension(100, 35));
        button.setBackground(PRIMARY_COLOR);
        button.setForeground(Color.WHITE);
        button.setFocusPainted(false);
        button.setBorder(BorderFactory.createRaisedBevelBorder());
    }

    private void initView() {
        setLayout(new BorderLayout());
        setBackground(BACKGROUND_COLOR);

        // 创建顶部工具栏
        JPanel topPanel = new JPanel(new BorderLayout());
        topPanel.setBackground(PRIMARY_COLOR);
        topPanel.setBorder(BorderFactory.createEmptyBorder(5, 10, 5, 10));

        JLabel titleLabel = new JLabel("测试管理");
        titleLabel.setFont(new Font("微软雅黑", Font.BOLD, 16));
        titleLabel.setForeground(Color.WHITE);
        topPanel.add(titleLabel, BorderLayout.WEST);
        topPanel.add(progressLabel, BorderLayout.EAST);
        topPanel.add(initMenuBar(), BorderLayout.CENTER);

        add(topPanel, BorderLayout.NORTH);

        // 创建中央内容面板
        JPanel centerPanel = new JPanel();
        centerPanel.setLayout(new BoxLayout(centerPanel, BoxLayout.Y_AXIS));
        centerPanel.setBackground(BACKGROUND_COLOR);
        centerPanel.setBorder(BorderFactory.createEmptyBorder(30, 30, 30, 30));

        // 添加初始显示内容
        centerPanel.add(Box.createVerticalGlue());

        // 题目展示区域
        JPanel questionPanel = new JPanel(new BorderLayout());
        questionPanel.setBackground(Color.WHITE);
        questionPanel.setBorder(BorderFactory.createCompoundBorder(
            BorderFactory.createLineBorder(BORDER_COLOR, 1),
            BorderFactory.createEmptyBorder(20, 20, 20, 20)
        ));
        questionPanel.setMaximumSize(new Dimension(600, 300));
        questionPanel.setAlignmentX(Component.CENTER_ALIGNMENT);

        questionPanel.add(questionLabel, BorderLayout.CENTER);
        questionPanel.add(descriptionLabel, BorderLayout.SOUTH);

        centerPanel.add(questionPanel);
        centerPanel.add(Box.createVerticalStrut(20));

        // 答案输入区域
        JPanel inputPanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 10, 5));
        inputPanel.setBackground(BACKGROUND_COLOR);
        inputPanel.add(new JLabel("请输入答案: "));
        inputPanel.add(answerTextField);
        centerPanel.add(inputPanel);
        centerPanel.add(Box.createVerticalStrut(15));

        // 按钮区域
        JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 15, 5));
        buttonPanel.setBackground(BACKGROUND_COLOR);
        buttonPanel.add(startButton);
        buttonPanel.add(submitButton);
        buttonPanel.add(nextButton);
        buttonPanel.add(exitButton);
        centerPanel.add(buttonPanel);

        centerPanel.add(Box.createVerticalGlue());
        add(centerPanel, BorderLayout.CENTER);

        // 更新按钮可见性
        updateButtonVisibility();
    }

    private void updateButtonVisibility() {
        startButton.setVisible(true);
        submitButton.setVisible(false);
        nextButton.setVisible(false);
        exitButton.setVisible(false);
    }

    private void showQuestion() {
        // 更新按钮可见性
        startButton.setVisible(false);
        submitButton.setVisible(true);
        nextButton.setVisible(false);
        exitButton.setVisible(false);

        // 更新进度显示
        progressLabel.setText("题目进度: 1/1");

        // 重新验证和重绘界面
        revalidate();
        repaint();
    }

    private void showNextQuestionOption() {
        // 更新按钮可见性
        startButton.setVisible(false);
        submitButton.setVisible(false);
        nextButton.setVisible(true);
        exitButton.setVisible(true);

        // 重新验证和重绘界面
        revalidate();
        repaint();
    }

    private void initListener() {
        startButton.addActionListener(e -> {
            // 获取随机题目并显示
            currentQuestion = questionsService.getRandomQuestion();
            if (currentQuestion != null) {
                //在排行榜中创建角色（若没有）
                ChartsService chartsService = new ChartsService();
                Charts charts = new Charts();
                charts.setUserid(userId);
                chartsService.insertCharts(charts);
                updateQuestionDisplay();
                showQuestion();
            } else {
                JOptionPane.showMessageDialog(this,
                    "没有可用的题目", "错误", JOptionPane.ERROR_MESSAGE);
            }
        });

        submitButton.addActionListener(e -> handleAnswerSubmission());

        // 为 nextButton 和 exitButton 添加监听器
        if (nextButton != null) {
            nextButton.addActionListener(e -> {
                currentQuestion = questionsService.getRandomQuestion();
                if (currentQuestion != null) {
                    updateQuestionDisplay();
                    showQuestion();
                } else {
                    JOptionPane.showMessageDialog(this,
                        "没有更多题目", "提示", JOptionPane.INFORMATION_MESSAGE);
                }
            });
        }

        if (exitButton != null) {
            exitButton.addActionListener(e -> {
                int choice = JOptionPane.showConfirmDialog(
                    this,
                    "确定要退出测试吗？",
                    "确认退出",
                    JOptionPane.YES_NO_OPTION
                );
                if (choice == JOptionPane.YES_OPTION) {
                    resetToInitialState();
                }
            });
        }
        // 为菜单项添加监听器
        JMenu testMenu = (JMenu) menuBar.getMenu(0);
        JMenuItem testContentItem = testMenu.getItem(0);
        testContentItem.addActionListener(e -> {
            resetToInitialState();
        });

        JMenu recordMenu = (JMenu) menuBar.getMenu(1);
        JMenuItem recordItem = recordMenu.getItem(0);
        recordItem.addActionListener(e -> {
            initRecordView();
        });

        JMenu chartMenu = (JMenu) menuBar.getMenu(2);
        JMenuItem chartItem = chartMenu.getItem(0);
        chartItem.addActionListener(e -> {
            // 这里可以添加排行榜页面的切换逻辑
            initRankView();
        });

    }

    private void updateQuestionDisplay() {
        if (currentQuestion != null) {
            questionLabel.setText(currentQuestion.getName());
            descriptionLabel.setText(currentQuestion.getDescription());
            answerTextField.setText("");
        }
    }

    private void handleAnswerSubmission() {
        int user=userId, questionId= currentQuestion.getId(), score=0;
        if (currentQuestion == null) {
            JOptionPane.showMessageDialog(this,
                "请先开始测试", "提示", JOptionPane.WARNING_MESSAGE);
            return;
        }

        String userAnswer = answerTextField.getText().trim();
        if (userAnswer.isEmpty()) {
            JOptionPane.showMessageDialog(this,
                "请输入答案", "提示", JOptionPane.WARNING_MESSAGE);
            return;
        }

        if (userAnswer.equalsIgnoreCase(currentQuestion.getAnswer())) {
            // 答案正确时高亮输入框
            answerTextField.setBackground(HIGHLIGHT_COLOR);
            JOptionPane.showMessageDialog(this,
                "答案正确！", "正确", JOptionPane.INFORMATION_MESSAGE);
            answerTextField.setBackground(Color.WHITE);
            score= ScoreKey.getScoreByKey(currentQuestion.getFrequency());
            showNextQuestionOption();
        } else {
            // 答案错误时改变输入框颜色
            answerTextField.setBackground(new Color(255, 220, 220)); // 淡红色
            int choice = JOptionPane.showConfirmDialog(
                this,
                "答案错误，正确答案是：" + currentQuestion.getAnswer() + "\n是否重新尝试？",
                "错误",
                JOptionPane.YES_NO_OPTION
            );

            if (choice == JOptionPane.NO_OPTION) {
                answerTextField.setBackground(Color.WHITE);
                showNextQuestionOption();
            } else {
                // 清空输入框，允许重新尝试
                answerTextField.setText("");
                answerTextField.setBackground(Color.WHITE);
            }
        }
        // 保存测试记录
        TestRecord testRecord = new TestRecord();
        testRecord.setUserId(user);
        testRecord.setQuestionId(questionId);
        testRecord.setScore(score);
        testRecord.setAnswer(userAnswer);
        testRecord.setTime(new Date(System.currentTimeMillis()));
        TestRecordService testRecordService = new TestRecordService();
        testRecordService.insert(testRecord);
    }

    private void resetToInitialState() {
        // 重置所有组件状态
        questionLabel.setText("点击开始测试获取题目");
        descriptionLabel.setText("描述将在这里显示");
        answerTextField.setText("");
        answerTextField.setBackground(Color.WHITE);

        // 重置按钮状态
        updateButtonVisibility();

        // 重置进度
        progressLabel.setText("题目进度: 0/0");

        revalidate();
        repaint();
    }

    private JMenuBar initMenuBar() {
        menuBar = new JMenuBar();
        menuBar.setBackground(PRIMARY_COLOR);

        JMenu testMenu = new JMenu("测试内容");
        testMenu.setForeground(Color.WHITE);
        testMenu.add(new JMenuItem("开始测试"));
        menuBar.add(testMenu);

        JMenu recordMenu = new JMenu("测试记录");
        recordMenu.setForeground(Color.WHITE);
        if(role.equals("user"))
            recordMenu.add(new JMenuItem("我的记录"));
        else
            recordMenu.add(new JMenuItem("查看所有记录"));
        menuBar.add(recordMenu);

        JMenu chartMenu = new JMenu("排行榜");
        chartMenu.setForeground(Color.WHITE);
        chartMenu.add(new JMenuItem("查看排行榜"));
        menuBar.add(chartMenu);

        return menuBar;
    }

    private void initRecordView() {
        // 清空当前面板
        removeAll();
        setLayout(new BorderLayout());

        // 创建顶部查询面板
        JPanel queryPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
        queryPanel.setBackground(PRIMARY_COLOR);
        queryPanel.setBorder(BorderFactory.createEmptyBorder(5, 10, 5, 10));

        // 添加查询输入框和按钮
        JLabel userLabel = new JLabel("用户:");
        userLabel.setForeground(Color.WHITE);
        JTextField userIdField = new JTextField(8);
        userIdField.setPreferredSize(new Dimension(80, 25));

        JLabel questionLabel = new JLabel("题目:");
        questionLabel.setForeground(Color.WHITE);
        JTextField questionIdField = new JTextField(8);
        questionIdField.setPreferredSize(new Dimension(80, 25));

        JButton searchButton = new JButton("查询");
        setButtonStyle(searchButton);

        JButton resetButton = new JButton("重置");
        setButtonStyle(resetButton);

        queryPanel.add(userLabel);
        queryPanel.add(userIdField);
        queryPanel.add(questionLabel);
        queryPanel.add(questionIdField);
        queryPanel.add(searchButton);
        queryPanel.add(resetButton);

        // 创建表格展示面板
        JPanel tablePanel = new JPanel(new BorderLayout());
        tablePanel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));

        // 初始化表格
        String[] columnNames = {"记录ID", "用户名", "题目", "得分", "答案", "时间"};
        DefaultTableModel tableModel = new DefaultTableModel(columnNames, 0) {
            @Override
            public boolean isCellEditable(int row, int column) {
                return false; // 表格不可编辑
            }
        };

        JTable recordTable = new JTable(tableModel);
        recordTable.setFont(new Font("微软雅黑", Font.PLAIN, 12));
        recordTable.getTableHeader().setFont(new Font("微软雅黑", Font.BOLD, 13));
        recordTable.getTableHeader().setBackground(PRIMARY_COLOR);
        recordTable.getTableHeader().setForeground(Color.WHITE);
        recordTable.setSelectionBackground(new Color(176, 224, 230));
        recordTable.setRowHeight(25);

        // 设置列宽
        recordTable.getColumnModel().getColumn(0).setPreferredWidth(60);  // 记录ID
        recordTable.getColumnModel().getColumn(1).setPreferredWidth(100); // 用户名
        recordTable.getColumnModel().getColumn(2).setPreferredWidth(200); // 题目
        recordTable.getColumnModel().getColumn(3).setPreferredWidth(60);  // 得分
        recordTable.getColumnModel().getColumn(4).setPreferredWidth(150); // 答案
        recordTable.getColumnModel().getColumn(5).setPreferredWidth(120); // 时间

        JScrollPane scrollPane = new JScrollPane(recordTable);
        scrollPane.setPreferredSize(new Dimension(700, 400));

        tablePanel.add(scrollPane, BorderLayout.CENTER);

        // 添加到主面板
        add(queryPanel, BorderLayout.NORTH);
        add(tablePanel, BorderLayout.CENTER);

        // 查询按钮事件处理
        searchButton.addActionListener(e -> {
            UserDao userDao = new UserDao();
            QuestionsDao questionsDao = new QuestionsDao();
            String userIdText = userIdField.getText().trim();
            String questionIdText = questionIdField.getText().trim();

            TestRecordService testRecordService = new TestRecordService();
            Vector<Vector<String>> records;

            try {
                if (!userIdText.isEmpty() && !questionIdText.isEmpty()) {
                    userIdText = String.valueOf(userDao.findByUsername(userIdField.getText().trim()).getId());
                    questionIdText = String.valueOf(questionsDao.getByName(questionIdField.getText().trim()).getId());
                    // 同时查询用户ID和题目ID
                    Integer userId = Integer.parseInt(userIdText);
                    Integer questionId = Integer.parseInt(questionIdText);
                    records = testRecordService.getByUserIdAndQuestionId(userId, questionId);
                } else if (!userIdText.isEmpty()) {
                    // 只查询用户ID
                    userIdText = String.valueOf(userDao.findByUsername(userIdField.getText().trim()).getId());
                    Integer userId = Integer.parseInt(userIdText);
                    records = testRecordService.getByUserId(userId);
                } else if (!questionIdText.isEmpty()) {
                    // 只查询题目ID
                    questionIdText = String.valueOf(questionsDao.getByName(questionIdField.getText().trim()).getId());
                    Integer questionId = Integer.parseInt(questionIdText);
                    records = testRecordService.getByQuestionId(questionId);
                } else {
                    // 查询所有记录（根据角色权限）
                    if (role.equals("user")) {
                        records = testRecordService.getByUserId(this.userId);
                    } else {
                        records = testRecordService.getAll();
                    }
                }

                // 清空表格
                tableModel.setRowCount(0);

                // 添加数据到表格
                for (Vector<String> record : records) {
                    tableModel.addRow(record);
                }

                // 如果没有找到记录，显示提示
                if (records.isEmpty()) {
                    JOptionPane.showMessageDialog(this, "没有找到匹配的记录", "提示", JOptionPane.INFORMATION_MESSAGE);
                }

            } catch (NumberFormatException ex) {
                JOptionPane.showMessageDialog(this, "请输入有效的数字ID", "错误", JOptionPane.ERROR_MESSAGE);
            }
        });

        // 重置按钮事件处理
        resetButton.addActionListener(e -> {
            userIdField.setText("");
            questionIdField.setText("");

            // 根据角色加载默认数据
            TestRecordService testRecordService = new TestRecordService();
            Vector<Vector<String>> records;

            if (role.equals("user")) {
                records = testRecordService.getByUserId(this.userId);
            } else {
                records = testRecordService.getAll();
            }

            // 清空表格
            tableModel.setRowCount(0);

            // 添加数据到表格
            for (Vector<String> record : records) {
                tableModel.addRow(record);
            }
        });

        // 初始加载数据
        SwingUtilities.invokeLater(() -> {
            TestRecordService testRecordService = new TestRecordService();
            Vector<Vector<String>> records;

            if (role.equals("user")) {
                records = testRecordService.getByUserId(this.userId);
            } else {
                records = testRecordService.getAll();
            }

            // 添加数据到表格
            for (Vector<String> record : records) {
                tableModel.addRow(record);
            }
        });

        revalidate();
        repaint();
    }

    private void initRankView() {
        // 清空当前面板
        removeAll();
        setLayout(new BorderLayout());

        // 创建顶部控制面板
        JPanel controlPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
        controlPanel.setBackground(PRIMARY_COLOR);
        controlPanel.setBorder(BorderFactory.createEmptyBorder(5, 10, 5, 10));

        JButton sortByScoreUpButton = new JButton("按分数升序");
        JButton sortByScoreDownButton = new JButton("按分数降序");
        setButtonStyle(sortByScoreUpButton);
        setButtonStyle(sortByScoreDownButton);

        controlPanel.add(sortByScoreUpButton);
        controlPanel.add(sortByScoreDownButton);

        // 创建表格展示面板
        JPanel tablePanel = new JPanel(new BorderLayout());
        tablePanel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));

        // 初始化表格
        String[] columnNames = {"排名", "用户名", "答题次数", "总得分"};
        DefaultTableModel tableModel = new DefaultTableModel(columnNames, 0) {
            @Override
            public boolean isCellEditable(int row, int column) {
                return false; // 表格不可编辑
            }
        };

        JTable rankTable = new JTable(tableModel);
        rankTable.setFont(new Font("微软雅黑", Font.PLAIN, 12));
        rankTable.getTableHeader().setFont(new Font("微软雅黑", Font.BOLD, 13));
        rankTable.getTableHeader().setBackground(PRIMARY_COLOR);
        rankTable.getTableHeader().setForeground(Color.WHITE);
        rankTable.setSelectionBackground(new Color(176, 224, 230));
        rankTable.setRowHeight(25);

        // 设置列宽
        rankTable.getColumnModel().getColumn(0).setPreferredWidth(60);  // 排名
        rankTable.getColumnModel().getColumn(1).setPreferredWidth(120); // 用户名
        rankTable.getColumnModel().getColumn(2).setPreferredWidth(100); // 答题次数
        rankTable.getColumnModel().getColumn(3).setPreferredWidth(100); // 总得分

        JScrollPane scrollPane = new JScrollPane(rankTable);
        scrollPane.setPreferredSize(new Dimension(600, 400));

        tablePanel.add(scrollPane, BorderLayout.CENTER);

        // 添加到主面板
        add(controlPanel, BorderLayout.NORTH);
        add(tablePanel, BorderLayout.CENTER);

        // 加载默认数据（升序）
        loadRankData(tableModel, true);

        // 按分数升序按钮事件
        sortByScoreUpButton.addActionListener(e -> {
            loadRankData(tableModel, true);
        });

        // 按分数降序按钮事件
        sortByScoreDownButton.addActionListener(e -> {
            loadRankData(tableModel, false);
        });

        revalidate();
        repaint();
    }

    private void loadRankData(DefaultTableModel tableModel, boolean isAscending) {
        ChartsService chartsService = new ChartsService();
        Vector<Vector<String>> rankData;

        if (isAscending) {
            rankData = chartsService.sortByScoreUp();
        } else {
            rankData = chartsService.sortByScoreDown();
        }

        // 清空表格
        tableModel.setRowCount(0);

        // 添加数据到表格
        for (Vector<String> rankItem : rankData) {
            tableModel.addRow(rankItem);
        }
    }


}
