//
//  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", "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, voiceActorItems: createVoiceActorItems()), 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, chatModeItems: createChatModeItems()), 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.register(ChatModeContainerCell.self, forCellReuseIdentifier: "ChatModeContainerCell")
        tableView.register(VoiceActorContainerCell.self, forCellReuseIdentifier: "VoiceActorContainerCell")
        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 }
        
        tableView.deselectRow(at: indexPath, animated: true)
        
        // 处理 Voice actor 展开
        if imageRow.title == "Voice actor", let voiceActorItems = imageRow.voiceActorItems, !voiceActorItems.isEmpty {
            let isExpanded = expandedStates[indexPath.section]?[indexPath.row] ?? false
            expandedStates[indexPath.section, default: [:]][indexPath.row] = !isExpanded
            
            if !isExpanded {
                // 展开：插入 VoiceActorRow
                let actorRow = VoiceActorRow(items: voiceActorItems)
                rows[indexPath.section].insert(actorRow, at: indexPath.row + 1)
                let insertIndexPath = IndexPath(row: indexPath.row + 1, section: indexPath.section)
                
                tableView.performBatchUpdates({
                    tableView.insertRows(at: [insertIndexPath], with: .fade)
                    tableView.reloadRows(at: [indexPath], with: .none)
                }, completion: nil)
            } else {
                // 折叠
                if indexPath.row + 1 < rows[indexPath.section].count,
                   rows[indexPath.section][indexPath.row + 1] is VoiceActorRow {
                    rows[indexPath.section].remove(at: indexPath.row + 1)
                    let deleteIndexPath = IndexPath(row: indexPath.row + 1, section: indexPath.section)
                    
                    tableView.performBatchUpdates({
                        tableView.deleteRows(at: [deleteIndexPath], with: .fade)
                        tableView.reloadRows(at: [indexPath], with: .none)
                    }, completion: nil)
                }
            }
            return
        }
        
        // 处理 Chat Mode 展开
        if imageRow.title == "Chat Mode", let chatModeItems = imageRow.chatModeItems, !chatModeItems.isEmpty {
            let isExpanded = expandedStates[indexPath.section]?[indexPath.row] ?? false
            expandedStates[indexPath.section, default: [:]][indexPath.row] = !isExpanded
            
            if !isExpanded {
                // 展开：先更新箭头状态（数据源还未改变）
                
                // 然后更新数据源并插入新行
                let modeRow = ChatModeRow(items: chatModeItems)
                rows[indexPath.section].insert(modeRow, at: indexPath.row + 1)
                let insertIndexPath = IndexPath(row: indexPath.row + 1, section: indexPath.section)
                
                tableView.performBatchUpdates({
                    tableView.insertRows(at: [insertIndexPath], with: .fade)
                    tableView.reloadRows(at: [indexPath], with: .none)
                }, completion: nil)
            } else {
                // 折叠：先更新箭头状态
                
                // 然后删除数据源和行
                if indexPath.row + 1 < rows[indexPath.section].count,
                   rows[indexPath.section][indexPath.row + 1] is ChatModeRow {
                    rows[indexPath.section].remove(at: indexPath.row + 1)
                    let deleteIndexPath = IndexPath(row: indexPath.row + 1, section: indexPath.section)
                    
                    tableView.performBatchUpdates({
                        tableView.deleteRows(at: [deleteIndexPath], with: .fade)
                        tableView.reloadRows(at: [indexPath], with: .none)

                    }, completion: nil)
                }
            }
            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]
        
        // 处理VoiceActorRow
        if let actorRow = row as? VoiceActorRow {
            let cell = tableView.dequeueReusableCell(withIdentifier: "VoiceActorContainerCell", for: indexPath) as! VoiceActorContainerCell
            cell.selectionStyle = .none
            
            // 设置选中回调，更新父cell头像
            cell.selectedItemChanged = { [weak self] item in
                self?.updateVoiceActorAvatar(item, at: indexPath.section, rowIndex: indexPath.row - 1)
            }
            
            cell.configure(with: actorRow)
            return cell
        }
        
        // 处理ChatModeRow
        if let modeRow = row as? ChatModeRow {
            let cell = tableView.dequeueReusableCell(withIdentifier: "ChatModeContainerCell", for: indexPath) as! ChatModeContainerCell
            cell.selectionStyle = .none
            cell.configure(with: modeRow)
            return cell
        }
        
        // 处理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
    }
    
    // MARK: - 创建ChatMode示例数据
    private func createChatModeItems() -> [ChatModeItem] {
        return [
            ChatModeItem(id: "1", title: "Dialogue Mode", subtitle: "Previous-generation large model", isVip: false, isSelected: true),
            ChatModeItem(id: "2", title: "Immersive Mode", subtitle: "Previous-generation large model", isVip: true, isSelected: false)
        ]
    }
    
    // MARK: - 创建VoiceActor示例数据
    private func createVoiceActorItems() -> [VoiceActorItem] {
        return [
            VoiceActorItem(id: "1", name: "Name 1", description: "Anime-Style Girl", avatarImage: "voice_actor_1", gender: "female", isSelected: true),
            VoiceActorItem(id: "2", name: "Name 2", description: "Anime-Style Girl", avatarImage: "voice_actor_1", gender: "female", isSelected: false),
            VoiceActorItem(id: "3", name: "Name 3", description: "Anime-Style Boy", avatarImage: "voice_actor_2", gender: "male", isSelected: false),
            VoiceActorItem(id: "4", name: "Name 4", description: "Anime-Style Girl", avatarImage: "voice_actor_1", gender: "female", isSelected: false),
            VoiceActorItem(id: "5", name: "Name 5", description: "Anime-Style Girl", avatarImage: "voice_actor_1", gender: "female", isSelected: false),
            VoiceActorItem(id: "6", name: "Name 6", description: "Anime-Style Boy", avatarImage: "voice_actor_2", gender: "male", isSelected: false),
            VoiceActorItem(id: "7", name: "Name 7", description: "Anime-Style Girl", avatarImage: "voice_actor_1", gender: "female", isSelected: false),
            VoiceActorItem(id: "8", name: "Name 8", description: "Anime-Style Boy", avatarImage: "voice_actor_2", gender: "male", isSelected: false),
        ]
    }
    
    // MARK: - 更新Voice Actor头像
    private func updateVoiceActorAvatar(_ item: VoiceActorItem, at section: Int, rowIndex: Int) {
        guard section >= 0 && section < rows.count,
              rowIndex >= 0 && rowIndex < rows[section].count else { return }
        
        // 更新数据源中的选中状态
        if var imageRow = rows[section][rowIndex] as? ImageRow,
           var voiceActorItems = imageRow.voiceActorItems {
            // 更新所有items的选中状态
            voiceActorItems = voiceActorItems.map { var i = $0; i.isSelected = (i.id == item.id); return i }
            
            // 由于 ImageRow 是 struct，需要重新创建
            let updatedRow = ImageRow(
                icon: imageRow.icon,
                title: imageRow.title,
                showAvatar: imageRow.showAvatar,
                showArrow: imageRow.showArrow,
                showSwitch: imageRow.showSwitch,
                subItems: imageRow.subItems,
                buttleItems: imageRow.buttleItems,
                chatModeItems: imageRow.chatModeItems,
                voiceActorItems: voiceActorItems
            )
            rows[section][rowIndex] = updatedRow
        }
        
        // 刷新父cell以更新头像
        let parentIndexPath = IndexPath(row: rowIndex, section: section)
        if let cell = tableView.cellForRow(at: parentIndexPath) as? ChatSwipeCell {
            // 更新avatarView的图像
            cell.avatarView.image = UIImage(named: item.avatarImage)
        }
    }
}
