//
//  YHCirclePublishViewController.swift
//  galaxy
//
//  Created by alexzzw on 2025/9/24.
//  Copyright © 2025 https://www.galaxy-immi.com. All rights reserved.
//

import UIKit
import SnapKit

class YHCirclePublishViewController: YHBaseViewController {
    
    class UserInfo {
        var userName: String = ""
        var userTitle: String = ""
        var avatar: String = ""
    }
    
    // MARK: - Properties
    private var mediaItems: [YHSelectMediaItem] = []
    private let maxMediaCount = 9
    
    private let marginX: CGFloat = 24
    private let itemSpace: CGFloat = 8
    
    var completion: (() -> Void)?
    
    lazy var userInfoViewModel: YHInformationAuthorizeViewModel = YHInformationAuthorizeViewModel()
    
    private var currentUser: UserInfo?
    
    private var circleId: String?
    private var titleText: String = ""
    private var content: String = ""
    
    lazy var viewModel: YHDynamicViewModel = YHDynamicViewModel()
    
    // MARK: - Navigation Items
    private lazy var leftBarItem: UIBarButtonItem = {
        let item = UIBarButtonItem(image: UIImage(named: "nav_black_24")?.withRenderingMode(.alwaysOriginal), style: .plain, target: self, action: #selector(cancelButtonTapped))
        return item
    }()
    
    private lazy var rightButton: UIButton = {
        let button = UIButton(type: .custom)
        button.frame = CGRect(x: 0, y: 0, width: 56, height: 32)
        button.layer.cornerRadius = 16
        button.clipsToBounds = true
        button.setTitle("发布", for: .normal)
        button.titleLabel?.font = UIFont.PFSC_M(ofSize: 12)
        button.setTitleColor(UIColor.brandGrayColor0, for: .normal)
        button.backgroundColor = UIColor.brandGrayColor8
        button.addTarget(self, action: #selector(publishButtonTapped), for: .touchUpInside)
        return button
    }()
    
    // MARK: - UI Components
    private lazy var scrollView: UIScrollView = {
        let scrollView = UIScrollView()
        scrollView.backgroundColor = .white
        scrollView.showsVerticalScrollIndicator = false
//        scrollView.keyboardDismissMode = .onDrag
        return scrollView
    }()
    
    private lazy var contentView: UIView = {
        let view = UIView()
        view.backgroundColor = .white
        return view
    }()
    
    private lazy var userInfoView: UIView = {
        let view = UIView()
        view.backgroundColor = .white
        return view
    }()
    
    private lazy var avatarImageView: UIImageView = {
        let imageView = UIImageView()
        imageView.image = UIImage(named: "people_head_default") // 设置默认头像
        imageView.layer.cornerRadius = 17
        imageView.clipsToBounds = true
        imageView.contentMode = .scaleAspectFill
        return imageView
    }()
    
    private lazy var usernameLabel: UILabel = {
        let label = UILabel()
        label.font = UIFont.PFSC_R(ofSize: 14)
        label.textColor = .brandGrayColor8
        return label
    }()
    
    private lazy var subtitleLabel: UILabel = {
        let label = UILabel()
        label.font = UIFont.PFSC_R(ofSize: 11)
        label.textColor = UIColor.brandGrayColor6
        return label
    }()
    
    private lazy var textView: UITextView = {
        let textView = UITextView()
        textView.font = UIFont.PFSC_B(ofSize: 17)
        textView.textColor = .brandGrayColor8
        textView.backgroundColor = .clear
        textView.delegate = self
        textView.textContainer.lineFragmentPadding = 0
        textView.textContainerInset = UIEdgeInsets.zero
        textView.showsVerticalScrollIndicator = false
        return textView
    }()
    
    private lazy var placeholderLabel: UILabel = {
        let label = UILabel()
        label.text = "添加标题"
        label.font = UIFont.PFSC_R(ofSize: 17)
        label.textColor = UIColor.brandGrayColor5
        return label
    }()
    
    private lazy var detailTextView: UITextView = {
        let textView = UITextView()
        textView.font = UIFont.PFSC_R(ofSize: 14)
        textView.textColor = UIColor.brandGrayColor8
        textView.backgroundColor = .clear
        textView.delegate = self
        textView.textContainer.lineFragmentPadding = 0
        textView.textContainerInset = UIEdgeInsets.zero
        textView.showsVerticalScrollIndicator = false
        return textView
    }()
    
    private lazy var detailPlaceholderLabel: UILabel = {
        let label = UILabel()
        label.text = "分享生活，表达想法，随时随地..."
        label.font = UIFont.PFSC_R(ofSize: 14)
        label.textColor = UIColor.brandGrayColor5
        label.numberOfLines = 0
        return label
    }()
    
    private lazy var mediaCollectionView: UICollectionView = {
        let layout = UICollectionViewFlowLayout()
        layout.minimumInteritemSpacing = itemSpace
        layout.minimumLineSpacing = itemSpace
        let itemWidth = getItemWidth()
        layout.itemSize = CGSize(width: itemWidth, height: itemWidth)
        
        let collectionView = UICollectionView(frame: .zero, collectionViewLayout: layout)
        collectionView.backgroundColor = .white
        collectionView.delegate = self
        collectionView.dataSource = self
        collectionView.register(YHCircleMediaCell.self, forCellWithReuseIdentifier: "YHCircleMediaCell")
        collectionView.register(YHCircleAddPhotoCell.self, forCellWithReuseIdentifier: "YHCircleAddPhotoCell")
        collectionView.showsVerticalScrollIndicator = false
        return collectionView
    }()
    
    private lazy var divideLine: UIView = {
        let view = UIView()
        view.backgroundColor = UIColor.brandGrayColor3
        return view
    }()
    
    init(currentUser: UserInfo? = nil, id: String? = nil, mediaItems: [YHSelectMediaItem]? = nil, title: String? = nil, content: String? = nil) {
        
        self.currentUser = currentUser
        self.circleId = id
        if let mediaItems = mediaItems {
            self.mediaItems = mediaItems
        }
        if let title = title {
            self.titleText = title
        }
        if let content = content {
            self.content = content
        }
        super.init(nibName: nil, bundle: nil)
    }
    
    @MainActor required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setupNav()
        setupUI()
        setupConstraints()
        setupNotifications()
        updateUserInfo()
        initTextViewsContent()
    }
    
    deinit {
        NotificationCenter.default.removeObserver(self)
        printLog("YHCirclePublishViewController deinit")
    }
    
    // MARK: - Setup Methods
    private func setupNav() {
        gk_navTitle = "发布动态"
        gk_navLeftBarButtonItem = leftBarItem
        gk_navRightBarButtonItem = UIBarButtonItem(customView: rightButton)
        gk_navItemRightSpace = 16
        gk_navItemLeftSpace = 16
        gk_navBackgroundColor = .white
    }
    
    private func setupUI() {
        view.backgroundColor = .white
        
        view.addSubview(scrollView)
        scrollView.addSubview(contentView)
        
        contentView.addSubview(userInfoView)
        userInfoView.addSubview(avatarImageView)
        userInfoView.addSubview(usernameLabel)
        userInfoView.addSubview(subtitleLabel)
        
        contentView.addSubview(textView)
        contentView.addSubview(placeholderLabel)
        contentView.addSubview(divideLine)
        contentView.addSubview(detailTextView)
        contentView.addSubview(detailPlaceholderLabel)
        contentView.addSubview(mediaCollectionView)
    }
    
    private func setupConstraints() {
        scrollView.snp.makeConstraints { make in
            make.top.equalTo(k_Height_NavigationtBarAndStatuBar)
            make.left.right.bottom.equalToSuperview()
        }
        
        contentView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
            make.width.equalTo(view.snp.width)
        }
        
        userInfoView.snp.makeConstraints { make in
            make.top.equalToSuperview().offset(20)
            make.left.right.equalToSuperview().inset(marginX)
        }
        
        avatarImageView.snp.makeConstraints { make in
            make.left.top.equalToSuperview()
            make.width.height.equalTo(34)
            make.bottom.equalToSuperview()
        }
        
        usernameLabel.snp.makeConstraints { make in
            make.left.equalTo(avatarImageView.snp.right).offset(8)
            make.top.equalTo(avatarImageView.snp.top)
            make.right.equalToSuperview()
        }
        
        subtitleLabel.snp.makeConstraints { make in
            make.left.equalTo(usernameLabel)
            make.bottom.equalTo(avatarImageView.snp.bottom)
            make.right.equalToSuperview()
        }
        
        textView.snp.makeConstraints { make in
            make.top.equalTo(userInfoView.snp.bottom).offset(24)
            make.left.right.equalToSuperview().inset(marginX)
            make.height.equalTo(24)
        }
        
        placeholderLabel.snp.makeConstraints { make in
            make.top.left.equalTo(textView)
        }
        
        let pixelOne = 1.0 / UIScreen.main.scale
        divideLine.snp.makeConstraints { make in
            make.top.equalTo(textView.snp.bottom).offset(16)
            make.left.right.equalTo(textView)
            make.height.equalTo(pixelOne)
        }
        
        detailTextView.snp.makeConstraints { make in
            make.top.equalTo(divideLine.snp.bottom).offset(16)
            make.left.right.equalToSuperview().inset(marginX)
            make.height.equalTo(92)
        }
        
        detailPlaceholderLabel.snp.makeConstraints { make in
            make.top.left.equalTo(detailTextView)
        }
        
        mediaCollectionView.snp.makeConstraints { make in
            make.top.equalTo(detailTextView.snp.bottom).offset(24)
            make.left.right.equalToSuperview().inset(marginX)
            make.height.equalTo(200)
            make.bottom.equalToSuperview().offset(-30)
        }
        
        updateCollectionViewHeight()
    }
    
    // 动态更新 TextView 高度
    private func updateTextViewHeight(_ textView: UITextView) {
        let width = textView.frame.width > 0 ? textView.frame.width : UIScreen.main.bounds.width - marginX * 2
        let size = textView.sizeThatFits(CGSize(width: width, height: .infinity))
        
        // 设置最小和最大高度限制
        let minHeight: CGFloat = textView == self.textView ? 24 : 92
        let maxHeight: CGFloat = textView == self.textView ? 100 : CGFloat.infinity
        
        let newHeight = min(max(size.height, minHeight), maxHeight)
        let currentHeight = textView.frame.size.height
        if abs(newHeight - currentHeight) > 1 || currentHeight == 0 {
            textView.snp.updateConstraints { make in
                make.height.equalTo(newHeight)
            }
            
            // 启用/禁用滚动
            textView.isScrollEnabled = size.height > maxHeight
            
            // 动画更新布局
            UIView.animate(withDuration: 0.2) {
                self.view.layoutIfNeeded()
            }
        }
    }
    
    private func updateUserInfo() {
        if let currentUser = currentUser {
            usernameLabel.text = currentUser.userName
            subtitleLabel.text = currentUser.userTitle
            if !currentUser.avatar.isEmpty, let url = URL(string: currentUser.avatar) {
                avatarImageView.kf.setImage(with: url, placeholder: UIImage(named: "people_head_default"))
            } else {
                avatarImageView.image = UIImage(named: "people_head_default")
            }
        } else {
            userInfoViewModel.requestUserInfo { [weak self] _, _ in
                guard let self = self else {
                    return
                }
                self.usernameLabel.text = self.userInfoViewModel.model.username
                self.subtitleLabel.text = self.userInfoViewModel.model.position
                let avatar = self.userInfoViewModel.model.avatar
                if !avatar.isEmpty, let url = URL(string: avatar) {
                    avatarImageView.kf.setImage(with: url, placeholder: UIImage(named: "people_head_default"))
                } else {
                    avatarImageView.image = UIImage(named: "people_head_default")
                }
            }
        }
    }
    
    private func initTextViewsContent() {
        textView.text = self.titleText
        detailTextView.text = self.content
        placeholderLabel.isHidden = !self.titleText.isEmpty
        detailPlaceholderLabel.isHidden = !self.content.isEmpty
        // 如果有初始文本,更新高度
        if !titleText.isEmpty {
            updateTextViewHeight(textView)
        }
        if !content.isEmpty {
            updateTextViewHeight(detailTextView)
        }
    }
    private func setupNotifications() {
        NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow), name: UIResponder.keyboardWillShowNotification, object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide), name: UIResponder.keyboardWillHideNotification, object: nil)
    }
    
    private func getItemWidth() -> CGFloat {
        let itemWidth = (UIScreen.main.bounds.width - marginX * 2 - itemSpace * 2) / 3
        return itemWidth
    }
    
    // MARK: - Actions
    @objc private func cancelButtonTapped() {
        if hasContent() {
            showCancelAlert()
        } else {
            dismiss(animated: true)
        }
    }
    
    @objc private func publishButtonTapped() {
        view.endEditing(true)
        guard !textView.text.isEmpty else {
            YHHUD.flash(message: "标题不能为空")
            return
        }
        guard !mediaItems.isEmpty else {
            YHHUD.flash(message: "请至少添加一张图片")
            return
        }
        // 检查是否所有媒体都上传成功
        let uploadingItems = mediaItems.filter { $0.uploadState == .uploading }
        let failedItems = mediaItems.filter { $0.uploadState == .failed }
        
        if !uploadingItems.isEmpty {
            YHHUD.flash(message: "图片上传中，请稍候...")
            return
        }
        
        if !failedItems.isEmpty {
            YHHUD.flash(message: "部分图片上传失败，请重试")
            return
        }
        
        // 收集所有成功上传的资源
        let resources = mediaItems.compactMap { $0.resourceURL }
        
        guard resources.count == mediaItems.count else {
            YHHUD.flash(message: "图片上传未完成")
            return
        }
        // 发布逻辑
        YHGrayCommonAlertView.show("", "确认发布本次动态？", "返回", "确认发布", fullGuestureEnable: false) {
        } callBack: { [weak self] in
            guard let self = self else {
                return
            }
            // 模拟发布延迟
            // 调用发布接口，传入 resources
            self.publishDynamic(with: resources)
        }
    }
    
    // 7. 实际发布方法
    private func publishDynamic(with resources: [YHResourceURLs]) {
        let title = textView.text ?? ""
        let content = detailTextView.text ?? ""
        
        // 调用你的发布接口
        YHHUD.show(.progress(message: "发布中..."))
        viewModel.publishCircle(self.circleId, title, content, resources: resources) { [weak self] success, error in
            guard let self = self else { return }
            YHHUD.hide()
            if let success = success, !success.isEmpty {
                // self.completion?()
                self.dismiss(animated: true) { [weak self] in
                    guard let self = self else { return }
                    self.gotoCircleDetailPage(id: success)
                }
            } else {
                YHHUD.flash(message: error?.errorMsg ?? "发布失败")
            }
        }
    }
    
    private func gotoCircleDetailPage(id: String) {
        var url = YHBaseUrlManager.shared.businessH5Url() + "/community/activity/\(id)"
        
        if YHLoginManager.shared.isLogin() {
            let token = YHLoginManager.shared.h5Token
            let urlHasParam = String.hasQueryParameters(urlString: url)
            if urlHasParam {
                url = url + "&param=" + token
            } else {
                url = url + "?param=" + token
            }
        }
        var tUrl = url
        if !url.contains("navigationH=") {
            tUrl = url + "?navigationH=\(k_Height_NavigationtBarAndStatuBar)"
            if url.contains("?") {
                tUrl = url + "&navigationH=\(k_Height_NavigationtBarAndStatuBar)"
            }
        }
        let vc = YHH5WebViewVC()
        vc.url = tUrl
        UIViewController.current?.navigationController?.pushViewController(vc)
    }
    
    // MARK: - Keyboard Handling
    @objc private func keyboardWillShow(notification: NSNotification) {
        guard let keyboardFrame = notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? CGRect,
              let duration = notification.userInfo?[UIResponder.keyboardAnimationDurationUserInfoKey] as? Double else { return }
        
        let keyboardHeight = keyboardFrame.height
        
        UIView.animate(withDuration: duration) {
            self.scrollView.contentInset.bottom = keyboardHeight
            self.scrollView.verticalScrollIndicatorInsets.bottom = keyboardHeight
        }
    }
    
    @objc private func keyboardWillHide(notification: NSNotification) {
        guard let duration = notification.userInfo?[UIResponder.keyboardAnimationDurationUserInfoKey] as? Double else { return }
        
        UIView.animate(withDuration: duration) {
            self.scrollView.contentInset.bottom = 0
            self.scrollView.verticalScrollIndicatorInsets.bottom = 0
        }
    }
    
    // MARK: - Helper Methods
    private func hasContent() -> Bool {
        return !textView.text.isEmpty || !detailTextView.text.isEmpty || !mediaItems.isEmpty
    }
    
    private func updateCollectionViewHeight() {
        let rows = ceil(Double(mediaItems.count + 1) / 3.0)
        let itemWidth = getItemWidth()
        let height = CGFloat(rows) * itemWidth + CGFloat(max(0, rows - 1)) * 8
        
        mediaCollectionView.snp.updateConstraints { make in
            make.height.equalTo(max(height, itemWidth))
        }
    }
    
    private func showCancelAlert() {
        YHGrayCommonAlertView.show("确定要离开吗？", "离开后内容将不会保存", "取消", "确定", fullGuestureEnable: false) {
        } callBack: { [weak self] in
            guard let self = self else {
                return
            }
            self.dismiss(animated: true)
        }
    }
    
}

// MARK: - UITextViewDelegate
extension YHCirclePublishViewController: UITextViewDelegate {
    func textViewDidChange(_ textView: UITextView) {
        if textView == self.textView {
            placeholderLabel.isHidden = !textView.text.isEmpty
            updateTextViewHeight(textView)
        } else if textView == detailTextView {
            detailPlaceholderLabel.isHidden = !textView.text.isEmpty
            updateTextViewHeight(textView)
        }
    }
    
    func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
        let currentText = textView.text ?? ""
        guard let stringRange = Range(range, in: currentText) else { return false }
        let updatedText = currentText.replacingCharacters(in: stringRange, with: text)
        
        if textView == self.textView {
            // 标题限制20个字符
            if updatedText.count > 20 {
                YHHUD.flash(message: "标题最多20个字符")
                return false
            }
            return true
        } else if textView == self.detailTextView {
            // 详情限制1000个字符
            if updatedText.count > 1000 {
                YHHUD.flash(message: "内容最多1000个字符")
                return false
            }
            return true
        }
        
        return true
    }
}

// MARK: - UICollectionViewDataSource & Delegate
extension YHCirclePublishViewController: UICollectionViewDataSource, UICollectionViewDelegate {
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return min(mediaItems.count + 1, maxMediaCount)
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        if indexPath.item < mediaItems.count {
            if let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "YHCircleMediaCell", for: indexPath) as? YHCircleMediaCell {
                cell.configure(with: mediaItems[indexPath.item])
                cell.deleteCallback = { [weak self] in
                    self?.removeMedia(at: indexPath.item)
                }
                return cell
            }
        } else {
            if let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "YHCircleAddPhotoCell", for: indexPath) as? YHCircleAddPhotoCell {
                return cell
            }
        }
        return UICollectionViewCell()
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        if indexPath.item >= mediaItems.count {
            showMediaUploadSheet()
        } else {
            // 预览本地选中的媒体
            previewLocalMedia(at: indexPath.item)
        }
    }
    
    // 预览本地选择的媒体文件
    private func previewLocalMedia(at index: Int) {
        
        YHPictureReviewManager.shared.showLocalMedia(
            curIndex: index,
            selectMediaItems: self.mediaItems
        ) { [weak self] deletedIndex in
            // 删除回调处理
            guard let self = self else { return }
            
            DispatchQueue.main.async {
                // 从本地媒体数组中删除对应项
                if deletedIndex < self.mediaItems.count {
                    self.mediaItems.remove(at: deletedIndex)
                    
                    // 刷新集合视图
                    self.mediaCollectionView.reloadData()
                    self.updateCollectionViewHeight()
                    
                    printLog("已从发布页面删除媒体项，剩余: \(self.mediaItems.count)")
                }
            }
        }
    }
    
    private func removeMedia(at index: Int) {
        let item = mediaItems[index]
        // 如果已经上传成功，可以选择是否通知后端删除
        if item.uploadState == .success {
            // TODO: 可选 - 通知后端删除资源
            // viewModel.deleteResource(item.resourceURL?.url)
        }
        
        mediaItems.remove(at: index)
        mediaCollectionView.reloadData()
        updateCollectionViewHeight()
    }
    
    private func showMediaUploadSheet() {
        YHMediaUploadSheetView.sheetView().show { [weak self] selectedMediaItems in
            guard let self = self else { return }
            
            // 检查是否超出最大数量限制
            let remainingSlots = maxMediaCount - mediaItems.count
            let itemsToAdd = Array(selectedMediaItems.prefix(remainingSlots))
            
            if itemsToAdd.count < selectedMediaItems.count {
                YHHUD.flash(message: "最多只能选择\(maxMediaCount)个媒体文件")
            }
            
            // 添加新选择的媒体项
            mediaItems.append(contentsOf: itemsToAdd)
            
            mediaCollectionView.reloadData()
            updateCollectionViewHeight()
            
            printLog("获得 \(itemsToAdd.count) 个媒体文件")
            // 为每个新添加的 item 开始上传
            itemsToAdd.forEach { item in
                self.uploadMediaItem(item)
            }
        }
    }
    
    // 4. 独立的上传方法
    private func uploadMediaItem(_ item: YHSelectMediaItem) {
        guard let image = item.image else {
            item.uploadState = .failed
            return
        }
        
        item.uploadState = .uploading
        
        viewModel.uploadImage(image, true) { [weak item] success, error in
            guard let item = item else { return }
            let imageUrl = (success ?? "").getCdnUrl()
            guard !imageUrl.isEmpty else {
                item.uploadState = .failed
                if let error = error {
                    item.uploadError = error
                    printLog("上传失败: \(item.name), error: \(error)")
                    return
                }
                return
            }
            
            // 创建并保存到 item 自身
            let source = YHResourceURLs()
            source.url = imageUrl
            source.width = "\(image.size.width)"
            source.height = "\(image.size.height)"
            source.type = 1
            source.name = item.name
            
            item.resourceURL = source
            item.uploadState = .success
            printLog("上传成功: \(item.name)")
        }
    }
}
