//
//  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()
    
    
    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
        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: "https://apps.apple.com/app/id6748631330")! ]
        let shareVc = UIActivityViewController(
            activityItems: items,
            applicationActivities: nil
        )
        present(shareVc, animated: true)
    }
    
    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.PublicData.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, didSelectRowAt indexPath: IndexPath) {
        let st = viewModel.setting[safe:indexPath.section]?.child?[indexPath.row]
        switch st?.title {
        case .Language:
            
            break
            
        case .Interest:
            let qa = SpeakEleQAViewModel()
            qa.fetchData()
            let inte = SpeakEleQAMoreViewCtr(items: qa.SpeakHoby, state: SpeakMessageType.hobby)
            self.present(inte, animated: true)
            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
        default:
            break
        }
    }
}
