//
//  LNAutoReplyListViewController.swift
//  Gami
//
//  Created by OneeChan on 2026/3/9.
//

import Foundation
import UIKit
import SnapKit
import MJRefresh
import Combine


extension UIView {
    func pushToAutoReplyList() {
        let vc = LNAutoReplyListViewController()
        navigationController?.pushViewController(vc, animated: true)
    }
}


class LNAutoReplyListViewController: LNViewController {
    private let emptyView = LNNoMoreDataView()
    private let tipsCreateButton = UIButton()
    private let tableView = UITableView()
    private let createButton = UIButton()
    
    private var isLoading = false
    private var items: [LNAutoReplyVO] = []
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        setupViews()
        LNEventDeliver.addObserver(self)
        tableView.mj_header?.beginRefreshing()
    }
}

extension LNAutoReplyListViewController: LNGameMateManagerNotify {
    func onAutoReplyCreated(item: LNAutoReplyVO) {
        loadList()
    }
    
    func onAutoReplyDeleted(id: String) {
        loadList()
    }
    
    func onAutoReplyModified(item: LNAutoReplyVO) {
        loadList()
    }
}

extension LNAutoReplyListViewController {
    private func loadList() {
        guard !isLoading else { return }
        isLoading = true
        
        LNGameMateManager.shared.getAutoReplayList { [weak self] res in
            guard let self else { return }
            isLoading = false
            
            tableView.mj_header?.endRefreshing()
            
            tipsCreateButton.isHidden = true
            if let list = res?.list {
                items = list
                tableView.reloadData()
                
                if items.isEmpty {
                    emptyView.showNoData(icon: .icNoDataRelationEmpty,
                                         tips: .init(key: "B00122"))
                    tipsCreateButton.isHidden = false
                    createButton.isHidden = true
                } else {
                    emptyView.hide()
                    createButton.isHidden = false
                }
            } else {
                if items.isEmpty {
                    emptyView.showNetworkError()
                    createButton.isHidden = true
                }
            }
        }
    }
    
    private func toCreateNewOne() {
        let sheet = LNBottomSheetMenu()
        sheet.update([
            .init(key: "B00119"),
            .init(key: "B00120")
        ]) { [weak self] index, _ in
            guard let self else { return }
            let item = LNAutoReplyVO()
            if index == 0 {
                item.type = .text
            } else {
                item.type = .voice
            }
            item.status = .pass
            view.pushToAutoRelyEdit(num: items.count, item: item)
        }
        sheet.popup()
    }
}

extension LNAutoReplyListViewController: UITableViewDataSource {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        items.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: LNAutoReplyItemCell.className, for: indexPath) as! LNAutoReplyItemCell
        cell.update(indexPath.row, item: items[indexPath.row])
        
        return cell
    }
}

extension LNAutoReplyListViewController {
    private func setupViews() {
        title = .init(key: "B00112")
        view.backgroundColor = .primary_1
        
        let header = MJRefreshNormalHeader { [weak self] in
            guard let self else { return }
            loadList()
        }
        header.lastUpdatedTimeLabel?.isHidden = true
        header.stateLabel?.isHidden = true
        tableView.mj_header = header
        
        tableView.backgroundColor = .clear
        tableView.dataSource = self
        tableView.separatorStyle = .none
        tableView.allowsSelection = false
        tableView.contentInset = .init(top: 2, left: 0, bottom: -view.commonBottomInset + 47, right: 0)
        tableView.register(LNAutoReplyItemCell.self, forCellReuseIdentifier: LNAutoReplyItemCell.className)
        view.addSubview(tableView)
        tableView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
        
        emptyView.tipsLabel.textColor = .black.withAlphaComponent(0.2)
        emptyView.isHidden = true
        tableView.addSubview(emptyView)
        emptyView.snp.makeConstraints { make in
            make.centerX.equalToSuperview()
            make.centerY.equalToSuperview().multipliedBy(0.6)
        }
        
        tipsCreateButton.isHidden = true
        tipsCreateButton.layer.cornerRadius = 23.5
        tipsCreateButton.clipsToBounds = true
        tipsCreateButton.setBackgroundImage(.primary_8, for: .normal)
        tipsCreateButton.setTitle(.init(key: "B00115"), for: .normal)
        tipsCreateButton.titleLabel?.font = .heading_h3
        tipsCreateButton.setTitleColor(.text_1, for: .normal)
        tipsCreateButton.addAction(UIAction(handler: { [weak self] _ in
            guard let self else { return }
            toCreateNewOne()
        }), for: .touchUpInside)
        emptyView.addActionView(tipsCreateButton)
        tipsCreateButton.snp.makeConstraints { make in
            make.width.equalTo(189)
            make.height.equalTo(47)
        }
        
        let bottomMenu = UIView()
        view.addSubview(bottomMenu)
        bottomMenu.snp.makeConstraints { make in
            make.horizontalEdges.equalToSuperview()
            make.bottom.equalToSuperview()
        }
        
        let bottomGradient = CAGradientLayer()
        bottomGradient.colors = [
            UIColor.white.withAlphaComponent(0).cgColor,
            UIColor.white.cgColor,
            UIColor.white.cgColor
        ]
        bottomGradient.locations = [0, 0.5, 1]
        bottomGradient.startPoint = .init(x: 0, y: 0)
        bottomGradient.endPoint = .init(x: 0, y: 1)
        bottomMenu.layer.addSublayer(bottomGradient)
        bottomMenu.publisher(for: \.bounds).removeDuplicates().sink { [weak bottomGradient] newValue in
            guard let bottomGradient else { return }
            bottomGradient.frame = newValue
        }.store(in: &cancellables)
        
        createButton.layer.cornerRadius = 23.5
        createButton.clipsToBounds = true
        createButton.setBackgroundImage(.primary_8, for: .normal)
        createButton.setTitle(.init(key: "B00115"), for: .normal)
        createButton.titleLabel?.font = .heading_h3
        createButton.setTitleColor(.text_1, for: .normal)
        createButton.isHidden = true
        createButton.addAction(UIAction(handler: { [weak self] _ in
            guard let self else { return }
            toCreateNewOne()
        }), for: .touchUpInside)
        bottomMenu.addSubview(createButton)
        createButton.snp.makeConstraints { make in
            make.horizontalEdges.equalToSuperview().inset(16)
            make.bottom.equalToSuperview().offset(view.commonBottomInset)
            make.top.equalToSuperview()
            make.height.equalTo(47)
        }
    }
}
