//
//  ContactBackupDetailViewController.swift
//  PhoneManager
//
//  Created by 赵前 on 2025/4/20.
//

import Foundation
import Contacts
import UIKit

class ContactBackupDetailViewController : BaseViewController {
    
    var dataSourceModel : [ContactModel] = []
    
    
    /// 分组后的联系人
    private var sectionedContacts: [String: [ContactModel]] = [:]
    
    /// 联系人首字母数组
    private var sectionTitles: [String] = []
    
    /// 选择的联系人
    private var selectedContacts: [ContactModel] = []
    
    
    var customIndexView: UIStackView!
    
    var selectedIndex = 0
    
    lazy var navView : ContactNavView = {
        let view = ContactNavView()
        return view
    }()
    
    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(CustomContactBacDetailTableViewCell.self, forCellReuseIdentifier: "CustomContactBacDetailTableViewCell")
        tableView.separatorStyle = .none
        tableView.backgroundColor = .clear
        tableView.showsVerticalScrollIndicator = false
        if #available(iOS 15.0, *) {
            tableView.sectionHeaderTopPadding = 0
        }
        return tableView
    }()
    
    lazy var restoreButton : RestoreButtonView = {
        let button = RestoreButtonView()
        // 设置删除按钮
        button.layer.cornerRadius = 23
        button.clipsToBounds = true
        return button
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        self.view.addSubview(self.navView)
        self.view.addSubview(self.titleLabel)
        self.view.addSubview(self.subTitleLabel)
        self.view.addSubview(self.tableView)
        self.view.addSubview(self.restoreButton)
        
        self.navView.snp.makeConstraints { make in
            make.top.left.right.equalToSuperview()
            make.height.equalTo(statusBarHeight + 44)
        }
        
        self.titleLabel.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(15 * RScreenW())
            make.top.equalTo(self.navView.snp.bottom)
            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())
            make.bottom.equalToSuperview().offset(-102 * RScreenH())
        }
        self.restoreButton.snp.makeConstraints { make in
            make.top.equalTo(self.tableView.snp.bottom).offset(16 * RScreenH())
            make.width.equalTo(345 * RScreenW())
            make.height.equalTo(46)
            make.centerX.equalToSuperview()
        }
        
        // 排序
        self.sortContacts()
        
        self.restoreButton.submitCallBack = {
            self.alertRestore()
        }
    }
    
}
extension ContactBackupDetailViewController:UITableViewDelegate,UITableViewDataSource {
    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, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "CustomContactBacDetailTableViewCell", for: indexPath) as! CustomContactBacDetailTableViewCell
        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"
        
        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.view.addSubview(customIndexView)
        
        self.customIndexView.snp.makeConstraints { make in
            make.left.equalTo(self.tableView.snp.right).offset(0)
            make.centerY.equalTo(self.view.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 alertRestore() {
        // 是否确实需要恢复
        let alertVc = ContactBacRestoreAlertView(frame: self.view.bounds)
        alertVc.alpha = 0
        self.view.addSubview(alertVc)
        UIView.animate(withDuration: AniDuration - 0.2) {
            alertVc.alpha = 1
        }
        alertVc.sureCallBack = {
            ContactManager.performAtomicRestore(self.dataSourceModel) { success, error in
                if success {
                    print("恢复成功！")
                    DispatchQueue.main.async {
                        // 再次请求数据 重新刷新页面
                        let buAlertVc = ContactRestoreSuccessView(frame: self.view.bounds)
                        cWindow?.addSubview(buAlertVc)
                        DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
                            buAlertVc.removeFromSuperview()
                        }
                    }
                } else {
                    print("失败原因: \(error?.localizedDescription ?? "未知错误")")
                }
            }
        }
    }
    
    
    /// 给联系人分组排序
    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()
    }
}
