//
//  SpeakCalendarView.swift
//  SpeakEasyLearnEnglish
//
//  Created by edy on 2025/8/1.
//

import UIKit

class CalendarView: UIView, UICollectionViewDelegate, UICollectionViewDataSource , UICollectionViewDelegateFlowLayout{
    
    @IBOutlet var CanlendarWeekLabels: [UILabel]!
    @IBOutlet weak var CanlendarDayView: UICollectionView!
    @IBOutlet weak var CanlendarHeight: NSLayoutConstraint!
    @IBOutlet weak var CanlendarFlowLayout: UICollectionViewFlowLayout!
    
    var WeekStr:[String] = [] {
        didSet{
            var i = 0
            WeekStr.forEach { str in
                CanlendarWeekLabels[safe:i]?.text = str
                i += 1
            }
        }
    }
    
    var signList:[String:[SignListModel]]?
    
    var currentData:Date = Date() {
        didSet{
            loadItemData()
        }
    }
    
    var itemHeight:CGFloat = 50
    
    class func loadNib() -> CalendarView {
        let nib = UINib(nibName: "CalendarView", bundle: nil).instantiate(withOwner: nil).first as! CalendarView
        return nib
    }

    override func awakeFromNib() {
        super.awakeFromNib()
        setup()
        CanlendarWeekLabels.forEach({$0.font = UIFont.montserrat(.medium,size: 14)})
    }
    
    private lazy var backView: UIView = {
        let back = UIView()
        self.addSubview(back)
        return back
    }()
    
    private func setup() -> Void {
        CanlendarFlowLayout.sectionInset = UIEdgeInsets(top: 0, left: 24, bottom: 0, right: 24)
        CanlendarHeight.constant = itemHeight * 6.0
        CanlendarDayView.delegate = self
        CanlendarDayView.dataSource = self;
        CanlendarDayView.showsVerticalScrollIndicator = false
        CanlendarDayView.showsHorizontalScrollIndicator = false
        CanlendarDayView.isScrollEnabled = false
        CanlendarDayView.register(CalendarDayView.self, forCellWithReuseIdentifier: "\(type(of: CalendarDayView.self) )" )
        backView.snp.makeConstraints { make in
            make.left.right.equalToSuperview().inset(24)
            make.top.bottom.equalTo(CanlendarDayView)
        }
    }
    
    override func layoutSubviews() {
        super.layoutSubviews()
        self.layoutIfNeeded()
        backView.corners = 12
        backView.borderColor = .init(hex: 0x3980F6,alpha: 0.2)
        backView.borderWidth = 0.6
    }
    
    private func loadItemData() -> Void {
        let days = currentData.daysOfMonth()
        var day = 1
        let start = currentData.setTm(day: 1).dayOfWeekInt() - 1
        itemDataSource.removeAll()
        for i in 0..<42 {
            if i >= start && day <= days {
                itemDataSource.append("\(day)")
                day += 1
            }else{
                itemDataSource.append("")
            }
        }
        CanlendarDayView.reloadData()
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        guard let call = callblack else { return }
        if let day = itemDataSource[indexPath.row] as? String,
            day.count > 0 ,
            let dnum = Int(day){
            let current = currentData.toStr("yyyy-MM") ?? ""
            call(String(format: "%@-%02d", current,dnum))
        }
    }
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return itemDataSource.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "\(type(of: CalendarDayView.self))", for: indexPath) as! CalendarDayView
        let day = itemDataSource[indexPath.row]
        var icon:UIImage? = nil
        if day != "" {
            let current = currentData.toStr("yyyy-MM") ?? ""
            let curr = String(format: "%@-%02d", current ,Int(day) ?? 01)
            if let sign:[SignListModel] = signList?[current] as? [SignListModel] {
                let ar = sign.filter({$0.signDate == curr})
                if ar.count > 0 {
                    icon = UIImage(named: "icon_sign_fire")
                }
            }
        }
        cell.setdata(day , icon: icon)
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
        return 0
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
        return 0
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        return CGSizeMake((collectionView.width-24.0*2-0.5) / 7.0, itemHeight)
    }
    
    var itemDataSource : [String] = []
    
    deinit {
        callblack = nil
    }
}



class CalendarDayView : UICollectionViewCell {
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setup()
    }
    
    private func setup() -> Void {
        backImage.snp.makeConstraints { make in
            make.left.right.top.bottom.equalToSuperview()
        }
        titleL.snp.makeConstraints { make in
            make.left.right.bottom.equalToSuperview()
            make.top.equalToSuperview().offset(5)
        }
    }
    
    func setdata(_ t:String , icon:UIImage?) -> Void {
        backImage.image = icon
        if icon == nil {
            titleL.textColor = .black
        }else{
            titleL.textColor = .white
        }
        titleL.text = t
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private lazy var titleL: UILabel = {
        let t = UILabel()
        contentView.addSubview(t)
        t.textAlignment = .center
        t.textColor = .black
        t.font = UIFont.montserrat(.semiBold,size: 14)
        return t
    }()
    
    private lazy var backImage: UIImageView = {
        let bgi = UIImageView()
        contentView.addSubview(bgi)
        bgi.contentMode = .center
        return bgi
    }()
}
