//
//  LNSkillManagerViewController.swift
//  Gami
//
//  Created by OneeChan on 2026/1/23.
//

import Foundation
import UIKit
import SnapKit


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


class LNSkillManagerViewController: LNViewController {
    private let stackView = UIStackView()
    private let createSkillButton = UIButton()
    private var skills: [LNMySkillItemVO] = []
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        setupViews()
    }
    
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        
        loadApplyInfo()
        loadList()
    }
}

extension LNSkillManagerViewController {
    private func loadList() {
        LNGameMateManager.shared.getMySkillList { [weak self] res in
            guard let self else { return }
            guard let res else {
                navigationController?.popViewController(animated: true)
                return
            }
            
            stackView.arrangedSubviews.forEach {
                self.stackView.removeArrangedSubview($0)
                $0.removeFromSuperview()
            }
            
            for skill in res.list {
                let view = buildSkillItem(skill)
                stackView.addArrangedSubview(view)
            }
            
            skills = res.list
        }
    }
    
    private func loadApplyInfo() {
        LNGameMateManager.shared.getJoinGameMateInfo { [weak self] res in
            guard let self else { return }
            guard let res else { return }
            enableCreate(!res.underReview)
        }
    }
}

extension LNSkillManagerViewController {
    private func enableCreate(_ enable: Bool) {
        if enable != createSkillButton.isEnabled {
            createSkillButton.isEnabled = enable
            createSkillButton.setBackgroundImage(enable ? .primary_8 : nil, for: .normal)
        }
    }
    
    private func setupViews() {
        title = .init(key: "B00076")
        view.backgroundColor = .primary_1
        
        let settingButton = UIButton()
        settingButton.setImage(.icSettings, for: .normal)
        settingButton.addAction(UIAction(handler: { [weak self] _ in
            guard let self else { return }
            view.pushToOrderAcceptSettings()
        }), for: .touchUpInside)
        setRightButton(settingButton)
        
        let scrollView = UIScrollView()
        scrollView.showsVerticalScrollIndicator = false
        scrollView.showsHorizontalScrollIndicator = false
        scrollView.contentInset = .init(top: 12, left: 0, bottom: -view.commonBottomInset + 50, right: 0)
        view.addSubview(scrollView)
        scrollView.snp.makeConstraints { make in
            make.verticalEdges.equalToSuperview()
            make.horizontalEdges.equalToSuperview().inset(16)
        }
        
        stackView.axis = .vertical
        stackView.spacing = 10
        scrollView.addSubview(stackView)
        stackView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
            make.width.equalToSuperview()
        }
        
        createSkillButton.setTitle(.init(key: "B00077"), for: .normal)
        createSkillButton.setTitleColor(.text_1, for: .normal)
        createSkillButton.titleLabel?.font = .heading_h3
        createSkillButton.layer.cornerRadius = 23.5
        createSkillButton.backgroundColor = .fill_4
        createSkillButton.clipsToBounds = true
        createSkillButton.isEnabled = false
        createSkillButton.addAction(UIAction(handler: { [weak self] _ in
            guard let self else { return }
            let curSkills = skills.map { $0.bizCategoryCode }
            view.pushToGameCategoryList(exclude: curSkills) { [weak self] category, game in
                guard let self else { return }
                showLoading()
                LNGameMateManager.shared.getCreateSkillFields(id: game.code) { [weak self] res in
                    dismissLoading()
                    guard let self else { return }
                    guard let res else { return }
                    view.pushToSkillCreate(skill: game, info: res)
                }
            }
        }), for: .touchUpInside)
        view.addSubview(createSkillButton)
        createSkillButton.snp.makeConstraints { make in
            make.horizontalEdges.equalToSuperview().inset(16)
            make.bottom.equalToSuperview().offset(view.commonBottomInset)
            make.height.equalTo(47)
        }
    }
    
    private func buildSkillItem(_ skill: LNMySkillItemVO) -> UIView {
        let container = UIView()
        container.layer.cornerRadius = 12
        container.backgroundColor = .fill
        container.onTap { [weak self] in
            guard let self else { return }
            view.pushToSkillDetail(skill.id)
        }
        
        let infoView = UIView()
        infoView.isUserInteractionEnabled = false
        container.addSubview(infoView)
        infoView.snp.makeConstraints { make in
            make.horizontalEdges.equalToSuperview()
            make.top.equalToSuperview()
            make.height.equalTo(64)
        }
        
        let icon = UIImageView()
        icon.sd_setImage(with: URL(string: skill.categoryIcon))
        infoView.addSubview(icon)
        icon.snp.makeConstraints { make in
            make.centerY.equalToSuperview()
            make.leading.equalToSuperview().offset(12)
            make.width.height.equalTo(50)
        }
        
        let arrow = UIImageView.arrowImageView(size: 16)
        arrow.tintColor = .text_4
        infoView.addSubview(arrow)
        arrow.snp.makeConstraints { make in
            make.centerY.equalToSuperview()
            make.trailing.equalToSuperview().offset(-12)
        }
        
        let textView = UIView()
        infoView.addSubview(textView)
        textView.snp.makeConstraints { make in
            make.centerY.equalToSuperview()
            make.leading.equalTo(icon.snp.trailing).offset(4)
            make.trailing.lessThanOrEqualTo(arrow.snp.leading).offset(-4)
        }
        
        let nameLabel = UILabel()
        nameLabel.text = skill.bizCategoryName
        nameLabel.font = .heading_h4
        nameLabel.textColor = .text_5
        textView.addSubview(nameLabel)
        nameLabel.snp.makeConstraints { make in
            make.horizontalEdges.equalToSuperview()
            make.top.equalToSuperview()
        }
        
        let priceView = UIView()
        textView.addSubview(priceView)
        priceView.snp.makeConstraints { make in
            make.horizontalEdges.equalToSuperview()
            make.bottom.equalToSuperview()
            make.top.equalTo(nameLabel.snp.bottom).offset(4)
        }
        
        let coin = UIImageView.coinImageView()
        priceView.addSubview(coin)
        coin.snp.makeConstraints { make in
            make.leading.equalToSuperview()
            make.centerY.equalToSuperview()
            make.width.height.equalTo(14)
        }
        
        let priceLabel = UILabel()
        priceLabel.text = skill.price.toDisplay
        priceLabel.font = .heading_h5
        priceLabel.textColor = .text_5
        priceView.addSubview(priceLabel)
        priceLabel.snp.makeConstraints { make in
            make.verticalEdges.equalToSuperview()
            make.leading.equalTo(coin.snp.trailing).offset(1)
        }
        
        let unitLabel = UILabel()
        unitLabel.text = "/\(skill.unit)"
        unitLabel.font = .body_s
        unitLabel.textColor = .text_4
        priceView.addSubview(unitLabel)
        unitLabel.snp.makeConstraints { make in
            make.centerY.equalToSuperview()
            make.leading.equalTo(priceLabel.snp.trailing).offset(1)
            make.trailing.lessThanOrEqualToSuperview()
        }
        
        let statusView = UIView()
        container.addSubview(statusView)
        statusView.snp.makeConstraints { make in
            make.horizontalEdges.equalToSuperview()
            make.top.equalTo(infoView.snp.bottom).offset(2)
            make.bottom.equalToSuperview().offset(-8)
            make.height.equalTo(25)
        }
        
        let titleLabel = UILabel()
        titleLabel.text = .init(key: "A00169")
        titleLabel.font = .heading_h5
        titleLabel.textColor = .text_5
        statusView.addSubview(titleLabel)
        titleLabel.snp.makeConstraints { make in
            make.leading.equalToSuperview().offset(18)
            make.centerY.equalToSuperview()
        }
        
        let scaleX: CGFloat = 40.0 / 51.0
        let scaleY: CGFloat = 24.5 / 31.0
        let switchView = UISwitch()
        switchView.isOn = skill.open
        switchView.onTintColor = .primary_5
        switchView.transform = CGAffineTransform(scaleX: scaleX, y: scaleY)
        switchView.addAction(UIAction(handler: { [weak switchView] _ in
            guard let switchView else { return }
            showLoading()
            LNGameMateManager.shared.enableSkill(skillId: skill.id, open: switchView.isOn)
            { [weak switchView] success in
                dismissLoading()
                guard let switchView else { return }
                if !success {
                    switchView.isOn.toggle()
                }
            }
        }), for: .valueChanged)
        statusView.addSubview(switchView)
        switchView.snp.makeConstraints { make in
            make.centerY.equalToSuperview()
            make.trailing.equalToSuperview().offset(-12)
        }
        
        return container
    }
}
