//
//  KeyboardTeachView.swift
//  AiKeyboard
//
//  Created by Destiny on 2025/4/24.
//

import UIKit

protocol KeyboardTeachViewDelegate: NSObjectProtocol {
    
    func teachCollectionViewDidSelectItem(characterId: String, content: String, complete: @escaping (([String]) -> ()))
    
    func teachTableViewDidSelectItem(content: String)
}

class KeyboardTeachView: KeyboardBaseView {
    
    struct UX {
        static let cellWidth = (KeyboardConst.kb_kScreenW - 96.0) / 3.0
        static let cellHeight = 46.0
        static let resultCellHeight = "单行文字".heightAccording(width: KeyboardConst.kb_kScreenW - 105, font: .systemFont(ofSize: 12), lineSpacing: 5) + 16
    }
    
    weak var teachDelegate: KeyboardTeachViewDelegate?
    
    // 是否在加载
    var isResultLoading: Bool = true
    
    var selectCharacter: CharacterModel?
    
    var characterList: [CharacterModel]? {
        didSet {
            self.collectionView.reloadData()
        }
    }
    
    var resultList: [String]? {
        didSet {
            self.tableView.reloadData()
        }
    }
    
    lazy var collectionView: UICollectionView = {
            
        let layout = UICollectionViewFlowLayout()
        layout.minimumLineSpacing = 0
        layout.scrollDirection = .vertical
        
        let collectionView = UICollectionView(frame: .zero, collectionViewLayout: layout)
        collectionView.backgroundColor = .clear
        
        collectionView.dataSource = self
        collectionView.delegate = self
        
        collectionView.showsVerticalScrollIndicator = false
        collectionView.bounces = false
        
        collectionView.register(KeyboardCharacterCell.self, forCellWithReuseIdentifier: KeyboardCharacterCell.reuseIdentifier())
        
        return collectionView
    }()
    
    lazy var resultView: UIView = {
       
        let view = UIView()
        view.isHidden = true
        return view
    }()
        
    lazy var backBtn: UIButton = {
        
        let btn = UIButton()
        btn.setImage(UIImage(named: "keyboard_back_btn"), for: .normal)
        btn.layer.shadowOffset = CGSize(width: 0, height: 0)
        btn.layer.shadowColor = UIColor.hexStringColor(hexString: "#000000", alpha: 0.12).cgColor
        btn.layer.shadowRadius = 6.1
        btn.addTarget(self, action: #selector(backBtnClickAction), for: .touchUpInside)
        return btn
    }()
    
    lazy var regenerateBtn: UIButton = {
        
        let btn = UIButton()
        btn.backgroundColor = .white
        btn.layer.cornerRadius = 12
        btn.layer.shadowOffset = CGSize(width: 0, height: 0)
        btn.layer.shadowColor = UIColor.hexStringColor(hexString: "#000000", alpha: 0.12).cgColor
        btn.layer.shadowRadius = 6.1
        btn.setTitle("重新生成", for: .normal)
        btn.setTitleColor(.hexStringColor(hexString: "#000000", alpha: 0.8), for: .normal)
        btn.titleLabel?.font = .systemFont(ofSize: 12)
        btn.addTarget(self, action: #selector(regenerateBtnClickAction), for: .touchUpInside)
        return btn
    }()
    
    lazy var tableView: UITableView = {
        
        let tableView = UITableView(frame: .zero, style: .grouped)
        tableView.backgroundColor = .clear
        tableView.separatorStyle = .none
        tableView.showsVerticalScrollIndicator = false
        tableView.delegate = self
        tableView.dataSource = self
       
        if #available(iOS 11, *) {
            tableView.estimatedRowHeight = 0
            tableView.estimatedSectionFooterHeight = 0
            tableView.estimatedSectionHeaderHeight = 0
            tableView.contentInsetAdjustmentBehavior = .never
        }
        
        tableView.isUserInteractionEnabled = true
        tableView.register(KeyboardTeachDialogueCell.self, forCellReuseIdentifier: KeyboardTeachDialogueCell.reuseIdentifier())
        
        return tableView
    }()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

extension KeyboardTeachView {
    
    // 返回按钮点击
    @objc func backBtnClickAction() {
        
        self.isResultLoading = true
        self.collectionView.isHidden = false
        self.resultView.isHidden = true
        self.dialogueClearBtnAction()
    }
    
    // 重新生成按钮点击
    @objc func regenerateBtnClickAction() {
        
        self.isResultLoading = true
        self.tableView.reloadData()
        
        if let selectCharacter = self.selectCharacter, let characterId = selectCharacter.id {
            
            teachDelegate?.teachCollectionViewDidSelectItem(characterId: characterId, content: self.dialogueLabel.text ?? "") { list in
                self.isResultLoading = false
                self.resultList = list
            }
        }
    }
}

extension KeyboardTeachView: UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return (self.characterList?.count ?? 0) + 1
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        
        if indexPath.row == self.characterList?.count {
            
            let cell = collectionView.dequeueReusableCell(withReuseIdentifier: KeyboardCharacterCell.reuseIdentifier(), for: indexPath) as! KeyboardCharacterCell
            cell.titleLabel.isHidden = true
            cell.addBtn.isHidden = false
            return cell
        } else {
            
            let cell = collectionView.dequeueReusableCell(withReuseIdentifier: KeyboardCharacterCell.reuseIdentifier(), for: indexPath) as! KeyboardCharacterCell
            if let model = self.characterList?[indexPath.row] {
                cell.config(model: model)
            }
            return cell
        }
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        
        if self.dialogueLabel.text?.count == 0 {
            self.toast(text: "请先粘贴文字")
            return
        }
        
        if let model = self.characterList?[indexPath.row], let characterId = model.id {
            
            // 清空回答列表
            self.resultList?.removeAll()
            self.collectionView.isHidden = true
            self.resultView.isHidden = false
            self.tableView.reloadData()
            
            self.selectCharacter = model
            teachDelegate?.teachCollectionViewDidSelectItem(characterId: characterId, content: self.dialogueLabel.text ?? "") { list in
                self.isResultLoading = false
                self.resultList = list
            }
        }
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        
        return CGSize(width: UX.cellWidth, height: UX.cellHeight)
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
        return 6
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
        return 6
    }
}

extension KeyboardTeachView: UITableViewDelegate, UITableViewDataSource {
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 1
    }
    
    func numberOfSections(in tableView: UITableView) -> Int {
        
        return isResultLoading ? 4 : (resultList?.count ?? 0) + 1
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    
        let cell = tableView.dequeueReusableCell(withIdentifier: KeyboardTeachDialogueCell.reuseIdentifier(), for: indexPath) as! KeyboardTeachDialogueCell
        cell.backgroundColor = .clear
        cell.selectionStyle = .none
        if indexPath.section == 0 {
            cell.isHidden = true
        } else {
            if let resultList = self.resultList, resultList.count > 0 && !isResultLoading {
                let content = resultList[indexPath.section - 1]
                cell.config(content: content)
            }
             
            cell.setLoading(play: isResultLoading)
        }
        return cell
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        
        if let resultList = self.resultList, resultList.count > 0 && !isResultLoading {
            
            let content = resultList[indexPath.section - 1]
            teachDelegate?.teachTableViewDidSelectItem(content: content)
            self.backBtnClickAction()
        }
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        
        if isResultLoading {
            return UX.resultCellHeight
        }
        
        if indexPath.section != 0 {
            if let resultList = self.resultList, resultList.count > 0 {
                let content = resultList[indexPath.section - 1]
                let height = content.heightAccording(width: KeyboardConst.kb_kScreenW - 105, font: .systemFont(ofSize: 12), lineSpacing: 5) + 16
                return height
            }
        }
        
        return UX.resultCellHeight
    }

    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 8
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let view = UIView(frame: CGRect(x: 0, y: 0, width: KeyboardConst.kb_kScreenW - 84, height: 8))
        return view
    }
    
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return 0.001
    }
    
    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        return nil
    }
    
}

extension KeyboardTeachView {
    
    func setupUI() {
        
        let attr = NSMutableAttributedString()
        let copyIcon = NSTextAttachment(image: UIImage(named: "keyboard_copy_icon")!)
        copyIcon.bounds = CGRect(x: -4, y: -4, width: 18, height: 18)
        let copyAttr = NSAttributedString(attachment: copyIcon)
        attr.append(copyAttr)
        
        let titleText = NSMutableAttributedString(string: "输入/粘贴你想说的话，润色升华")
        titleText.addAttributes([.font: UIFont.systemFont(ofSize: 14, weight: .medium), .foregroundColor: UIColor.hexStringColor(hexString: "#996DFF")], range: NSRange(location: 0, length: titleText.length))
        attr.append(titleText)

        self.dialogueTitleLabel.attributedText = attr
        
        self.addSubview(self.collectionView)
        collectionView.snp.makeConstraints { make in
            make.left.equalTo(10)
            make.right.equalTo(deleteBtn.snp.left).offset(-6)
            make.top.equalTo(dialogueView.snp.bottom).offset(6)
            make.bottom.equalTo(self.sendBtn.snp.bottom).offset(3)
        }
        
        self.addSubview(resultView)
        resultView.snp.makeConstraints { make in
            make.left.equalTo(10)
            make.right.equalTo(deleteBtn.snp.left).offset(-6)
            make.top.equalTo(dialogueView.snp.bottom).offset(12)
            make.bottom.equalTo(0)
        }
        
        resultView.addSubview(tableView)
        tableView.snp.makeConstraints { make in
            make.top.left.bottom.right.equalTo(0)
        }
        
        resultView.addSubview(backBtn)
        backBtn.snp.makeConstraints { make in
            make.size.equalTo(CGSize(width: 32, height: 32))
            make.left.equalTo(0)
            make.top.equalTo(0)
        }
        
        resultView.addSubview(regenerateBtn)
        regenerateBtn.snp.makeConstraints { make in
            make.size.equalTo(CGSize(width: 74, height: 32))
            make.top.right.equalTo(0)
        }
    }
}
