//
//  EmailFilterController.swift
//  PhoneManager
//
//  Created by edy on 2025/5/9.
//

import UIKit

class EmailFilterController: BaseViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        setup()
    }

    var filter = EmailFilterManager.share.FilterSet
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.tableView.reloadData()
        self.view.layoutIfNeeded()
    }
    
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        DispatchQueue.main.asyncAfter(deadline: .now()+0.1) {
            self.tableView.reloadData()
        }
    }
    
    var datasource:[EmailFilterModel] = EmailFilterManager.share.EmailfilterHeaders()
    
    private func setup() -> Void {
        titleLabel.snp.makeConstraints({ make in
            make.left.equalTo(titleView.backBtn.snp.right).offset(5)
            make.centerY.equalTo(titleView.backBtn)
        })
        tableView.snp.makeConstraints { make in
            make.left.right.equalToSuperview().inset(marginLR)
            make.top.equalTo(titleView.snp.bottom).offset(10)
            make.bottom.equalTo(ApplyBtn.snp.top)
        }
        ApplyBtn.snp.makeConstraints { make in
            make.height.equalTo(46)
            make.bottom.equalToSuperview().offset(-(cWindow?.safeAreaInsets.bottom ?? 0)-10)
            make.left.right.equalToSuperview().inset(marginLR)
        }
    }
    
    private lazy var titleLabel: UILabel = {
        let label = UILabel()
        label.text = "Filters"
        label.font = UIFont.systemFont(ofSize: 20, weight: .bold)
        label.textColor = .black
        label.textAlignment = .left
        titleView.addSubview(label)
        return label
    }()
    
    private lazy var tableView: UITableView = {
        let tab = UITableView(frame: CGRectZero, style: .grouped)
        tab.delegate = self;
        tab.dataSource = self
        tab.showsVerticalScrollIndicator = false
        tab.showsHorizontalScrollIndicator = false
        tab.separatorStyle = .none
        tab.backgroundColor = .white
        tab.separatorInset = UIEdgeInsets()
        tab.sectionHeaderHeight = 50
        tab.register(UINib(nibName: EmailFilterSelectCell.id, bundle: nil), forCellReuseIdentifier: EmailFilterSelectCell.id)
        tab.register(UINib(nibName: EmailFilterFAVORITECell.id, bundle: nil), forCellReuseIdentifier: EmailFilterFAVORITECell.id)
        tab.register(UINib(nibName: EmailFilterFAVORITECell.id, bundle: nil), forCellReuseIdentifier: EmailFilterFAVORITECell.id + "Sub")
        tab.register(UINib(nibName: EmailFilterKeywordCell.id, bundle: nil), forCellReuseIdentifier: EmailFilterKeywordCell.id)
        tab.register(UINib(nibName: EmailKeyWordItemsCell.id, bundle: nil), forCellReuseIdentifier: EmailKeyWordItemsCell.id)
        if #available(iOS 15.0, *) {
            tab.sectionHeaderTopPadding = 0
        }
        view.addSubview(tab)
        return tab
    }()
    
    private lazy var ApplyBtn: UIButton = {
        let emailLogin = UIButton(type: .custom)
        emailLogin.backgroundColor = UIColor.colorWithHex(hexStr: "#0082FF")
        emailLogin.setTitle("Apply Filters", for: .normal)
        emailLogin.setTitleColor(.white, for: .normal)
        emailLogin.titleLabel?.font = UIFont.boldSystemFont(ofSize: 16)
        emailLogin.layer.cornerRadius = 46/2.0
        emailLogin.clipsToBounds = true
        emailLogin.backgroundColor = UIColor.colorWithHex(hexStr: "#0082FF")
        emailLogin.addTarget(self, action: #selector(ApplyAction), for: .touchUpInside)
        view.addSubview(emailLogin)
        return emailLogin
    }()
        
    private func readUnread(_ indexPath:IndexPath ,isselect:Bool) -> Void {
        if isselect {
            if indexPath.row == 0 {
                self.filter.read = isselect
            }else{
                self.filter.unread = isselect
            }
        }else{
            if indexPath.row == 0 {
                if self.filter.unread == false {
                    self.filter.unread = true
                    self.filter.read = isselect
                }else{
                    self.filter.read = isselect
                }
            }else{
                if self.filter.read == false {
                    self.filter.read = true
                    self.filter.unread = isselect
                }else{
                    self.filter.unread = isselect
                }
            }
        }
    }
    
}

extension EmailFilterController : UITableViewDelegate,UITableViewDataSource {
    
    @objc func ApplyAction() -> Void {
        let alert = EmailContentDelAlert(state: .emailApply)
        alert.show()
        self.view.showBlur()
        alert.callblock = { [weak self] idx in
            guard let self = self else { return }
            self.view.hideBlur()
            if idx == 1 {
                EmailFilterManager.share.FilterSet = self.filter
                EmailFilterManager.share.SelectEmailSet = (0..<5).map { _ in NSMutableSet() }
                emailSort()
                let save = EmailSaveController()
                save.modalTransitionStyle = .crossDissolve
                save.modalPresentationStyle = .overFullScreen
                self.present(save, animated: true)
                DispatchQueue.main.asyncAfter(deadline: .now()+1.5) {
                    save.dismiss(animated: true) {
                        self.navigationController?.popViewController(animated: true)
                    }
                }
            }
        }
    }
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return datasource.count + 1
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if section < datasource.count {
            return datasource[section].child?.count ?? 0
        }
        return 1
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        if indexPath.section < datasource.count {
            let dataA = datasource[indexPath.section].child
            let data = dataA?[indexPath.row]
            if datasource[indexPath.section].header == "TIME" {
                let cell = tableView.dequeueReusableCell(withIdentifier: EmailFilterSelectCell.id, for: indexPath) as! EmailFilterSelectCell
                cell.titleL.text = data?.title ?? ""
                cell.selectBtn.isSelected = (filter.date == indexPath.row)
                cell.top = (indexPath.row == 0)
                cell.bot = (indexPath.row == ((dataA?.count ?? 1) - 1))
                cell.callblock = {[weak self] select in
                    guard let self = self else { return }
                    self.filter.date = indexPath.row
                    self.vibrate()
                    tableView.reloadData()
                }
                cell.selectionStyle = .none
                cell.reload()
                return cell
            }else if datasource[indexPath.section].header == "FAVORITE" {
                let cell = tableView.dequeueReusableCell(withIdentifier: EmailFilterFAVORITECell.id, for: indexPath) as! EmailFilterFAVORITECell
                cell.titleL.text = data?.title ?? ""
                cell.emSwtich.isOn = filter.start
                cell.top = (indexPath.row == 0)
                cell.selectionStyle = .none
                cell.bot = (indexPath.row == ((dataA?.count ?? 1) - 1))
                cell.callblock = {[weak self] select in
                    guard let self = self else { return }
                    self.filter.start = select
                    tableView.reloadData()
                }
                cell.reload()
                return cell
            }else if datasource[indexPath.section].header == "READ & UNREAD" {
                let cell = tableView.dequeueReusableCell(withIdentifier: EmailFilterFAVORITECell.id + "Sub", for: indexPath) as! EmailFilterFAVORITECell
                cell.titleL.text = data?.title ?? ""
                if indexPath.row == 0 {
                    cell.emSwtich.isOn = filter.read
                }else{
                    cell.emSwtich.isOn = filter.unread
                }
                cell.top = (indexPath.row == 0)
                cell.selectionStyle = .none
                cell.bot = (indexPath.row == ((dataA?.count ?? 1) - 1))
                cell.callblock = {[weak self] select in
                    guard let self = self else { return }
                    self.readUnread(indexPath,isselect: select)
                    tableView.reloadData()
                }
                cell.reload()
                return cell
            }else{
                let cell =  tableView.dequeueReusableCell(withIdentifier: EmailFilterKeywordCell.id, for: indexPath) as! EmailFilterKeywordCell
                cell.kwTitleL.text = data?.title ?? ""
                cell.emSwitch.isOn = filter.keyword
                cell.top = (indexPath.row == 0)
                cell.selectionStyle = .none
                cell.bot = (indexPath.row == (dataA?.count ?? 0 - 1))
                cell.callblock = {[weak self] event, select in
                    guard let self = self else { return }
                    if event == "switch" {
                        self.filter.keyword = select
                        tableView.reloadData()
                    }else{
                        self.view.showBlur()
                        let keyword = EmailKeywordController()
                        keyword.modalPresentationStyle = .overFullScreen
                        keyword.callblock = { text in
                            if text.count > 0 {
                                var keywords = EmailFilterManager.share.keyword
                                keywords.append(text)
                                
                                EmailFilterManager.share.keyword = keywords
                                tableView.reloadData()
                            }
                            self.view.hideBlur()
                        }
                        self.present(keyword, animated: true)
                    }
                }
                cell.reload()
                return cell
            }
        }else{
            let cell = tableView.dequeueReusableCell(withIdentifier: EmailKeyWordItemsCell.id, for: indexPath) as! EmailKeyWordItemsCell
            cell.selectionStyle = .none
            cell.datasoure = EmailFilterManager.share.keyword
            cell.callblock = {
                tableView.reloadData()
            }
            cell.reload()
            return cell
        }
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        if section < datasource.count {
            let header = UILabel()
            header.backgroundColor = .white
            header.font = UIFont.boldSystemFont(ofSize: 12)
            header.text = datasource[section].header ?? ""
            header.textColor = UIColor.colorWithHex(hexStr: "#B3B3B3")
            return header
        }
        return UIView()
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        if section < datasource.count {
            return 50
        }
        return 0.01
    }
    
    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        let v = UIView()
        v.backgroundColor = .white
        return v
    }
    
}
