//
//  LNProfileFeedProvider.swift
//  Gami
//
//  Created by OneeChan on 2026/3/2.
//

import Foundation
import UIKit
import MJRefresh


class LNProfileFeedProvider: NSObject, LNProfileBaseProvider {
    private(set) var title: String = .init(key: "A00303")
    private weak var tableView: UITableView?
    private var curDetail: LNUserProfileVO?
    private var loading = false
    private var feedList: [LNFeedItemVO] = []
    private var nextTag: String?
    
    var numberOfCell: Int {
        feedList.count
    }
    
    override init() {
        super.init()
        
        LNEventDeliver.addObserver(self)
    }
    
    func registerCell(tableView: UITableView) {
        tableView.register(LNProfileFeedItemCell.self, forCellReuseIdentifier: LNProfileFeedItemCell.className)
        self.tableView = tableView
        
        let footer = MJRefreshAutoNormalFooter { [weak self] in
            guard let self else { return }
            self.loadList()
        }
        footer.setTitle("", for: .noMoreData)
        footer.setTitle(.init(key: "A00046"), for: .idle)
        footer.endRefreshingCompletionBlock = { [weak self] in
            guard let self else { return }
            loadList()
        }
        tableView.mj_footer = footer
    }
    
    func buildCell(tableView: UITableView, indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: LNProfileFeedItemCell.className, for: indexPath) as! LNProfileFeedItemCell
        
        let data = feedList[indexPath.row]
        cell.update(data)
        
        return cell
    }
    
    func onAppear() {
        autoPlayVideo()
    }
    
    func update(_ detail: LNUserProfileVO) {
        curDetail = detail
        loadList()
    }
}

extension LNProfileFeedProvider: LNFeedManagerNotify {
    func onPostFeedSuccess() {
        guard let curDetail else { return }
        LNFeedManager.shared.getFeedList(uid: curDetail.userNo, next: nil) { [weak self] res in
            guard let self else { return }
            guard let res else { return }
            
            let curFirst = feedList.first?.id ?? ""
            if let index = res.list.firstIndex(where: { $0.id == curFirst })  {
                let newItems = res.list[..<index]
                feedList.insert(contentsOf: newItems, at: 0)
            } else {
                feedList.insert(contentsOf: res.list, at: 0)
            }
            tableView?.reloadData()
        }
    }
    
    func onFeedDelete(id: String) {
        feedList.removeAll { $0.id == id }
        tableView?.reloadData()
    }
}

extension LNProfileFeedProvider: UITableViewDelegate {
    func tableView(_ tableView: UITableView, didEndDisplaying cell: UITableViewCell, forRowAt indexPath: IndexPath) {
        guard let view = cell as? LNProfileFeedItemCell, view.isVideo else {
            return
        }
        view.stopPlayVideoIfNeed()
    }

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

    func scrollViewDidEndScrollingAnimation(_ scrollView: UIScrollView) {
        autoPlayVideo()
    }

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

extension LNProfileFeedProvider {
    private func autoPlayVideo() {
        guard let tableView else { return }
        let visibleRows = tableView.visibleCells.compactMap { $0 as? LNProfileFeedItemCell }
        let videoCells = visibleRows.compactMap {
            if $0.isVideo {
                $0
            } else {
                nil
            }
        }

        if videoCells.isEmpty { return }
        else {
            let first = videoCells.first {
                tableView.contentOffset.y - $0.frame.minY < 100
                && tableView.contentOffset.y + tableView.bounds.height - $0.frame.minY > 300
            }
            videoCells.forEach {
                if $0 != first {
                    $0.stopPlayVideoIfNeed()
                } else {
                    $0.autoPlayVideoIfNeed()
                }
            }
        }
    }
}

extension LNProfileFeedProvider {
    private func loadList() {
        guard let curDetail, !loading else { return }
        loading = true
        let curNext = nextTag ?? ""
        LNFeedManager.shared.getFeedList(uid: curDetail.userNo, next: curNext) { [weak self] res in
            guard let self else { return }
            loading = false
            if let res {
                if curNext.isEmpty {
                    feedList.removeAll()
                }
                feedList.append(contentsOf: res.list)
                self.nextTag = nextTag
                tableView?.reloadData()
            }
            
            if nextTag?.isEmpty != false {
                tableView?.mj_footer?.endRefreshingWithNoMoreData()
            } else {
                tableView?.mj_footer?.endRefreshing()
            }
        }
    }
}
