//
//  SubtitleView.swift
//  Dialog_Demo
//
//  对话字幕展示视图 - 滚动对话列表，支持历史记录浏览
//

import UIKit
import SnapKit

class SubtitleView: UIView {

    // MARK: - Message Type

    private enum MessageType {
        case user
        case ai
    }

    private struct MessageItem {
        let type: MessageType
        let label: UILabel
    }

    // MARK: - UI Components

    private lazy var scrollView: UIScrollView = {
        let sv = UIScrollView()
        sv.showsVerticalScrollIndicator = true
        sv.showsHorizontalScrollIndicator = false
        sv.alwaysBounceVertical = true
        sv.contentInset = UIEdgeInsets(top: 8, left: 0, bottom: 8, right: 0)
        return sv
    }()

    private lazy var stackView: UIStackView = {
        let stack = UIStackView()
        stack.axis = .vertical
        stack.spacing = 12
        stack.alignment = .fill
        stack.distribution = .fill
        return stack
    }()

    // MARK: - State

    private var messages: [MessageItem] = []

    /// 是否正在用户手动滚动（手动滚动时不自动跳到底部）
    private var isUserScrolling = false

    // MARK: - Initialization

    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }

    required init?(coder: NSCoder) {
        super.init(coder: coder)
        setupUI()
    }

    // MARK: - Setup

    private func setupUI() {
        backgroundColor = .clear

        addSubview(scrollView)
        scrollView.addSubview(stackView)
        scrollView.delegate = self

        scrollView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }

        stackView.snp.makeConstraints { make in
            make.top.bottom.equalToSuperview()
            make.leading.equalToSuperview().offset(20)
            make.trailing.equalToSuperview().offset(-20)
            make.width.equalToSuperview().offset(-40)
        }
    }

    // MARK: - Public Interface

    /// 添加一条用户消息
    func addUserMessage(_ text: String) {
        let label = createUserLabel(text)
        stackView.addArrangedSubview(label)
        messages.append(MessageItem(type: .user, label: label))
        scrollToBottomAnimated()
    }

    /// 更新最后一条用户消息（识别中间结果）
    func updateLastUserMessage(_ text: String) {
        if let last = messages.last, last.type == .user {
            last.label.attributedText = buildUserAttributedText(text)
            scrollToBottomAnimated()
        } else {
            // 如果最后一条不是用户消息，则新建
            addUserMessage(text)
        }
    }

    /// 添加一条完整的 AI 消息
    func addAIMessage(_ text: String) {
        let label = createAILabel(text)
        stackView.addArrangedSubview(label)
        messages.append(MessageItem(type: .ai, label: label))
        scrollToBottomAnimated()
    }

    /// 更新最后一条 AI 消息（用于流式追加）
    func updateLastAIMessage(_ text: String) {
        if let last = messages.last, last.type == .ai {
            last.label.attributedText = buildAIAttributedText(text)
            scrollToBottomAnimated()
        } else {
            // 如果最后一条不是 AI 消息，则新建一条
            addAIMessage(text)
        }
    }

    /// 清空所有消息
    func clearAll() {
        for message in messages {
            stackView.removeArrangedSubview(message.label)
            message.label.removeFromSuperview()
        }
        messages.removeAll()
    }

    // MARK: - Private Helpers

    private func createUserLabel(_ text: String) -> UILabel {
        let label = UILabel()
        label.numberOfLines = 0
        label.lineBreakMode = .byWordWrapping
        label.attributedText = buildUserAttributedText(text)
        return label
    }

    private func createAILabel(_ text: String) -> UILabel {
        let label = UILabel()
        label.numberOfLines = 0
        label.lineBreakMode = .byWordWrapping
        label.attributedText = buildAIAttributedText(text)
        return label
    }

    /// 构建用户文字的富文本（前缀 "我：" 使用略粗字体）
    private func buildUserAttributedText(_ text: String) -> NSAttributedString {
        let attributed = NSMutableAttributedString()

        let prefixAttrs: [NSAttributedString.Key: Any] = [
            .font: UIFont.systemFont(ofSize: 14, weight: .semibold),
            .foregroundColor: UIColor(red: 0x66/255.0, green: 0x66/255.0, blue: 0x66/255.0, alpha: 1.0)
        ]
        attributed.append(NSAttributedString(string: "我：", attributes: prefixAttrs))

        let textAttrs: [NSAttributedString.Key: Any] = [
            .font: UIFont.systemFont(ofSize: 14),
            .foregroundColor: UIColor(red: 0x66/255.0, green: 0x66/255.0, blue: 0x66/255.0, alpha: 1.0)
        ]
        attributed.append(NSAttributedString(string: text, attributes: textAttrs))

        return attributed
    }

    /// 构建AI文字的富文本（前缀 "AI：" 使用略粗字体）
    private func buildAIAttributedText(_ text: String) -> NSAttributedString {
        let attributed = NSMutableAttributedString()

        let prefixAttrs: [NSAttributedString.Key: Any] = [
            .font: UIFont.systemFont(ofSize: 16, weight: .bold),
            .foregroundColor: UIColor(red: 0x33/255.0, green: 0x33/255.0, blue: 0x33/255.0, alpha: 1.0)
        ]
        attributed.append(NSAttributedString(string: "AI：", attributes: prefixAttrs))

        let textAttrs: [NSAttributedString.Key: Any] = [
            .font: UIFont.systemFont(ofSize: 16, weight: .medium),
            .foregroundColor: UIColor(red: 0x33/255.0, green: 0x33/255.0, blue: 0x33/255.0, alpha: 1.0)
        ]
        attributed.append(NSAttributedString(string: text, attributes: textAttrs))

        return attributed
    }

    /// 滚动到底部（带动画）
    private func scrollToBottomAnimated() {
        // 如果用户正在手动滚动，则不自动滚动
        guard !isUserScrolling else { return }

        layoutIfNeeded()
        DispatchQueue.main.async {
            let bottomOffset = self.scrollView.contentSize.height - self.scrollView.bounds.height + self.scrollView.contentInset.bottom
            if bottomOffset > 0 {
                self.scrollView.setContentOffset(CGPoint(x: 0, y: bottomOffset), animated: true)
            }
        }
    }
}

// MARK: - UIScrollViewDelegate

extension SubtitleView: UIScrollViewDelegate {

    func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
        isUserScrolling = true
    }

    func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
        if !decelerate {
            checkIfAtBottom()
        }
    }

    func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
        checkIfAtBottom()
    }

    /// 如果滚动到底部附近，恢复自动滚动
    private func checkIfAtBottom() {
        let bottomOffset = scrollView.contentSize.height - scrollView.bounds.height + scrollView.contentInset.bottom
        if scrollView.contentOffset.y >= bottomOffset - 20 {
            isUserScrolling = false
        }
    }
}
