//
//  ChatSettingSwipeView.swift
//  Visual_Novel_iOS
//
//  Created by mh on 2025/10/24.
//

import UIKit
import SnapKit

class ChatSettingSwipeView: CLContainer {
    
    var closeAction: (()->Void)?
    
    var sectionTitle: [String] = ["Switch Model", "Sound", "Maximum number of response tokens Maximum number of response tokens", "Appearance", "Background", "Historical Archives"]
    var rows: [[RowModel]] = []
    
    // 展开状态管理：section -> rowIndex -> isExpanded
    private var expandedStates: [Int: [Int: Bool]] = [:]
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        // 初始化rows数据，包含子项（至少10条数据）
        let modelRow = ImageRow(icon: "role_exchange_mode", title: "XL-0826-32K", showAvatar: false, showArrow: true, showSwitch: false, subItems: [
            ImageRow(icon: "role_exchange_mode", title: "Sub Item 1", showAvatar: false, showArrow: false, showSwitch: false),
            ImageRow(icon: "role_exchange_mode", title: "Sub Item 2", showAvatar: false, showArrow: false, showSwitch: false),
            ImageRow(icon: "role_exchange_mode", title: "Sub Item 3", showAvatar: false, showArrow: false, showSwitch: false),
            ImageRow(icon: "role_exchange_mode", title: "Sub Item 4", showAvatar: false, showArrow: false, showSwitch: false),
            ImageRow(icon: "role_exchange_mode", title: "Sub Item 5", showAvatar: false, showArrow: false, showSwitch: false),
//            ImageRow(icon: "role_exchange_mode", title: "Sub Item 6", showAvatar: false, showArrow: false, showSwitch: false),
//            ImageRow(icon: "role_exchange_mode", title: "Sub Item 7", showAvatar: false, showArrow: false, showSwitch: false),
//            ImageRow(icon: "role_exchange_mode", title: "Sub Item 8", showAvatar: false, showArrow: false, showSwitch: false),
//            ImageRow(icon: "role_exchange_mode", title: "Sub Item 9", showAvatar: false, showArrow: false, showSwitch: false),
//            ImageRow(icon: "role_exchange_mode", title: "Sub Item 10", showAvatar: false, showArrow: false, showSwitch: false)
        ])
        
        let buttleRow = ImageRow(icon: "role_chat_buttle", title: "Chat buttle", showAvatar: false, showArrow: true, showSwitch: false, buttleItems: [
            ChatButtleRow(id: "1", name: "Default", price: nil, kind: .default, status: .selected),
            ChatButtleRow(id: "2", name: "Name1", price: nil, kind: .vip, status: .available),
            ChatButtleRow(id: "3", name: "Name2", price: nil, kind: .premium, status: .available),
            // Row 2
            ChatButtleRow(id: "4", name: "Name3", price: nil, kind: .vip, status: .locked),
            ChatButtleRow(id: "5", name: "Name4", price: nil, kind: .vip, status: .locked),
            ChatButtleRow(id: "6", name: "Name5", price: nil, kind: .vip, status: .locked),
            // Row 3
            ChatButtleRow(id: "7", name: "Name6", price: 20, kind: .premium, status: .locked),
            ChatButtleRow(id: "8", name: "Name7", price: 20, kind: .premium, status: .locked),
            ChatButtleRow(id: "9", name: "Name8", price: 20, kind: .premium, status: .gettable),
            // Row 4
//            ChatButtleRow(id: "10", name: "Name9", price: 20, kind: .premium, status: .locked),
//            ChatButtleRow(id: "11", name: "Name10", price: 20, kind: .premium, status: .locked),
//            ChatButtleRow(id: "12", name: "Name11", price: 20, kind: .premium, status: .locked)
        ])
        
        rows = [
            [modelRow, ImageRow(icon: "role_text_mode", title: "Short Text Mode", showAvatar: false, showArrow: false, showSwitch: true)],
            [ImageRow(icon: "role_voice", title: "Voice actor", showAvatar: true, showArrow: true, showSwitch: false), ImageRow(icon: "role_talk", title: "Play dialogue only", showAvatar: false, showArrow: false, showSwitch: true)],
            [TokenRow(count: "2500")],
            [FontRow(count: "20", icon: "role_font", title: "Font size"), ImageRow(icon: "role_chat_mode", title: "Chat Mode", showAvatar: false, showArrow: true, showSwitch: false), buttleRow],
            [BackgroundRow(count: 50)],
            [HistoryRow(time: "", icon: "", title: "", itemCount: 30)]
        ]
        
        setupViews()
    }

    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    lazy var titleLab: UILabel = {
        let lab = UILabel()
        lab.text = "Setting"
        lab.font = UIFont.boldSystemFont(ofSize: 18)
        lab.textColor = UIColor(hex: "#000000")
        return lab
    }()
    
    lazy var closeBtn: UIButton = {
        let btn = UIButton(type: .custom)
        btn.setImage(UIImage(named: "role_chat_close"), for: .normal)
        btn.addTarget(self, action: #selector(closeBtnTap), for: .touchUpInside)
        return btn
    }()
    
    lazy var newChatBtn: UIButton = {
        let btn = UIButton(type: .custom)
        btn.setBackgroundImage(UIImage(named: "role_new_chat"), for: .normal)
        btn.addTarget(self, action: #selector(newChatBtnTap), for: .touchUpInside)
        btn.setTitle("+ Start New Chat", for: .normal)
        btn.titleLabel?.font = UIFont.boldSystemFont(ofSize: 17)
        btn.imageView?.contentMode = .scaleToFill
        return btn
    }()
    
    lazy var tableView: UITableView = {
        let tableView = UITableView(frame: .zero, style: .grouped)
        tableView.separatorStyle = .none
        tableView.delegate = self
        tableView.dataSource = self
        tableView.estimatedRowHeight = 72
        tableView.rowHeight = UITableView.automaticDimension
        tableView.backgroundColor = .clear
        tableView.showsVerticalScrollIndicator = false
        tableView.tableFooterView = UIView()
        tableView.register(ChatSwipeCell.self, forCellReuseIdentifier: "ChatSwipeCell")
        tableView.register(ChatResponseTokenCell.self, forCellReuseIdentifier: "ChatResponseTokenCell")
        tableView.register(ChatFontCell.self, forCellReuseIdentifier: "ChatFontCell")
        tableView.register(ChatBackgroundCell.self, forCellReuseIdentifier: "ChatBackgroundCell")
        tableView.register(ChatHistoryCell.self, forCellReuseIdentifier: "ChatHistoryCell")
        tableView.register(SubItemsContainerCell.self, forCellReuseIdentifier: "SubItemsContainerCell")
        tableView.register(ChatButtleCollectionCell.self, forCellReuseIdentifier: "ChatButtleCollectionCell")
        tableView.contentInset = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
        return tableView
    }()
    
    func setupViews() {
        
        navigationView = NavigationView()
        navigationView?.backButton.isHidden = false
        navigationView?.isHidden = true
        addSubview(navigationView ?? UIView())
        
        addSubview(titleLab)
        addSubview(closeBtn)
        addSubview(tableView)
        addSubview(newChatBtn)
        
        navigationView?.snp.makeConstraints { make in
            make.top.equalToSuperview()
            make.left.equalToSuperview()
            make.right.equalToSuperview()
            make.height.equalTo(UIWindow.navBarTotalHeight)
        }
        
        titleLab.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(20)
            if self.navigationView != nil {
                make.centerY.equalTo(self.navigationView!.titleLabel.snp.centerY)
            } else {
                make.top.equalToSuperview().offset(UIDevice().statusBarHeight + 13.0)
            }

            make.right.equalTo(closeBtn.snp.left).offset(-10)
        }
        
        closeBtn.snp.makeConstraints { make in
            make.centerY.equalTo(titleLab.snp.centerY)
            make.right.equalToSuperview().inset(20)
            make.width.height.equalTo(25)
        }
        
        
        newChatBtn.snp.makeConstraints { make in
            make.left.right.equalToSuperview().inset(20)
            make.height.equalTo(50)
            make.bottom.equalToSuperview().inset(UIDevice().safeBottom + 5.0)
        }
        
        tableView.snp.makeConstraints { make in
            make.left.right.equalToSuperview()
            make.top.equalTo(closeBtn.snp.bottom).offset(10)
            make.bottom.equalTo(newChatBtn.snp.top).offset(-5)
        }
        
        // 设置tableView的contentInset，让内容可以滑动到最顶部
        tableView.contentInsetAdjustmentBehavior = .never
        tableView.automaticallyAdjustsScrollIndicatorInsets = false

    }
}

extension ChatSettingSwipeView {
    
    @objc func closeBtnTap() {
        self.closeAction?()
    }
    
    @objc func newChatBtnTap() {
        
    }
}

extension ChatSettingSwipeView: UITableViewDelegate, UITableViewDataSource {
    
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        // 确保tableView内容可以滑动到最顶部
        // 不需要额外的contentInset调整
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        guard let imageRow = rows[indexPath.section][indexPath.row] as? ImageRow,
              imageRow.showArrow else { return }
        // 统一处理：优先判断 Chat buttle（使用集合视图）
        if imageRow.title == "Chat buttle", let subItems = imageRow.buttleItems, !subItems.isEmpty {
            tableView.deselectRow(at: indexPath, animated: true)
            let isExpanded = expandedStates[indexPath.section]?[indexPath.row] ?? false
            expandedStates[indexPath.section, default: [:]][indexPath.row] = !isExpanded
            if !isExpanded {
                // 展开：插入 ChatButtleRow
                let subItemsRow = SubButtleRow(subItems: subItems)
                rows[indexPath.section].insert(subItemsRow, at: indexPath.row + 1)

                let insertIndexPath = IndexPath(row: indexPath.row + 1, section: indexPath.section)
                tableView.insertRows(at: [insertIndexPath], with: .fade)
                if let cell = tableView.cellForRow(at: indexPath) as? ChatSwipeCell {
                    cell.updateArrowState(isExpanded: true)
                }
            } else {
                // 折叠
                if indexPath.row + 1 < rows[indexPath.section].count,
                   rows[indexPath.section][indexPath.row + 1] is SubButtleRow {
                    rows[indexPath.section].remove(at: indexPath.row + 1)

                    let deleteIndexPath = IndexPath(row: indexPath.row + 1, section: indexPath.section)
                    tableView.deleteRows(at: [deleteIndexPath], with: .fade)
                    if let cell = tableView.cellForRow(at: indexPath) as? ChatSwipeCell {
                        cell.updateArrowState(isExpanded: false)
                    }
                }
            }
            return
        }
        
        if let subItems = imageRow.subItems, !subItems.isEmpty {
            // 切换展开状态
            let isExpanded = expandedStates[indexPath.section]?[indexPath.row] ?? false
            expandedStates[indexPath.section, default: [:]][indexPath.row] = !isExpanded
            
            // 插入或删除SubItemsContainerCell
            if !isExpanded {
                // 展开：插入SubItemsContainerCell
                let subItemsRow = SubItemsRow(subItems: subItems)
                rows[indexPath.section].insert(subItemsRow, at: indexPath.row + 1)
                
                let insertIndexPath = IndexPath(row: indexPath.row + 1, section: indexPath.section)
                tableView.beginUpdates()
                tableView.insertRows(at: [insertIndexPath], with: .fade)
                tableView.endUpdates()
                
                // 更新箭头状态
                tableView.reloadRows(at: [indexPath], with: .none)
            } else {
                // 折叠：删除SubItemsContainerCell
                if indexPath.row + 1 < rows[indexPath.section].count,
                   rows[indexPath.section][indexPath.row + 1] is SubItemsRow {
                    rows[indexPath.section].remove(at: indexPath.row + 1)
                    
                    let deleteIndexPath = IndexPath(row: indexPath.row + 1, section: indexPath.section)
                    tableView.beginUpdates()
                    tableView.deleteRows(at: [deleteIndexPath], with: .fade)
                    tableView.endUpdates()
                    
                    // 更新箭头状态
                    tableView.reloadRows(at: [indexPath], with: .none)
                }
            }
        }
    }
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return rows.count
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return rows[section].count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let row = rows[indexPath.section][indexPath.row]
        
        // 处理ChatButtleRow
        if let buttleRow = row as? SubButtleRow {
            let cell = tableView.dequeueReusableCell(withIdentifier: "ChatButtleCollectionCell", for: indexPath) as! ChatButtleCollectionCell
            cell.selectionStyle = .none
            cell.configure(with: buttleRow)
            return cell
        }
        
        // 处理SubItemsRow
        if let subItemsRow = row as? SubItemsRow {
            let cell = tableView.dequeueReusableCell(withIdentifier: "SubItemsContainerCell", for: indexPath) as! SubItemsContainerCell
            cell.selectionStyle = .none
            cell.configure(with: subItemsRow)
            return cell
        }
        
        let cell = tableView.dequeueReusableCell(withIdentifier: row.cellReuseID, for: indexPath)
        cell.selectionStyle = .none
        
        // 如果是ImageRow，设置展开状态
        if var imageRow = row as? ImageRow {
            imageRow.isExpanded = expandedStates[indexPath.section]?[indexPath.row] ?? false
            (cell as? CellConfigurable)?.configure(with: imageRow)
        } else {
            (cell as? CellConfigurable)?.configure(with: row)
        }
        
        return cell
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let header = UIView()
        
        let lab = UILabel()
        lab.text = sectionTitle[section]
        lab.textColor = UIColor(hex: "#333333")
        lab.font = UIFont.boldSystemFont(ofSize: 16)
        lab.numberOfLines = 0
        header.addSubview(lab)
        lab.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(20)
            make.right.equalToSuperview()
            make.top.equalToSuperview().inset(5)
            make.bottom.equalToSuperview()
        }
        
        return header
    }
    
    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        return UIView()
    }
    
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return CGFLOAT_MIN
    }
}
