//
//  SpeakEleProfileViewCtr.swift
//  SpeakEasyLearnEnglish
//
//  Created by edy on 2025/7/21.
//

import UIKit

class SpeakEleProfileViewCtr: SpeakEleBaseViewCtr {

    @IBOutlet weak var SpeakProfileTableView: UITableView!
    
    private let viewModel = SpeakEleProfileViewModel()
    private let userViewModel = SpeakUserNetViewModel()
    private let qa = SpeakEleQAViewModel()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        NotificationCenter.default.addObserver(self, selector: #selector(updateUI), name: Notification.Name.ProfilesettingUpdateUI, object: nil)
    }
    
    override func setup() {
        SpeakProfileTableView.delegate = self
        SpeakProfileTableView.dataSource = self
        SpeakProfileTableView.separatorStyle = .none
        SpeakProfileTableView.sectionHeaderTopPadding = 0
        SpeakProfileTableView.showsVerticalScrollIndicator = false
        SpeakProfileTableView.showsHorizontalScrollIndicator = false
        SpeakProfileTableView.estimatedSectionHeaderHeight = 120 + SpWindow.safeAreaInsets.top + Dev.navHeight + 60
        SpeakProfileTableView.sectionHeaderHeight = UITableView.automaticDimension
        SpeakProfileTableView.register(UINib(nibName: SpeakEleProfileSwtichCell.id, bundle: nil), forCellReuseIdentifier: SpeakEleProfileSwtichCell.id)
        SpeakProfileTableView.register(UINib(nibName: SpeakEleProfileCell.id, bundle: nil), forCellReuseIdentifier: SpeakEleProfileCell.id)
        SpeakProfileTableView.register(SpeakEleProfileHeaderView.self, forHeaderFooterViewReuseIdentifier: SpeakEleProfileHeaderView.id)
    }
    
    @objc func updateUI() -> Void {
        SpeakProfileTableView.reloadData()
    }
    
    @IBAction func SpeakShareTaps(_ sender: Any) {
        let items: [Any] = [ URL(string: AppStoreShare)! ]
        let shareVc = UIActivityViewController(
            activityItems: items,
            applicationActivities: nil
        )
        present(shareVc, animated: true)
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        titleView.isHidden = true
        SpeakProfileTableView.reloadData()
    }
    
    deinit {
        NotificationCenter.default.removeObserver(self)
    }
}

extension SpeakEleProfileViewCtr : UITableViewDelegate,UITableViewDataSource {
    
    private func updateUser(state:SpeakTitleState ,data:Any) -> Void {
        var parma:[String:Any] = [:]
        if state == .Learn {
            if let l = data as? Bool {
                parma["learnedNative"] = l ? 1 : 0
            }
        }
        userViewModel.update(param: parma) { su in
            if su {
                SpeakElePublicManager.share.userInfo.learnedNative = parma["learnedNative"] as? Int ?? 0
            }
        }
        
    }
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return viewModel.setting.count
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        let st = viewModel.setting[section]
        return st.child?.count ?? 0
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let child = viewModel.setting[safe:indexPath.section]?.child
        let st = child?[indexPath.row]
        if st?.state == .PInfo {
            let cell = tableView.dequeueReusableCell(withIdentifier: SpeakEleProfileCell.id, for: indexPath) as! SpeakEleProfileCell
            cell.isTop = (indexPath.row == 0)
            cell.isBot = (indexPath.row == (child?.count ?? 0) - 1)
            cell.data = st
            cell.callblack = { [weak self] data in
                self?.updateUser(state: st?.title ?? .Delete, data: data)
            }
            return cell
        }else{
            let cell = tableView.dequeueReusableCell(withIdentifier: SpeakEleProfileSwtichCell.id, for: indexPath) as! SpeakEleProfileSwtichCell
            cell.isTop = (indexPath.row == 0)
            cell.isBot = (indexPath.row == (child?.count ?? 0) - 1)
            cell.data = st
            cell.callblack = { [weak self] data in
                self?.updateUser(state: st?.title ?? .Learn, data: data)
            }
            return cell
        }
    }
    
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let header = tableView.dequeueReusableHeaderFooterView(withIdentifier: SpeakEleProfileHeaderView.id) as! SpeakEleProfileHeaderView
        header.isFrist = section == 0
        header.data = viewModel.setting[section]
        return header
    }
    
//    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
//        if section == 0 {
//            return 120 + SpWindow.safeAreaInsets.top + Dev.navHeight + 60
//        }
//        return 50
//    }
    
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        if section == viewModel.setting.count - 1 {
            return 150
        }
        return 0.01
    }
    
    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        let footer = UIView()
        footer.backgroundColor = .clear
        if section == viewModel.setting.count - 1 {
            let icon = UIImageView(image: UIImage(named: "logo"))
            footer.addSubview(icon)
            icon.snp.makeConstraints { make in
                make.centerX.equalToSuperview()
                make.top.equalToSuperview().offset(25)
            }
            let t = UILabel()
            t.text = "Speak Easy Learning"
            t.textColor = .init(hex: 0x000000,alpha: 0.9)
            t.font = UIFont.montserrat(.semiBold ,size: 14)
            footer.addSubview(t)
            t.snp.makeConstraints { make in
                make.centerX.equalToSuperview()
                make.top.equalTo(icon.snp.bottom).offset(12)
            }
            let vt = UILabel()
            if let version = Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String {
                vt.text = "Version \(version)"
            }
            vt.textColor = .init(hex: 0x000000,alpha: 0.9)
            vt.font = UIFont.montserrat(.regular ,size: 14)
            footer.addSubview(vt)
            vt.snp.makeConstraints { make in
                make.centerX.equalToSuperview()
                make.top.equalTo(t.snp.bottom).offset(6)
            }
        }
        return footer
    }
    
    
    
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let st = viewModel.setting[safe:indexPath.section]?.child?[indexPath.row]
        switch st?.title {
        case .TargetLanguage , .NativeLanguage ,.Interest ,.Target:
            if st?.title == .TargetLanguage && !IAPViewModel.share.isSubscribed {
                return
            }
            let more = SpeakProfileMoreViewCtr(state: st?.title ?? .TargetLanguage)
            self.navigationController?.pushViewController(more, animated: true)
            break
        case .Restore:
            IAPViewModel.share.restore(.week) { su in
                
            }
            break
        case .RateUs:
            let rate = SpeakEleRateUsViewCtr()
            rate.show()
            break
        case .PrivacyPolicy:
            let web = SpeakEleWebViewCtr()
            web.LoadWithUrl(url: SpeakPrivacy)
            self.parent?.navigationController?.pushViewController(web, animated: true)
            break
        case .Terms:
            let web = SpeakEleWebViewCtr()
            web.LoadWithUrl(url: SpeakTerms)
            self.parent?.navigationController?.pushViewController(web, animated: true)
            break
        case .Delete:
            SpeakAlertHUD.share.show()
            viewModel.deleteAccount { [weak self] in
                SpeakAlertHUD.share.disMiss()
                self?.deleteAccount()
            }
            break
        default:
            break
        }
    }
}

extension SpeakEleProfileViewCtr {
    
    func deleteAccount() -> Void {
        SpeakElePublicManager.share.PublicData = PublicModel()
        SpeakElePublicManager.share.userInfo = UserMode()
        SpeakLeassonData.data.leassionData = []
        SpeakDayEveryManager.manager.deleteTab()
        SpeakCache.cache.delete()
        qa.anwer = []
        
        SpeakElePublicManager.share.PublicData.state = .start
        let nav = SpeakEleBaseNavigationCtr(rootViewController: SpeakEleLoginGuideCtr())
        SpWindow.rootViewController = (nav)
    }
    
}
