//
//  SettingListController.swift

//
//  Created by Leon on 2025/7/22.
//

import UIKit
import TZImagePickerController
import Combine

struct SettingItem {
    let title: String
    let action: (() -> Void)?
}

class SettingViewModel {
    var itemsSection1: [SettingItem]
    
    var itemsSection2:[SettingItem]

    init(itemsSection1: [SettingItem], itemsSection2: [SettingItem]) {
        self.itemsSection1 = itemsSection1
        self.itemsSection2 = itemsSection2
    }
}

class SettingListController: CLBaseViewController {
    let logoutButton = StyleButton()
    let tableView = UITableView()

    var viewModel: SettingViewModel!
    //var titleView: TitleView!
    
    var headView: SettingHeaderView!
    
    var uploadingAvatar : UploadPhotoM?
    
    private var cancellables = Set<AnyCancellable>()

    override func viewDidLoad() {
        super.viewDidLoad()

        viewModel = SettingViewModel(itemsSection1: [
            SettingItem(title: "Edit Profile", action: {  [weak self] in self?.goPersonalInfoEdit()}),
            SettingItem(title: "Account", action: { [weak self] in self?.goAccountManage() }),
        ], itemsSection2: [
            SettingItem(title: "About Us", action: { AppRouter.goAboutUs() }),
            SettingItem(title: "User Agreement", action: { AppRouter.goTermsOfService() }),
            SettingItem(title: "Privacy Policy", action: { AppRouter.goPrivacyPolicy() }),
        ])

        setupViews()
        setupEvents()
        navigationView.alpha0Title = "Setting"
    }

    private func setupViews() {
        logoutButton.tertiary(size: .large)
        logoutButton.setTitle("Logout", for: .normal)
        logoutButton.addTarget(self, action: #selector(logoutButtonTapped), for: .touchUpInside)
        view.addSubview(logoutButton)
        logoutButton.snp.makeConstraints { make in
            make.leading.equalToSuperview().offset(CGFloat.lrs)
            make.trailing.equalToSuperview().offset(-CGFloat.lrs)
            make.bottom.equalToSuperview().offset(-UIWindow.safeAreaBottom * 0.5 - 16)
        }

        tableView.contentInset = UIEdgeInsets(top: 0, left: 0, bottom: 16, right: 0)
        view.addSubview(tableView)
        tableView.snp.makeConstraints { make in
            make.leading.equalToSuperview()
            make.trailing.equalToSuperview()
            make.top.equalTo(navigationView.snp.bottom)
            make.bottom.equalTo(logoutButton.snp.top).offset(-16)
        }
        tableView.separatorStyle = .none
        tableView.dataSource = self
        tableView.delegate = self
        tableView.backgroundColor = .clear
        tableView.register(SettingCell.self, forCellReuseIdentifier: "SettingCell")

        headView = {
            let v = SettingHeaderView()
            return v
        }()

        headView.frame = CGRect(x: 0, y: 0, width: view.frame.width, height: 200)

        tableView.tableHeaderView = headView
        headView.heightChangeBlock = {[weak self] height in
            self?.headView.frame = CGRect(x: 0, y: 0, width: UIScreen.width, height: height)
            self?.tableView.tableHeaderView = self?.headView
        }
    }

    private func setupEvents() {
        headView.avatarView.setTapAction { [weak self] in
            self?.tapAvatarButton()
        }
        NotificationCenter.default.addObserver(self, selector: #selector(notiUserInfoChanged), name: AppNotificationName.userInfoUpdated.notificationName, object: nil)
        
        UserCore.shared.$user.sink {[weak self] user in
            self?.headView.avatarView.bindImageUrl(imgUrl: user?.headImage)
        }.store(in: &cancellables)
    }

    @objc func logoutButtonTapped() {
        let alert = Alert(title: "Log out", text: "请确认是否退出登录?")
        let action1 = AlertAction(title: "Log out", actionStyle: .destructive) {[weak self] in
            self?.doLogoutRequest()
        }
        let action2 = AlertAction(title: "Cancel", actionStyle: .cancel)
        alert .addAction(action1)
        alert.addAction(action2)
        alert.show()
    }
    
    // MARK: - Action
    @objc func tapAvatarButton(){
        guard let picker = ImagePicker(maxImagesCount: 1, delegate: self) else { return }
        picker.allowPickingGif = false
        picker.showSelectBtn = false
        picker.needCircleCrop = true
        
        picker.cropRect = CGRect(origin: .init(x: 0, y: 0), size: CGSize(width: UIScreen.width, height: UIScreen.height))
        picker.circleCropRadius = Int((UIScreen.width - 37*2) * 0.5)
        present(picker, animated: true, completion: nil)
    }

    // MARK: - Helper
    
    private func doLogoutRequest(){
        Hud.showIndicator()
        UserProvider.request(.userSignout) { result in
            Hud.hideIndicator()
            switch result{
            case .success:
                UserCore.shared.logout()
                
                AppRouter.goBackRootController {
                    Hud.toast(str: "已退出登陆")
                }
            case .failure:
                return
            }
        }
    }
    
    private func goAccountManage() {
        let vc = AccountManageController()
        navigationController?.pushViewController(vc, animated: true)
    }
    
    private func goPersonalInfoEdit(){
        let vc = PersonInformationEditController()
        navigationController?.pushViewController(vc, animated: true)
    }
    
    func updateHeadImage(headUrlString: String?, completion: ((Bool)->Void)? = nil){
        guard let avatar = headUrlString else { return }
        var params = [String:Any]()
        params.updateValue(UserCore.shared.user!.userId, forKey: "userId")
        params.updateValue(avatar, forKey: "headImage")
        Hud.showIndicator()
        UserProvider.request(.userInfoEdit(params: params), modelType: String.self) {[weak self] result in
            Hud.hideIndicator()
            switch result {
            case .success:
                self?.uploadingAvatar = nil
                UserCore.shared.refreshUserInfo(block: nil)
                completion?(true)
            case .failure:
                completion?(false)
            }
        }
    }
    
    // MARK: - Noti
    @objc private func notiUserInfoChanged(){
        self.headView.avatarView.bindImageUrl(imgUrl: UserCore.shared.user?.headImage)
    }
}

extension SettingListController:TZImagePickerControllerDelegate{
    func imagePickerController(_: TZImagePickerController!,
                               didFinishPickingPhotos photos: [UIImage]!,
                               sourceAssets _: [Any]!,
                               isSelectOriginalPhoto _: Bool,
                               infos _: [[AnyHashable: Any]]!)
    {
        guard let img = photos.first else {
            return
        }
        
        // Crop Avatar
        let cropViewController = CropViewController(image: img) { [unowned self] croppedImage in
            self.headView.avatarView.bindImage(img: croppedImage, showUploading: true)
            
            // 裁剪后的图片
            let photo = UploadPhotoM()
            photo.image = croppedImage
            photo.imageSize = croppedImage?.size ?? CGSizeZero
            photo.addThisItemTimeStamp = Date().timeStamp
            photo.delegate = self
            uploadingAvatar = photo
            
            CloudStorage.shared.s3AddPhotos([photo], bucket: .HEAD_IMAGE)
        }
        let navc = CLNavigationController(rootViewController: cropViewController)
        UIWindow.getTopViewController()?.present(navc, animated: true, completion: nil)
    }
}

extension SettingListController:UploadPhotoDelegate{
    func uploadFailWith(_ photo: UploadPhotoM) {
        dlog("👮upload failed: \(photo)")
        self.headView.avatarView.bindImage(img: nil)
    }
    
    func uploadProgress(_ progress: Float) {
        dlog("👮progress \(progress)")
    }
    
    func uploadDoneWith(_ photo: UploadPhotoM){
        dlog("👮上传成功： \(photo.remoteFullPath ?? ""), remoteImageUrlString  \(photo.remoteImageUrlString ?? "")")
    }
    
    func imageCheck(_ photoM: UploadPhotoM, result: Bool){
        dlog("👮鉴黄结果:\(result)")
        
        if(result){
            // 上传到s3... 并修改个人信息
            self.updateHeadImage(headUrlString: photoM.remoteFullPath) {[weak self] result in
                if result{
                    self?.headView.avatarView.bindImageUrl(imgUrl: photoM.remoteFullPath)
                }
            }
        }else{
            self.headView.avatarView.bindImageUrl(imgUrl: UserCore.shared.user?.headImage)
        }
        
    }
}

extension SettingListController: UITableViewDataSource, UITableViewDelegate {
    func numberOfSections(in tableView: UITableView) -> Int {
        return 2
    }
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if section == 0{
            return viewModel.itemsSection1.count
        }else if section == 1{
            return viewModel.itemsSection2.count
        }
        return 0
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        var item:SettingItem
        if(indexPath.section == 0){
            item = viewModel.itemsSection1[indexPath.row]
        }else{
            item = viewModel.itemsSection2[indexPath.row]
        }
        let cell = tableView.dequeueReusableCell(withIdentifier: "SettingCell", for: indexPath) as! SettingCell
        cell.titleLabel.text = item.title
        
        let total = self.tableView(tableView, numberOfRowsInSection: indexPath.section)
        cell.line.isHidden = true
        if total == 1{
            cell.setupFullCorner()
        }else if indexPath.row == 0{
            cell.line.isHidden = false
            cell.setupFirstCellCorner()
        }else if indexPath.row == total - 1{
            cell.setupLastCellCorner()
        }else{
            cell.line.isHidden = false
            cell.setupEmptyCorner()
        }
        return cell
    }

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        var item:SettingItem
        if(indexPath.section == 0){
            item = viewModel.itemsSection1[indexPath.row]
        }else{
            item = viewModel.itemsSection2[indexPath.row]
        }
        item.action?()
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 16
    }

    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let spacer = UIView()
        spacer.backgroundColor = .clear
        return spacer
    }

    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        NaviAlphaHandle.changeNaviTitleAlpha(scrollView: scrollView, titleLabel: navigationView.titleLabel)
    }
}


class SettingHeaderView: UIView{
    var titleView: TitleView!
    var avatarView: AvatarView!
    
    var heightChangeBlock: ((CGFloat) -> Void)?
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupViews()
        setupData()
        setupEvent()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func layoutSubviews() {
        super.layoutSubviews()
        let maxY = avatarView.frame.maxY + 12
        heightChangeBlock?(maxY)
    }
    
    private func setupViews() {
        titleView = {
            let view = TitleView()
            view.title = "Setting"
            view.backgroundColor = .clear
            addSubview(view)
            view.snp.makeConstraints { make in
                make.leading.trailing.equalToSuperview()
                make.top.equalToSuperview()
            }
            return view
        }()

        avatarView = {
            let view = AvatarView()
            view.cameraCircle.isHidden = false
            addSubview(view)
            view.snp.makeConstraints { make in
                make.centerX.equalToSuperview()
                make.top.equalTo(titleView.snp.bottom).offset(12)
                make.size.equalTo(CGSize(width: 90, height: 90))
            }
            return view
        }()
    }
    
    private func setupData(){
        
    }
    
    private func setupEvent(){
        
    }
}

class SettingCell: UITableViewCell {
    var block: UIView!
    var titleLabel: UILabel!
    var arrowImageView: UIImageView!

    var line: LineView!
    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        setupViews()
    }

    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    func setupViews() {
        backgroundColor = .clear
        selectionStyle = .none

        block = {
            let view = UIView()
            view.backgroundColor = .c.csbn
            view.layer.cornerRadius = 16
            view.layer.masksToBounds = true
            contentView.addSubview(view)
            view.snp.makeConstraints { make in
                make.leading.equalToSuperview().offset(CGFloat.lrs)
                make.trailing.equalToSuperview().offset(-CGFloat.lrs)
                make.top.equalToSuperview()//.offset(12)
                make.bottom.equalToSuperview()//.offset(-4)
                make.height.equalTo(61)
            }
            return view
        }()

        titleLabel = {
            let label = UILabel()
            label.font = .t.tts
            label.textColor = .c.ctpn
            block.addSubview(label)
            label.snp.makeConstraints { make in
                make.leading.equalToSuperview().offset(16)
                make.centerY.equalToSuperview()
            }
            return label
        }()

        arrowImageView = {
            let imageView = UIImageView()
            imageView.image = MWIconFont.image(fromIcon: .arrowRightBorder, size: CGSizeMake(12, 12), color: .c.ctsn)
            block.addSubview(imageView)
            imageView.snp.makeConstraints { make in
                make.trailing.equalToSuperview().offset(-16)
                make.centerY.equalToSuperview()
                make.size.equalTo(CGSize(width: 12, height: 12))
            }
            imageView.contentMode = .scaleAspectFit
            return imageView
        }()
        
        line = {
            let v = LineView()
            block.addSubview(v)
            v.snp.makeConstraints { make in
                make.bottom.equalToSuperview()
                make.leading.equalToSuperview().offset(16)
                make.trailing.equalToSuperview().offset(-16)
            }
            return v
        }()
    }
    
    func setupFirstCellCorner(){
        block.layer.maskedCorners = [.layerMinXMinYCorner, .layerMaxXMinYCorner]
    }
    
    func setupLastCellCorner(){
        block.layer.maskedCorners = [.layerMinXMaxYCorner, .layerMaxXMaxYCorner]
    }
    
    func setupFullCorner(){
        block.layer.maskedCorners = [
            .layerMinXMinYCorner, // 左上
            .layerMaxXMinYCorner, // 右上
            .layerMinXMaxYCorner, // 左下
            .layerMaxXMaxYCorner  // 右下
        ]
    }
    
    func setupEmptyCorner(){
        block.layer.maskedCorners = []
    }
}
