#ifndef AV_RECORDER_SETTINGS_DIALOG_H
#define AV_RECORDER_SETTINGS_DIALOG_H

#include <QDialog>
#include <QVBoxLayout>
#include <QHBoxLayout>
#include <QGridLayout>
#include <QTabWidget>
#include <QGroupBox>
#include <QLabel>
#include <QLineEdit>
#include <QComboBox>
#include <QSpinBox>
#include <QDoubleSpinBox>
#include <QSlider>
#include <QCheckBox>
#include <QPushButton>
#include <QFileDialog>
#include <QStandardPaths>
#include <QSettings>
#include <QTimer>
#include <QProgressBar>
#include <QTextEdit>
#include <QSplitter>
#include <QTreeWidget>
#include <QListWidget>
#include <memory>

// 前向声明
namespace av {
namespace recorder {
class RecorderModule;
}
}

/**
 * 录制器设置对话框
 * 
 * 提供完整的录制参数配置界面，包括：
 * - 音频设置（设备、格式、质量）
 * - 视频设置（设备、分辨率、帧率、编码）
 * - 输出设置（路径、格式、文件名模板）
 * - 高级设置（编码器参数、性能优化）
 * - 预设管理（保存/加载配置预设）
 */
class RecorderSettingsDialog : public QDialog {
    Q_OBJECT

public:
    /**
     * 设置类别
     */
    enum SettingsCategory {
        AudioCategory,
        VideoCategory,
        OutputCategory,
        AdvancedCategory,
        PresetCategory
    };
    
    /**
     * 音频设置结构
     */
    struct AudioSettings {
        QString deviceName;
        int sampleRate = 44100;
        int channels = 2;
        int bitDepth = 16;
        QString codec = "aac";
        int bitrate = 128000;
        bool enableNoiseSuppression = false;
        bool enableEchoCancellation = false;
        double inputGain = 1.0;
        
        AudioSettings() = default;
    };
    
    /**
     * 视频设置结构
     */
    struct VideoSettings {
        QString deviceName;
        int width = 1920;
        int height = 1080;
        double frameRate = 30.0;
        QString codec = "h264";
        int bitrate = 5000000;
        QString preset = "medium";
        QString profile = "high";
        int keyFrameInterval = 60;
        bool enableHardwareAcceleration = true;
        
        VideoSettings() = default;
    };
    
    /**
     * 输出设置结构
     */
    struct OutputSettings {
        QString outputDirectory;
        QString fileNameTemplate = "recording_%Y%m%d_%H%M%S";
        QString containerFormat = "mp4";
        bool autoCreateDirectory = true;
        bool overwriteExisting = false;
        int maxFileSize = 0; // 0 = unlimited
        int maxDuration = 0; // 0 = unlimited
        
        OutputSettings() {
            outputDirectory = QStandardPaths::writableLocation(QStandardPaths::MoviesLocation);
        }
    };
    
    /**
     * 高级设置结构
     */
    struct AdvancedSettings {
        int bufferSize = 4096;
        int threadCount = 0; // 0 = auto
        bool enableGPUAcceleration = true;
        QString gpuDevice;
        bool enableLowLatency = false;
        bool enableRealTimeEncoding = true;
        int encodingPriority = 0; // -2 to 2
        
        AdvancedSettings() = default;
    };
    
    /**
     * 完整设置结构
     */
    struct Settings {
        AudioSettings audio;
        VideoSettings video;
        OutputSettings output;
        AdvancedSettings advanced;
        
        Settings() = default;
    };

public:
    explicit RecorderSettingsDialog(av::recorder::RecorderModule* recorderModule, QWidget* parent = nullptr);
    ~RecorderSettingsDialog();

    /**
     * 设置当前配置
     */
    void setSettings(const Settings& settings);
    
    /**
     * 获取当前配置
     */
    Settings getSettings() const;
    
    /**
     * 显示指定类别的设置
     */
    void showCategory(SettingsCategory category);
    
    /**
     * 重置为默认设置
     */
    void resetToDefaults();
    
    /**
     * 加载设置
     */
    void loadSettings();
    
    /**
     * 保存设置
     */
    void saveSettings();
    
    /**
     * 验证设置有效性
     */
    bool validateSettings(QString* errorMessage = nullptr) const;

protected:
    void showEvent(QShowEvent* event) override;
    void closeEvent(QCloseEvent* event) override;

private slots:
    void onTabChanged(int index);
    void onAudioDeviceChanged(const QString& device);
    void onVideoDeviceChanged(const QString& device);
    void onOutputDirectoryBrowse();
    void onFileNameTemplateChanged();
    void onPresetSave();
    void onPresetLoad();
    void onPresetDelete();
    void onPresetExport();
    void onPresetImport();
    void onTestAudioDevice();
    void onTestVideoDevice();
    void onResetCategory();
    void onApplySettings();
    void onOkClicked();
    void onCancelClicked();
    void updatePreview();
    void refreshDevices();

signals:
    /**
     * 设置已应用信号
     */
    void settingsApplied(const Settings& settings);
    
    /**
     * 设置已改变信号
     */
    void settingsChanged();

private:
    /**
     * 初始化UI
     */
    void initializeUI();
    
    /**
     * 创建音频设置页面
     */
    QWidget* createAudioSettingsPage();
    
    /**
     * 创建视频设置页面
     */
    QWidget* createVideoSettingsPage();
    
    /**
     * 创建输出设置页面
     */
    QWidget* createOutputSettingsPage();
    
    /**
     * 创建高级设置页面
     */
    QWidget* createAdvancedSettingsPage();
    
    /**
     * 创建预设管理页面
     */
    QWidget* createPresetSettingsPage();
    
    /**
     * 连接信号槽
     */
    void connectSignals();
    
    /**
     * 更新UI状态
     */
    void updateUI();
    
    /**
     * 更新音频设备列表
     */
    void updateAudioDevices();
    
    /**
     * 更新视频设备列表
     */
    void updateVideoDevices();
    
    /**
     * 更新编码器列表
     */
    void updateCodecLists();
    
    /**
     * 更新预设列表
     */
    void updatePresetList();
    
    /**
     * 从UI读取设置
     */
    void readSettingsFromUI();
    
    /**
     * 将设置写入UI
     */
    void writeSettingsToUI();
    
    /**
     * 获取默认设置
     */
    Settings getDefaultSettings() const;
    
    /**
     * 格式化文件名预览
     */
    QString formatFileNamePreview() const;
    
    /**
     * 验证输出目录
     */
    bool validateOutputDirectory(const QString& path) const;
    
    /**
     * 创建设置组
     */
    QGroupBox* createSettingsGroup(const QString& title, QWidget* content);
    
    /**
     * 创建标签和控件的水平布局
     */
    QHBoxLayout* createLabeledControl(const QString& label, QWidget* control, 
                                     const QString& tooltip = QString());
    
    /**
     * 保存预设到文件
     */
    bool savePresetToFile(const QString& name, const Settings& settings);
    
    /**
     * 从文件加载预设
     */
    bool loadPresetFromFile(const QString& name, Settings& settings);
    
    /**
     * 获取预设文件路径
     */
    QString getPresetFilePath(const QString& name) const;
    
    /**
     * 获取预设目录
     */
    QString getPresetDirectory() const;

private:
    // 核心组件
    av::recorder::RecorderModule* m_recorderModule;
    
    // UI组件
    QTabWidget* m_tabWidget;
    QVBoxLayout* m_mainLayout;
    QHBoxLayout* m_buttonLayout;
    
    // 按钮
    QPushButton* m_okButton;
    QPushButton* m_cancelButton;
    QPushButton* m_applyButton;
    QPushButton* m_resetButton;
    
    // 音频设置控件
    QComboBox* m_audioDeviceCombo;
    QComboBox* m_audioSampleRateCombo;
    QComboBox* m_audioChannelsCombo;
    QComboBox* m_audioBitDepthCombo;
    QComboBox* m_audioCodecCombo;
    QSpinBox* m_audioBitrateSpinBox;
    QCheckBox* m_audioNoiseSuppressionCheckBox;
    QCheckBox* m_audioEchoCancellationCheckBox;
    QDoubleSpinBox* m_audioInputGainSpinBox;
    QPushButton* m_testAudioButton;
    
    // 视频设置控件
    QComboBox* m_videoDeviceCombo;
    QComboBox* m_videoResolutionCombo;
    QDoubleSpinBox* m_videoFrameRateSpinBox;
    QComboBox* m_videoCodecCombo;
    QSpinBox* m_videoBitrateSpinBox;
    QComboBox* m_videoPresetCombo;
    QComboBox* m_videoProfileCombo;
    QSpinBox* m_videoKeyFrameSpinBox;
    QCheckBox* m_videoHardwareAccelCheckBox;
    QPushButton* m_testVideoButton;
    
    // 输出设置控件
    QLineEdit* m_outputDirectoryEdit;
    QPushButton* m_outputDirectoryBrowseButton;
    QLineEdit* m_fileNameTemplateEdit;
    QLabel* m_fileNamePreviewLabel;
    QComboBox* m_containerFormatCombo;
    QCheckBox* m_autoCreateDirectoryCheckBox;
    QCheckBox* m_overwriteExistingCheckBox;
    QSpinBox* m_maxFileSizeSpinBox;
    QSpinBox* m_maxDurationSpinBox;
    
    // 高级设置控件
    QSpinBox* m_bufferSizeSpinBox;
    QSpinBox* m_threadCountSpinBox;
    QCheckBox* m_gpuAccelerationCheckBox;
    QComboBox* m_gpuDeviceCombo;
    QCheckBox* m_lowLatencyCheckBox;
    QCheckBox* m_realTimeEncodingCheckBox;
    QSlider* m_encodingPrioritySlider;
    QLabel* m_encodingPriorityLabel;
    
    // 预设管理控件
    QListWidget* m_presetListWidget;
    QPushButton* m_savePresetButton;
    QPushButton* m_loadPresetButton;
    QPushButton* m_deletePresetButton;
    QPushButton* m_exportPresetButton;
    QPushButton* m_importPresetButton;
    QTextEdit* m_presetDescriptionEdit;
    
    // 数据
    Settings m_currentSettings;
    Settings m_originalSettings;
    
    // 状态
    bool m_settingsChanged;
    bool m_updating;
    
    // 定时器
    QTimer* m_previewUpdateTimer;
    QTimer* m_deviceRefreshTimer;
};

#endif // AV_RECORDER_SETTINGS_DIALOG_H
