//
//  ContactAllView.swift
//  PhoneManager
//
//  Created by 赵前 on 2025/4/19.
//

import Foundation
import SnapKit
import UIKit
class ContactAllView : UIView {
    
    static let CONTACT_ALL = "contact_all"
    
    private var bottomConstraint: Constraint?
    
    var dataSourceModel : [ContactModel] = []
    
    private var tabBottomConstraint: Constraint?
    
    var dataClearCallBack : ()->Void = {}
    
    
    /// 分组后的联系人
    private var sectionedContacts: [String: [ContactModel]] = [:]
    
    /// 联系人首字母数组
    private var sectionTitles: [String] = []
    
    /// 选择的联系人
    private var selectedContacts: [ContactModel] = []
    
    
    var customIndexView: UIStackView!
    
    var selectedIndex = 0
    
    lazy var titleLabel: UILabel = {
        let label = UILabel()
        label.text = "All contacts"
        label.font = UIFont.systemFont(ofSize: 20, weight: .bold)
        label.textColor = UIColor(red: 0.2, green: 0.2, blue: 0.2, alpha: 1)
        label.textAlignment = .left
        return label
    }()
    
    lazy var subTitleLabel: UILabel = {
        let label = UILabel()
        label.text = "\(self.dataSourceModel.count) Contacts"
        label.font = UIFont.systemFont(ofSize: 14, weight: .regular)
        label.textColor = UIColor(red: 0.2, green: 0.2, blue: 0.2, alpha: 1)
        label.textAlignment = .left
        return label
    }()
    
    lazy var tableView : UITableView = {
        let tableView = UITableView(frame: CGRect(x: 0, y: 0, width: 0, height: 12), style: UITableView.Style.grouped)
        tableView.dataSource = self
        tableView.delegate = self
        tableView.register(CustomContactAllViewTableViewCell.self, forCellReuseIdentifier: "CustomContactAllViewTableViewCell")
        tableView.separatorStyle = .none
        tableView.backgroundColor = .clear
        tableView.showsVerticalScrollIndicator = false
        if #available(iOS 15.0, *) {
            tableView.sectionHeaderTopPadding = 0
        }
        return tableView
    }()
    
    lazy var deleteButton : DeleteButtonView = {
        let deleteButton = DeleteButtonView()
        return deleteButton
    }()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        self.addSubview(self.titleLabel)
        self.addSubview(self.subTitleLabel)
        self.addSubview(self.tableView)
        self.addSubview(self.deleteButton)
        self.backgroundColor = .clear
        self.titleLabel.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(15 * RScreenW())
            make.top.equalToSuperview().offset(14 * RScreenH())
            make.width.equalTo(345 * RScreenW())
            make.height.equalTo(32)
        }
        
        self.subTitleLabel.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(15 * RScreenW())
            make.top.equalTo(self.titleLabel.snp.bottom).offset(2 * RScreenH())
            make.width.equalTo(345 * RScreenW())
            make.height.equalTo(20)
        }
        
        self.tableView.snp.makeConstraints { make in
            make.top.equalTo(self.subTitleLabel.snp.bottom).offset(16 * RScreenH())
            make.left.equalToSuperview().offset(15 * RScreenW())
            make.right.equalToSuperview().offset(-15 * RScreenW())
            self.tabBottomConstraint = make.bottom.equalToSuperview().offset(-safeHeight).constraint
        }
        self.deleteButton.snp.makeConstraints { make in
            make.left.right.equalToSuperview()
            self.bottomConstraint = make.bottom.equalToSuperview().offset(68).constraint
            make.height.equalTo(68)
        }
        
        // 排序
        self.sortContacts()
        
        self.deleteButton.submitCallBack = {
            self.alertWhenDeleteSomeOne()
        }
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

extension ContactAllView : UITableViewDataSource,UITableViewDelegate {
    
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return sectionTitles.count
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        let sectionTitle = sectionTitles[section]
        return sectionedContacts[sectionTitle]?.count ?? 0
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let cell = tableView.cellForRow(at: indexPath) as! CustomContactAllViewTableViewCell
        cell.selectContact(cell.selectButton)
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "CustomContactAllViewTableViewCell", for: indexPath) as! CustomContactAllViewTableViewCell
        let sectionTitle = sectionTitles[indexPath.section]
        let contact = sectionedContacts[sectionTitle]?[indexPath.row]
        cell.model = contact
        cell.nameLabel.text = contact?.fullName.count ?? 0 > 0 ? contact?.fullName : "Untitled contact person"
        if self.selectedContacts.contains(where: { $0.identifier == contact!.identifier }) {
            cell.selectButton.isSelected = true
        }else {
            cell.selectButton.isSelected = false
        }
        cell.buttonSelectCallBack = {[weak self] model,selected in
            guard let self else {return}
            if selected {
                self.selectedContacts.append(model)
            }else{
                self.selectedContacts.removeAll(where: { $0.identifier == model.identifier })
            }
            self.vibrate()
            DispatchQueue.main.async {
                // 判断button是否显示
                if self.selectedContacts.count > 0 {
                    // 设置button的title
                    self.deleteButton.deleteButton.setTitle("Delete \(self.selectedContacts.count) Contact", for: .normal)
                    UIView.animate(withDuration: 0.1) {
                        // 更新约束
                        self.bottomConstraint?.update(offset: -safeHeight)
                        self.tabBottomConstraint?.update(offset: -safeHeight - 68)
                        self.layoutIfNeeded()
                    }
                }else{
                    UIView.animate(withDuration: 0.1) {
                        // 更新约束
                        self.bottomConstraint?.update(offset: 68)
                        self.tabBottomConstraint?.update(offset: -safeHeight)
                        self.layoutIfNeeded()
                    }
                }
            }
            
        }
        
        return cell
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 77 + 8 * RScreenH()
    }
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let label = UILabel(frame: CGRect(x: 0 , y: 0, width: 345, height: 20))
        label.text = sectionTitles[section]
        label.textAlignment = .left
        label.font = UIFont.systemFont(ofSize: 14, weight: .bold)
        label.textColor = UIColor(red: 0.7, green: 0.7, blue: 0.7, alpha: 1)
        return label
    }
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 20
    }
    func setupCustomIndexView() {
        customIndexView = nil
        customIndexView = UIStackView()
        customIndexView.axis = .vertical
        customIndexView.alignment = .center
        customIndexView.distribution = .equalSpacing
        customIndexView.translatesAutoresizingMaskIntoConstraints = false
        self.addSubview(customIndexView)
        
        self.customIndexView.snp.makeConstraints { make in
            make.left.equalTo(self.tableView.snp.right).offset(0)
            make.centerY.equalTo(self.snp.centerY)
            make.width.equalTo(15 * RScreenW())
            make.height.equalTo(self.sectionTitles.count * (14 + 2))
        }
        
        for (index, section) in sectionTitles.enumerated() {
            let label = UILabel()
            label.text = section
            label.font = UIFont.systemFont(ofSize: 10, weight: .bold)
            label.textColor = index == selectedIndex ? .white : UIColor(red: 0.4, green: 0.4, blue: 0.4, alpha: 1)
            label.textAlignment = .center
            label.layer.cornerRadius = 7
            label.layer.masksToBounds = true
            label.backgroundColor = index == selectedIndex ? UIColor(red: 0, green: 0.51, blue: 1, alpha: 1) : .clear
            NSLayoutConstraint.activate([
                label.widthAnchor.constraint(equalToConstant: 14),
                label.heightAnchor.constraint(equalToConstant: 14)
            ])
            
            label.isUserInteractionEnabled = true
            let tapGesture = UITapGestureRecognizer(target: self, action: #selector(indexTapped(_:)))
            label.addGestureRecognizer(tapGesture)
            label.tag = index
            customIndexView.addArrangedSubview(label)
        }
    }
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        // 获取可见区域的中心点，稍微向下偏移以更准确地检测当前可见的 section
        let visibleRect = CGRect(
            origin: tableView.contentOffset,
            size: tableView.bounds.size
        )
        
        // 将检测点从顶部边缘下移一些，例如下移10%的可见区域高度
        let adjustedY = visibleRect.minY + visibleRect.height * 0.1
        let visiblePoint = CGPoint(x: visibleRect.midX, y: adjustedY)
        
        // 获取可见区域最顶部的单元格的 indexPath
        if let visibleIndexPath = tableView.indexPathForRow(at: visiblePoint) {
            let newIndex = visibleIndexPath.section
            if newIndex != selectedIndex {
                selectedIndex = newIndex
                updateIndexStyles()
            }
        }
    }
    func updateIndexStyles() {
        for (index, view) in customIndexView.arrangedSubviews.enumerated() {
            if let label = view as? UILabel {
                label.textColor = index == selectedIndex ? .white : UIColor(red: 0.4, green: 0.4, blue: 0.4, alpha: 1)
                label.backgroundColor = index == selectedIndex ? UIColor(red: 0, green: 0.51, blue: 1, alpha: 1) : .clear
            }
        }
    }
    
    @objc func indexTapped(_ gesture: UIGestureRecognizer) {
        if let label = gesture.view as? UILabel {
            let index = label.tag
            let indexPath = IndexPath(row: 0, section: index)
            tableView.scrollToRow(at: indexPath, at: .top, animated: true)
            selectedIndex = index
        }
    }
    
    func alertWhenDeleteSomeOne() {
        // 删除之前弹出是否需要备份
        let alertVc = ContactBackupAlertView()
        self.responderViewController()?.view.showBlur()
        self.responderViewController()?.view.addSubview(alertVc)
        alertVc.frame = CGRectMake(0, ScreenH, ScreenW, ScreenH)
        UIView.animate(withDuration: AniDuration) {
            alertVc.frame = CGRectMake(0, 0, ScreenW, ScreenH)
        }
        alertVc.sureCallBack = {[weak self] isSure in
            guard let self else {return}
            self.responderViewController()?.view.hideBlur()
            DispatchQueue.main.asyncAfter(deadline: .now() + AniDuration) {
                if isSure {
                    self.backupContactsByselect {
                        // 删除之前弹出是否真的需要删除
                        let alertVc = ContactDeleteAlertView()
                        alertVc.frame = (self.responderViewController()?.view.bounds)!
                        alertVc.alpha = 0
                        cWindow?.addSubview(alertVc)
                        UIView.animate(withDuration: AniDuration - 0.2) {
                            alertVc.alpha = 1
                        }
                        alertVc.sureCallBack = {[weak self] isSure in
                            guard let self else {return}
                            if isSure {
                                // 提示是否删除
                                self.deleteContacts()
                            }
                        }
                    }
                }else{
                    // 删除之前弹出是否真的需要删除
                    let alertVc = ContactDeleteAlertView()
                    alertVc.frame = (self.responderViewController()?.view.bounds)!
                    cWindow?.addSubview(alertVc)
                    alertVc.alpha = 0
                    UIView.animate(withDuration: AniDuration - 0.2) {
                        alertVc.alpha = 1
                    }
                    alertVc.sureCallBack = {[weak self] isSure in
                        guard let self else {return}
                        if isSure {
                            // 提示是否删除
                            self.deleteContacts()
                        }
                    }
                }
            }
        }
    }
    
    func backupContactsByselect(success:@escaping()->Void){
        // 开始备份联系人，备份完成提示
        let vm = BackupViewModel()
        vm.backupPartialContacts(self.dataSourceModel) { finised, error in
            if finised {
                // 备份成功
                DispatchQueue.main.async {
                    let buAlertVc = ContactBackUpCompletedAlertView(frame: (cWindow?.bounds)!)
                    buAlertVc.alpha = 0
                    cWindow?.addSubview(buAlertVc)
                    UIView.animate(withDuration: AniDuration-0.2) {
                        buAlertVc.alpha = 1
                    }
                    DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
                        buAlertVc.removeFromSuperview()
                        success()
                    }
                }
            }else{
                Print("备份失败")
            }
        }
    }
    
    
    
    
    func deleteContacts(){
        // 删除逻辑
        for contact in selectedContacts {
            if let index = self.dataSourceModel.firstIndex(of: contact) {
                self.dataSourceModel.remove(at: index)
            }
            for (key, var sectionContacts) in sectionedContacts {
                if let index = sectionContacts.firstIndex(of: contact) {
                    sectionContacts.remove(at: index)
                    sectionedContacts[key] = sectionContacts
                }
            }
        }
        
        // fixme: 需要从联系人列表中删除
        ContactManager.batchDeleteContacts(self.selectedContacts) { result in
            switch result {
            case .success(let deletedContacts):
                print("成功删除 \(deletedContacts.count) 个联系人")
                self.selectedContacts.removeAll()
                self.sortContacts()
                self.subTitleLabel.text = "\(self.dataSourceModel.count) Contacts"
                self.updateDeleteButtonStatus()
                self.tableView.reloadData()
                
                if self.dataSourceModel.count <= 0 {
                    self.dataClearCallBack()
                }
                
                // 删除完成 弹窗
                let buAlertVc = ContactBackUpDeleteCompletedAlertView(frame: (cWindow?.bounds)!)
                cWindow?.addSubview(buAlertVc)
                buAlertVc.alpha = 0
                UIView.animate(withDuration: AniDuration - 0.2) {
                    buAlertVc.alpha = 1
                }
                DispatchQueue.main.asyncAfter(deadline: .now() + 2) {
                    UIView.animate(withDuration: AniDuration - 0.2) {
                        buAlertVc.alpha = 0
                    } completion: { su in
                        buAlertVc.removeFromSuperview()
                    }
                }
                break
            case .failure(.contactNotFound(let missing)):
                print("操作终止：未找到联系人 \(missing.identifier)")
            case .failure(.unauthorized):
                print("无通讯录访问权限")
            case .failure(.executionFailed(let error)):
                print("操作失败：\(error.localizedDescription)")
            }
        }
        
    }
    
    func updateDeleteButtonStatus() {
        DispatchQueue.main.async {
            // 判断button是否显示
            if self.selectedContacts.count > 0 {
                // 设置button的title
                self.deleteButton.deleteButton.setTitle("Delete \(self.selectedContacts.count) Contact", for: .normal)
                UIView.animate(withDuration: 0.1) {
                    // 更新约束
                    self.bottomConstraint?.update(offset: -safeHeight)
                    self.tabBottomConstraint?.update(offset: -safeHeight - 68)
                    self.layoutIfNeeded()
                }
            }else{
                UIView.animate(withDuration: 0.1) {
                    // 更新约束
                    self.bottomConstraint?.update(offset: 68)
                    self.tabBottomConstraint?.update(offset: -safeHeight)
                    self.layoutIfNeeded()
                }
            }
        }
    }
    
    
    /// 给联系人分组排序
    func sortContacts() {
        sectionedContacts.removeAll()
        for contact in self.dataSourceModel {
            let firstLetter = pinyinFirstLetter(contact.fullName).uppercased()
            if sectionedContacts[firstLetter] == nil {
                sectionedContacts[firstLetter] = []
            }
            sectionedContacts[firstLetter]?.append(contact)
        }
        
        sectionTitles = sectionedContacts.keys.sorted()
        for key in sectionTitles {
            sectionedContacts[key] = sectionedContacts[key]?.sorted {
                return pinyinFirstLetter($0.fullName).uppercased() < pinyinFirstLetter($1.fullName).uppercased()
            }
        }
    }
    
    // 获取拼音首字母
    private func pinyinFirstLetter(_ string: String) -> String {
        let mutableString = NSMutableString(string: string)
        CFStringTransform(mutableString, nil, kCFStringTransformToLatin, false)
        CFStringTransform(mutableString, nil, kCFStringTransformStripDiacritics, false)
        var pinyin = mutableString as String
        if pinyin.isEmpty {
            return "#"
        }
        pinyin = pinyin.replacingOccurrences(of: " ", with: "")
        return pinyin.isEmpty ? "#" : String(pinyin.first!).uppercased()
    }
    
}
