//
//  ResourceFilterBoxView.swift
//  PhoneManager
//
//  Created by edy on 2025/5/12.
//

import Foundation

import SnapKit

enum ResouceSortType : String{
    case largest = "largest"
    case smallest = "smallest"
    case latest = "latest"
    case oldest = "oldest"
}

struct ResourceFilterBoxModel {
    var startDate : Date?
    var endDate : Date?
    var sortType : ResouceSortType = .latest
    
    init(startDate: Date? = nil, endDate: Date? = nil, sortType: ResouceSortType) {
        self.startDate = startDate
        self.endDate = endDate
        self.sortType = sortType
    }
}

class ResourceFilterBoxView : UIView {
    
    var submitCallBack : (ResourceFilterBoxModel)->Void = {model in}
    
    var startDate : Date?
    var endDate : Date?
    
    var currentSortType: ResouceSortType = .latest
    let tableData: [String] = ["largest", "smallest", "latest", "oldest"]
    var callBack : callBack<Any> = {sortType in}
    
    var datePicker : YearMonthPickerView?
    
    private var selectedViewBottomConstraint: Constraint?
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    lazy var backView: UIView = {
        let view = UIView()
        view.backgroundColor = UIColor(red: 0.07, green: 0.07, blue: 0.07, alpha: 0.8000)
        view.backgroundColor = .clear
        view.isUserInteractionEnabled = true
        let tap = UITapGestureRecognizer()
        tap.addTarget(self, action: #selector(backViewClick))
        view.addGestureRecognizer(tap)
        return view
    }()
    
    lazy var selectedView: UIView = {
        let view = UIView()
        view.backgroundColor = .white
        return view
    }()
    
    lazy var startDateButton : DateSelectButtonView = {
        let view = DateSelectButtonView()
        view.type = .start
        view.dateButton.addTarget(self , action: #selector(startDateButtonAction), for: .touchUpInside)
        return view
    }()
    lazy var endDateButton : DateSelectButtonView = {
        let view = DateSelectButtonView()
        view.type = .end
        view.dateButton.addTarget(self , action: #selector(endDateButtonAction), for: .touchUpInside)
        return view
    }()
    
    lazy var titleLabel: UILabel = {
        let view = UILabel()
        view.text = "Sorting method"
        view.textAlignment = .center
        view.textColor = UIColor(red: 0.7, green: 0.7, blue: 0.7, alpha: 1)
        view.font = UIFont.systemFont(ofSize: 14, weight: .bold)
        return view
    }()
    
    lazy var tableView: UITableView = {
        let view = UITableView()
        view.register(ResourceFilterBoxTableViewCell.classForCoder(), forCellReuseIdentifier: "ResourceFilterBoxTableViewCell")
        view.backgroundColor = .clear
        view.separatorStyle = .none
        view.showsVerticalScrollIndicator = false
        view.delegate = self
        view.dataSource = self
        view.contentInset = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
        if #available(iOS 15.0, *) {
            view.sectionHeaderTopPadding = 0
        }
        return view
    }()
    
    lazy var applyButton: UIButton = {
        let view = UIButton(type: .custom)
        view.setTitle("Continue", for: .normal)
        view.layer.cornerRadius = 25
        view.clipsToBounds = true
        view.backgroundColor = UIColor(red: 0, green: 0.51, blue: 1, alpha: 1)
        view.setTitleColor(.white, for: .normal)
        view.addTarget(self, action: #selector(applyAction), for: .touchUpInside)
        return view
    }()
    
    init(frame: CGRect,startDate : Date?, endDate :Date?,sortType: ResouceSortType?) {
        super.init(frame: frame)
        self.startDate = startDate
        self.endDate = endDate
        if let sortType = sortType  {
            self.currentSortType = sortType
        }
        addViews()
        setUpUI()
        self.setDefaultDataInPage()
        
    }
    
    private func setDefaultDataInPage(){
        // 设置按钮
        resetByType(date: self.startDate, type: PickerDateType.start)
        resetByType(date: self.endDate, type: PickerDateType.end)
        
        // 设置选择框
        DispatchQueue.main.async {
            self.tableView.reloadData()
        }
    }
    
    
    /// 设置当前年月
    /// - Parameters:
    ///   - date: 时间
    ///   - type: 类型
    private func resetByType(date:Date?,type:PickerDateType){
        if let date = date {
            let timeNumber = getYearAndMonthFromDate(currentDate: date)
            if let year = timeNumber.0{
                if let month = timeNumber.1 {
                    self.resetDateStringFromYearAndMonth(year: year, month: month, type: type)
                }
            }
        }
    }
    
    /// 通过时间获取年月
    /// - Parameter currentDate: 当前时间
    /// - Returns: 年和月
    private func getYearAndMonthFromDate(currentDate : Date)->(Int?,Int?){
        let calendar = Calendar.current
        let components = calendar.dateComponents([.year, .month], from: currentDate)
        return (components.year,components.month)
    }
    
    
    /// 设置按钮显示
    /// - Parameters:
    ///   - year: 年
    ///   - month: 月
    ///   - type: 按钮类型
    func resetDateStringFromYearAndMonth(year: Int, month: Int ,type: PickerDateType){
        DispatchQueue.main.async {
            if type == .start {
                self.startDateButton.dateButton.setTitle("From \(self.getMonthEn(month: month)) \(year)", for: .normal)
                self.startDateButton.closeButton.isHidden = false
                self.startDate = self.dateFrom(year: year, month: month)
            }else {
                // 判断结束时间是否大于开始时间，如果是
                self.endDateButton.dateButton.setTitle("To \(self.getMonthEn(month: month)) \(year)", for: .normal)
                self.endDateButton.closeButton.isHidden = false
                self.endDate = self.lastDayOfMonth(year: year, month: month)
            }
        }
    }
    
    func getMonthEn(month: Int) -> String {
        // 检查输入是否在有效范围内（1-12）
        guard (1...12).contains(month) else {
            return "Invalid Month" // 或抛出错误
        }
        
        let formatter = DateFormatter()
        formatter.locale = Locale(identifier: "en_US")
        return formatter.monthSymbols[month - 1]
    }
    
    override func removeFromSuperview() {
        UIView.animate(withDuration: AniDuration) {
            // 更新约束
            self.backView.backgroundColor = .clear
            self.selectedViewBottomConstraint?.update(offset: 440)
            self.layoutIfNeeded()
        }completion: { _ in
            super.removeFromSuperview()
        }
    }
    
    func addViews(){
        self.addSubview(self.backView)
        self.backView.addSubview(self.selectedView)
        self.selectedView.addSubview(self.startDateButton)
        self.selectedView.addSubview(self.endDateButton)
        self.selectedView.addSubview(self.titleLabel)
        self.selectedView.addSubview(self.tableView)
        self.selectedView.addSubview(self.applyButton)
        
        self.startDateButton.closeCallBack = {
            self.startDate = nil
            self.datePicker?.startDate = nil
            self.datePicker?.reloadData()
        }
        self.endDateButton.closeCallBack = {
            self.endDate = nil
            self.datePicker?.endDate = nil
            self.datePicker?.reloadData()
        }
        
        self.startDateButton.reSetButtonTitle()
        self.endDateButton.reSetButtonTitle()
        
    }
    
    func setUpUI(){
        self.backView.snp.makeConstraints { make in
            make.top.left.right.bottom.equalToSuperview()
        }
        
        self.selectedView.snp.makeConstraints { make in
            make.left.right.equalToSuperview()
            make.height.equalTo(440)
            // 初始时将 selectedView 移到屏幕下方
            self.selectedViewBottomConstraint = make.bottom.equalToSuperview().offset(440).constraint
        }
        
        self.startDateButton.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(27 * RScreenW())
            make.top.equalToSuperview().offset(24)
            make.width.equalTo(151 * RScreenW())
            make.height.equalTo(46)
        }
        
        self.endDateButton.snp.makeConstraints { make in
            make.right.equalToSuperview().offset(-27 * RScreenW())
            make.top.equalToSuperview().offset(24)
            make.width.equalTo(151 * RScreenW())
            make.height.equalTo(46)
        }
        
        self.titleLabel.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(15)
            make.right.equalToSuperview().offset(-15)
            make.top.equalTo(self.startDateButton.snp.bottom).offset(11)
            make.height.equalTo(22)
        }
        self.applyButton.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(15)
            make.right.equalToSuperview().offset(-15)
            make.height.equalTo(50)
            make.bottom.equalToSuperview().offset(-26)
        }
        
        self.tableView.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(15)
            make.right.equalToSuperview().offset(-15)
            make.top.equalTo(self.titleLabel.snp.bottom).offset(14)
            make.bottom.equalTo(self.applyButton.snp.top).offset(-23)
        }
        
        // 先显示背景，然后延迟显示弹框
        DispatchQueue.main.asyncAfter(deadline: .now() + 0.01) {
            UIView.animate(withDuration: AniDuration) {
                // 更新约束
                self.selectedViewBottomConstraint?.update(offset: 0)
                self.layoutIfNeeded()
            }
        }
    }
    
    
    
    
    @objc func applyAction() {
        // 移除自身
        self.dismissDatePicker()
        self.removeFromSuperview()
        cWindow?.hideBlur()
        
        self.submitCallBack(ResourceFilterBoxModel.init(startDate: self.startDate, endDate: self.endDate, sortType: self.currentSortType))
        // 开始排序
    }
    
    func dateFrom(year: Int, month: Int) -> Date? {
        var components = DateComponents()
        components.year = year
        components.month = month
        components.day = 1   // 设置为当月第一天
        components.timeZone = TimeZone(identifier: "UTC")
        
        // 使用公历日历
        let calendar = Calendar(identifier: .gregorian)
        return calendar.date(from: components)
    }
    
    func lastDayOfMonth(year: Int, month: Int) -> Date? {
        // 计算下个月的年和月
        var nextMonth = month + 1
        var nextYear = year
        if nextMonth > 12 {
            nextMonth = 1
            nextYear += 1
        }
        
        // 获取下个月第一天的日期
        var components = DateComponents()
        components.year = nextYear
        components.month = nextMonth
        components.day = 1
        components.timeZone = TimeZone(identifier: "UTC")
        
        let calendar = Calendar(identifier: .gregorian)
        guard let nextMonthFirstDay = calendar.date(from: components) else {
            return nil
        }
        
        // 减去一天得到当月最后一天
        return calendar.date(byAdding: .day, value: -1, to: nextMonthFirstDay)
    }
    
    
    
    @objc func backViewClick() {
        // 移除自身
        self.dismissDatePicker()
        self.removeFromSuperview()
        cWindow?.hideBlur()
        
    }
    
    @objc func startDateButtonAction(_ sender : UIButton) {
        popDatePikerView(type: .start)
    }
    
    @objc func endDateButtonAction(_ sender : UIButton) {
        popDatePikerView(type: .end)
    }
    
    func popDatePikerView(type: PickerDateType){
        showDatePicker(type: type,startDate: self.startDate,endDate: self.endDate)
    }
    
    // 显示
    func showDatePicker(type: PickerDateType,startDate:Date?,endDate:Date?){
        if self.datePicker != nil {
            self.datePicker?.type = type
            self.datePicker?.startDate = self.startDate
            self.datePicker?.endDate = self.endDate
            self.datePicker?.reloadData()
            return
        }
        self.datePicker = YearMonthPickerView()
        self.datePicker?.type = type
        self.datePicker?.startDate = self.startDate
        self.datePicker?.endDate = self.endDate
        
        self.datePicker?.backgroundColor = .white
        if let window = cWindow,let datePicker = self.datePicker {
            let datePickerFrame = CGRect(x: 0, y: window.height, width:window.width, height: 204)
            datePicker.frame = datePickerFrame
            cWindow?.addSubview(datePicker)
            UIView.animate(withDuration: 0.3, animations: {
                datePicker.frame = CGRect(x: 0, y: window.height - 204, width: window.width, height: 204)
            })
        }
        self.datePicker?.onCancel = {
            self.dismissDatePicker()
        }
        self.datePicker?.onConfirm = {type,year,month in
            self.resetDateStringFromYearAndMonth(year: year, month: month, type: type)
            self.dismissDatePicker()
        }
    }
    
    // 消失
    func dismissDatePicker(){
        if let window = cWindow,let datePicker = self.datePicker {
            UIView.animate(withDuration: 0.2, animations: {
                datePicker.frame = CGRect(x: 0, y: window.height, width: window.width, height: 204)
            }) { finished in
                datePicker.removeFromSuperview()
                self.datePicker = nil
            }
        }
    }
}
extension ResourceFilterBoxView : UITableViewDataSource,UITableViewDelegate {
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return tableData.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell: ResourceFilterBoxTableViewCell = tableView.dequeueReusableCell(withIdentifier: "ResourceFilterBoxTableViewCell", for: indexPath) as! ResourceFilterBoxTableViewCell
        cell.cellTag = indexPath.row
        cell.selectButton.setTitle(tableData[indexPath.row], for: .normal)
        cell.callBack = { [weak self] cellTag in
            guard let self = self else { return }
            self.currentSortType = getSortTypeByTag(index: cellTag as! Int)
            self.tableView.reloadData()
        }
        if getSortTypeByTag(index: indexPath.row) == currentSortType {
            cell.selectButton.layer.borderWidth = 1.0
            cell.selectButton.setTitleColor(UIColor(red: 0, green: 0.51, blue: 1, alpha: 1), for: .normal)
        } else {
            cell.selectButton.layer.borderWidth = 0
            cell.selectButton.setTitleColor(UIColor(red: 0.2, green: 0.2, blue: 0.2, alpha: 1), for: .normal)
        }
        return cell
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 56
    }
    
    func getSortTypeByTag(index : Int) -> ResouceSortType {
        if index == 0 {
            return ResouceSortType.largest
        }
        if index == 1 {
            return ResouceSortType.smallest
        }
        if index == 2 {
            return ResouceSortType.latest
        }
        if index == 3 {
            return ResouceSortType.oldest
        }
        return ResouceSortType.largest
    }
}
