#include "recorder_audio_widget.h"
#include <QComboBox>
#include <QDateTime>
#include <QDebug>
#include <QPainterPath>
#include <QLinearGradient>
#include <QApplication>
#include <QStyle>
#include <cmath>

// AudioLevelWidget 实现

AudioLevelWidget::AudioLevelWidget(QWidget* parent)
    : QWidget(parent)
    , m_leftLevel(0.0)
    , m_rightLevel(0.0)
    , m_leftPeak(0.0)
    , m_rightPeak(0.0)
    , m_leftPeakTime(0)
    , m_rightPeakTime(0)
    , m_peakHoldTime(1500)
    , m_overloadThreshold(0.95)
    , m_showValues(true) {
    
    setMinimumSize(100, 40);
    setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed);
    
    // 创建峰值更新定时器
    m_peakTimer = new QTimer(this);
    connect(m_peakTimer, &QTimer::timeout, this, &AudioLevelWidget::updatePeaks);
    m_peakTimer->start(50); // 20fps更新
}

AudioLevelWidget::~AudioLevelWidget() = default;

void AudioLevelWidget::setLeftLevel(double level) {
    QMutexLocker locker(&m_mutex);
    
    level = qBound(0.0, level, 1.0);
    m_leftLevel = level;
    
    // 更新峰值
    qint64 currentTime = QDateTime::currentMSecsSinceEpoch();
    if (level > m_leftPeak) {
        m_leftPeak = level;
        m_leftPeakTime = currentTime;
    }
    
    update();
}

void AudioLevelWidget::setRightLevel(double level) {
    QMutexLocker locker(&m_mutex);
    
    level = qBound(0.0, level, 1.0);
    m_rightLevel = level;
    
    // 更新峰值
    qint64 currentTime = QDateTime::currentMSecsSinceEpoch();
    if (level > m_rightPeak) {
        m_rightPeak = level;
        m_rightPeakTime = currentTime;
    }
    
    update();
}

void AudioLevelWidget::setLevels(double left, double right) {
    QMutexLocker locker(&m_mutex);
    
    left = qBound(0.0, left, 1.0);
    right = qBound(0.0, right, 1.0);
    
    m_leftLevel = left;
    m_rightLevel = right;
    
    // 更新峰值
    qint64 currentTime = QDateTime::currentMSecsSinceEpoch();
    
    if (left > m_leftPeak) {
        m_leftPeak = left;
        m_leftPeakTime = currentTime;
    }
    
    if (right > m_rightPeak) {
        m_rightPeak = right;
        m_rightPeakTime = currentTime;
    }
    
    update();
}

void AudioLevelWidget::resetPeaks() {
    QMutexLocker locker(&m_mutex);
    
    m_leftPeak = 0.0;
    m_rightPeak = 0.0;
    m_leftPeakTime = 0;
    m_rightPeakTime = 0;
    
    update();
}

void AudioLevelWidget::paintEvent(QPaintEvent* event) {
    Q_UNUSED(event)
    
    QPainter painter(this);
    painter.setRenderHint(QPainter::Antialiasing);
    
    QMutexLocker locker(&m_mutex);
    
    // 计算绘制区域
    QRect drawRect = rect().adjusted(2, 2, -2, -2);
    int channelHeight = (drawRect.height() - 4) / 2;
    
    // 绘制左声道
    QRect leftRect(drawRect.x(), drawRect.y(), drawRect.width(), channelHeight);
    drawChannel(painter, leftRect, m_leftLevel, m_leftPeak, true);
    
    // 绘制右声道
    QRect rightRect(drawRect.x(), drawRect.y() + channelHeight + 4, 
                   drawRect.width(), channelHeight);
    drawChannel(painter, rightRect, m_rightLevel, m_rightPeak, false);
    
    // 绘制标签
    painter.setPen(Qt::white);
    painter.setFont(QFont("Arial", 8));
    
    painter.drawText(leftRect.adjusted(2, 0, 0, 0), Qt::AlignLeft | Qt::AlignVCenter, "L");
    painter.drawText(rightRect.adjusted(2, 0, 0, 0), Qt::AlignLeft | Qt::AlignVCenter, "R");
    
    // 绘制数值
    if (m_showValues) {
        QString leftText = QString("%1").arg(static_cast<int>(m_leftLevel * 100));
        QString rightText = QString("%1").arg(static_cast<int>(m_rightLevel * 100));
        
        painter.drawText(leftRect.adjusted(0, 0, -2, 0), Qt::AlignRight | Qt::AlignVCenter, leftText);
        painter.drawText(rightRect.adjusted(0, 0, -2, 0), Qt::AlignRight | Qt::AlignVCenter, rightText);
    }
}

QSize AudioLevelWidget::sizeHint() const {
    return QSize(180, 32);
}

QSize AudioLevelWidget::minimumSizeHint() const {
    return QSize(120, 32);
}

void AudioLevelWidget::updatePeaks() {
    QMutexLocker locker(&m_mutex);
    
    qint64 currentTime = QDateTime::currentMSecsSinceEpoch();
    bool needUpdate = false;
    
    // 检查左声道峰值是否过期
    if (m_leftPeakTime > 0 && (currentTime - m_leftPeakTime) > m_peakHoldTime) {
        m_leftPeak = m_leftLevel;
        m_leftPeakTime = currentTime;
        needUpdate = true;
    }
    
    // 检查右声道峰值是否过期
    if (m_rightPeakTime > 0 && (currentTime - m_rightPeakTime) > m_peakHoldTime) {
        m_rightPeak = m_rightLevel;
        m_rightPeakTime = currentTime;
        needUpdate = true;
    }
    
    if (needUpdate) {
        update();
    }
}

void AudioLevelWidget::drawChannel(QPainter& painter, const QRect& rect, 
                                  double level, double peak, bool isLeft) {
    Q_UNUSED(isLeft)
    
    // 绘制背景
    painter.fillRect(rect, QColor(40, 40, 40));
    
    // 绘制边框
    painter.setPen(QColor(80, 80, 80));
    painter.drawRect(rect);
    
    if (level <= 0.0) {
        return;
    }
    
    // 计算电平条宽度
    int levelWidth = static_cast<int>(rect.width() * level);
    QRect levelRect(rect.x(), rect.y(), levelWidth, rect.height());
    
    // 创建渐变
    QLinearGradient gradient(levelRect.topLeft(), levelRect.topRight());
    
    if (level < 0.7) {
        // 绿色区域
        gradient.setColorAt(0.0, QColor(0, 255, 0));
        gradient.setColorAt(1.0, QColor(100, 255, 0));
    } else if (level < m_overloadThreshold) {
        // 黄色区域
        gradient.setColorAt(0.0, QColor(100, 255, 0));
        gradient.setColorAt(0.5, QColor(255, 255, 0));
        gradient.setColorAt(1.0, QColor(255, 200, 0));
    } else {
        // 红色区域（过载）
        gradient.setColorAt(0.0, QColor(255, 200, 0));
        gradient.setColorAt(1.0, QColor(255, 0, 0));
    }
    
    painter.fillRect(levelRect, gradient);
    
    // 绘制峰值线
    if (peak > level && peak > 0.0) {
        int peakX = static_cast<int>(rect.x() + rect.width() * peak);
        QColor peakColor = getLevelColor(peak);
        
        painter.setPen(QPen(peakColor, 2));
        painter.drawLine(peakX, rect.y(), peakX, rect.y() + rect.height());
    }
}

QColor AudioLevelWidget::getLevelColor(double level) const {
    if (level < 0.7) {
        return QColor(0, 255, 0); // 绿色
    } else if (level < m_overloadThreshold) {
        return QColor(255, 255, 0); // 黄色
    } else {
        return QColor(255, 0, 0); // 红色
    }
}

// RecorderAudioWidget 实现

RecorderAudioWidget::RecorderAudioWidget(QWidget* parent)
    : QWidget(parent)
    , m_mainLayout(nullptr)
    , m_controlLayout(nullptr)
    , m_deviceLayout(nullptr)
    , m_infoLayout(nullptr)
    , m_volumeLabel(nullptr)
    , m_volumeSlider(nullptr)
    , m_volumeValueLabel(nullptr)
    , m_muteButton(nullptr)
    , m_levelWidget(nullptr)
    , m_deviceLabel(nullptr)
    , m_deviceCombo(nullptr)
    , m_settingsButton(nullptr)
    , m_statusLabel(nullptr)
    , m_volumeAnimation(nullptr)
    , m_levelOpacityEffect(nullptr)
    , m_showAdvancedControls(true)
    , m_volumeChanging(false) {
    
    initializeUI();
    connectSignals();
    updateUI();
}

RecorderAudioWidget::~RecorderAudioWidget() = default;

void RecorderAudioWidget::setAudioInfo(const AudioInfo& info) {
    QMutexLocker locker(&m_mutex);
    
    m_audioInfo = info;
    
    // 更新UI（在主线程中）
    QMetaObject::invokeMethod(this, "updateUI", Qt::QueuedConnection);
}

void RecorderAudioWidget::setVolume(double volume) {
    QMutexLocker locker(&m_mutex);
    
    volume = qBound(0.0, volume, 1.0);
    if (qAbs(m_audioInfo.volume - volume) < 0.001) {
        return;
    }
    
    m_audioInfo.volume = volume;
    
    // 更新滑块（避免循环信号）
    if (!m_volumeChanging) {
        QMetaObject::invokeMethod(this, "updateVolumeDisplay", Qt::QueuedConnection);
    }
    
    emit volumeChanged(volume);
}

void RecorderAudioWidget::setMuted(bool muted) {
    QMutexLocker locker(&m_mutex);
    
    if (m_audioInfo.isMuted == muted) {
        return;
    }
    
    m_audioInfo.isMuted = muted;
    
    QMetaObject::invokeMethod(this, "updateMuteButton", Qt::QueuedConnection);
    
    emit mutedChanged(muted);
}

void RecorderAudioWidget::setRecording(bool recording) {
    QMutexLocker locker(&m_mutex);
    
    if (m_audioInfo.isRecording == recording) {
        return;
    }
    
    m_audioInfo.isRecording = recording;
    
    QMetaObject::invokeMethod(this, "updateUI", Qt::QueuedConnection);
}

void RecorderAudioWidget::updateAudioLevels(double left, double right) {
    if (m_levelWidget) {
        m_levelWidget->setLevels(left, right);
    }
}

void RecorderAudioWidget::setAvailableDevices(const QStringList& devices) {
    if (!m_deviceCombo) {
        return;
    }
    
    // 保存当前选择
    QString currentDevice = m_deviceCombo->currentText();
    
    // 更新设备列表
    m_deviceCombo->clear();
    m_deviceCombo->addItems(devices);
    
    // 恢复选择
    int index = m_deviceCombo->findText(currentDevice);
    if (index >= 0) {
        m_deviceCombo->setCurrentIndex(index);
    }
}

void RecorderAudioWidget::setCurrentDevice(const QString& device) {
    if (!m_deviceCombo) {
        return;
    }
    
    int index = m_deviceCombo->findText(device);
    if (index >= 0) {
        m_deviceCombo->setCurrentIndex(index);
    }
    
    QMutexLocker locker(&m_mutex);
    m_audioInfo.deviceName = device;
    
    QMetaObject::invokeMethod(this, "updateDeviceInfo", Qt::QueuedConnection);
}

QString RecorderAudioWidget::currentDevice() const {
    if (!m_deviceCombo) {
        return QString();
    }
    
    return m_deviceCombo->currentText();
}

void RecorderAudioWidget::setShowAdvancedControls(bool show) {
    m_showAdvancedControls = show;
    
    if (m_deviceLayout) {
        m_deviceLabel->setVisible(show);
        m_deviceCombo->setVisible(show);
        m_settingsButton->setVisible(show);
    }
}

void RecorderAudioWidget::resetAudioPeaks() {
    if (m_levelWidget) {
        m_levelWidget->resetPeaks();
    }
}

void RecorderAudioWidget::paintEvent(QPaintEvent* event) {
    // 绘制背景
    QStyleOption opt;
    opt.init(this);
    QPainter painter(this);
    style()->drawPrimitive(QStyle::PE_Widget, &opt, &painter, this);
    
    QWidget::paintEvent(event);
}

void RecorderAudioWidget::onVolumeSliderChanged(int value) {
    m_volumeChanging = true;
    
    double volume = value / 100.0;
    setVolume(volume);
    
    // 更新数值标签
    if (m_volumeValueLabel) {
        m_volumeValueLabel->setText(QString("%1%").arg(value));
    }
    
    m_volumeChanging = false;
}

void RecorderAudioWidget::onMuteButtonClicked() {
    setMuted(!isMuted());
}

void RecorderAudioWidget::onDeviceComboChanged(const QString& device) {
    QMutexLocker locker(&m_mutex);
    m_audioInfo.deviceName = device;
    locker.unlock();
    
    updateDeviceInfo();
    emit deviceChanged(device);
}

void RecorderAudioWidget::onSettingsButtonClicked() {
    emit audioSettingsRequested();
}

void RecorderAudioWidget::updateVolumeAnimation() {
    // 音量变化动画效果
    if (m_volumeAnimation && m_levelWidget) {
        // 可以添加音量变化的视觉反馈
    }
}

void RecorderAudioWidget::initializeUI() {
    // 创建主布局
    m_mainLayout = new QVBoxLayout(this);
    m_mainLayout->setContentsMargins(6, 6, 6, 6);
    m_mainLayout->setSpacing(4);
    
    // 音量控制布局
    m_controlLayout = new QHBoxLayout();
    m_controlLayout->setSpacing(6);
    
    m_volumeLabel = new QLabel("音量:");
    m_volumeLabel->setMinimumWidth(35);
    m_volumeLabel->setMaximumWidth(35);
    
    m_volumeSlider = new QSlider(Qt::Horizontal);
    m_volumeSlider->setRange(0, 100);
    m_volumeSlider->setValue(100);
    m_volumeSlider->setMinimumWidth(80);
    m_volumeSlider->setMaximumHeight(20);
    
    m_volumeValueLabel = new QLabel("100%");
    m_volumeValueLabel->setMinimumWidth(30);
    m_volumeValueLabel->setMaximumWidth(30);
    m_volumeValueLabel->setAlignment(Qt::AlignRight | Qt::AlignVCenter);
    
    m_muteButton = new QPushButton();
    m_muteButton->setCheckable(true);
    m_muteButton->setFixedSize(20, 20);
    m_muteButton->setToolTip("静音/取消静音");
    
    m_controlLayout->addWidget(m_volumeLabel);
    m_controlLayout->addWidget(m_volumeSlider, 1);
    m_controlLayout->addWidget(m_volumeValueLabel);
    m_controlLayout->addWidget(m_muteButton);
    
    // 音频电平显示
    m_levelWidget = new AudioLevelWidget();
    m_levelWidget->setFixedHeight(32);  // 固定高度，避免被挤压
    m_levelWidget->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed);
    
    // 设备选择布局（简化版）
    m_deviceLayout = new QHBoxLayout();
    m_deviceLayout->setSpacing(4);
    
    m_deviceLabel = new QLabel("设备:");
    m_deviceLabel->setMinimumWidth(35);
    m_deviceLabel->setMaximumWidth(35);
    
    m_deviceCombo = new QComboBox();
    m_deviceCombo->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed);
    m_deviceCombo->setMaximumHeight(22);
    
    m_settingsButton = new QPushButton("⚙");
    m_settingsButton->setFixedSize(20, 20);
    m_settingsButton->setToolTip("音频设置");
    
    m_deviceLayout->addWidget(m_deviceLabel);
    m_deviceLayout->addWidget(m_deviceCombo, 1);
    m_deviceLayout->addWidget(m_settingsButton);
    
    // 状态显示布局（简化版）
    m_infoLayout = new QHBoxLayout();
    m_infoLayout->setSpacing(4);
    
    m_statusLabel = new QLabel("待机");
    m_statusLabel->setStyleSheet("font-size: 8pt; color: #888;");
    m_statusLabel->setAlignment(Qt::AlignRight | Qt::AlignVCenter);

    m_infoLayout->addStretch();
    m_infoLayout->addWidget(m_statusLabel);
    
    // 添加到主布局
    m_mainLayout->addLayout(m_controlLayout);
    m_mainLayout->addWidget(m_levelWidget);
    m_mainLayout->addLayout(m_deviceLayout);
    m_mainLayout->addLayout(m_infoLayout);
    
    // 创建动画
    m_volumeAnimation = new QPropertyAnimation(this, "volume");
    m_volumeAnimation->setDuration(200);
    m_volumeAnimation->setEasingCurve(QEasingCurve::OutCubic);
    
    // 设置样式
    // setStyleSheet(R"(
    //     RecorderAudioWidget {
    //         background-color: #2b2b2b;
    //         border: 1px solid #555;
    //         border-radius: 4px;
    //     }
    //     QLabel {
    //         color: #fff;
    //     }
    //     QSlider::groove:horizontal {
    //         border: 1px solid #555;
    //         height: 6px;
    //         background: #333;
    //         border-radius: 3px;
    //     }
    //     QSlider::handle:horizontal {
    //         background: #0a84ff;
    //         border: 1px solid #0a84ff;
    //         width: 14px;
    //         margin: -4px 0;
    //         border-radius: 7px;
    //     }
    //     QSlider::sub-page:horizontal {
    //         background: #0a84ff;
    //         border-radius: 3px;
    //     }
    //     QPushButton {
    //         background-color: #444;
    //         border: 1px solid #666;
    //         border-radius: 3px;
    //         color: #fff;
    //         padding: 4px 8px;
    //     }
    //     QPushButton:hover {
    //         background-color: #555;
    //     }
    //     QPushButton:pressed {
    //         background-color: #333;
    //     }
    //     QPushButton:checked {
    //         background-color: #0a84ff;
    //     }
    //     QComboBox {
    //         background-color: #444;
    //         border: 1px solid #666;
    //         border-radius: 3px;
    //         color: #fff;
    //         padding: 4px;
    //     }
    //     QComboBox::drop-down {
    //         border: none;
    //     }
    //     QComboBox::down-arrow {
    //         image: none;
    //         border-left: 4px solid transparent;
    //         border-right: 4px solid transparent;
    //         border-top: 4px solid #fff;
    //     }
    // )");
}

void RecorderAudioWidget::connectSignals() {
    // 音量控制信号
    connect(m_volumeSlider, QOverload<int>::of(&QSlider::valueChanged),
            this, &RecorderAudioWidget::onVolumeSliderChanged);
    
    connect(m_muteButton, &QPushButton::clicked,
            this, &RecorderAudioWidget::onMuteButtonClicked);
    
    // 设备选择信号
    connect(m_deviceCombo, QOverload<const QString&>::of(&QComboBox::currentTextChanged),
            this, &RecorderAudioWidget::onDeviceComboChanged);
    
    connect(m_settingsButton, &QPushButton::clicked,
            this, &RecorderAudioWidget::onSettingsButtonClicked);
    
    // 动画信号
    connect(m_volumeAnimation, &QPropertyAnimation::valueChanged,
            this, &RecorderAudioWidget::updateVolumeAnimation);
}

void RecorderAudioWidget::updateUI() {
    QMutexLocker locker(&m_mutex);
    AudioInfo info = m_audioInfo;
    locker.unlock();
    
    updateVolumeDisplay();
    updateMuteButton();
    updateDeviceInfo();
    
    // 更新状态标签
    if (m_statusLabel) {
        if (info.isRecording) {
            m_statusLabel->setText("● 录制中");
            m_statusLabel->setStyleSheet("color: #ff3b30; font-weight: bold;");
        } else {
            m_statusLabel->setText("待机");
            m_statusLabel->setStyleSheet("color: #888; font-weight: normal;");
        }
    }
}

void RecorderAudioWidget::updateVolumeDisplay() {
    if (!m_volumeSlider || !m_volumeValueLabel) {
        return;
    }
    
    QMutexLocker locker(&m_mutex);
    int value = static_cast<int>(m_audioInfo.volume * 100);
    locker.unlock();
    
    m_volumeChanging = true;
    m_volumeSlider->setValue(value);
    m_volumeValueLabel->setText(QString("%1%").arg(value));
    m_volumeChanging = false;
}

void RecorderAudioWidget::updateMuteButton() {
    if (!m_muteButton) {
        return;
    }
    
    QMutexLocker locker(&m_mutex);
    bool muted = m_audioInfo.isMuted;
    locker.unlock();
    
    m_muteButton->setChecked(muted);
    m_muteButton->setText(muted ? "🔇" : "🔊");
    m_muteButton->setToolTip(muted ? "取消静音" : "静音");
    
    // 更新音量滑块状态
    if (m_volumeSlider) {
        m_volumeSlider->setEnabled(!muted);
    }
}

void RecorderAudioWidget::updateDeviceInfo() {
    // 设备信息现在通过工具提示显示
    QMutexLocker locker(&m_mutex);
    QString infoText = formatAudioInfoText();
    locker.unlock();
    
    if (m_deviceCombo) {
        m_deviceCombo->setToolTip(infoText);
    }
}

QString RecorderAudioWidget::formatAudioInfoText() const {
    if (m_audioInfo.deviceName.isEmpty()) {
        return "无音频设备";
    }
    
    return QString("%1 | %2Hz %3ch %4bit")
           .arg(m_audioInfo.deviceName)
           .arg(m_audioInfo.sampleRate)
           .arg(m_audioInfo.channels)
           .arg(m_audioInfo.bitDepth);
}
