//
//  SpeakProgressStudyCell.swift
//  SpeakEasyLearnEnglish
//
//  Created by edy on 2025/7/22.
//

import UIKit

class SpeakProgressStudyCell: UITableViewCell {

    static let id = "SpeakProgressStudyCell"
    
    @IBOutlet weak var SpeakSegmentView: SpeakSegmentTool!
    @IBOutlet weak var SpeakTotalL: UILabel!
    @IBOutlet weak var SpeakAverageL: UILabel!
    @IBOutlet weak var SpeakSegmentChart: UICollectionView!
    @IBOutlet weak var SpeakChartTatalB: UIButton!
    
    var selectIdx:Int = 0 {
        didSet {
            SpeakSegmentView.selectIdx = selectIdx
        }
    }
    
    override func awakeFromNib() {
        super.awakeFromNib()
        setup()
        SpeakSegmentView.callblack = { [weak self] tag in
            guard let call = self?.callblack ,
                let idx = tag as? Int else { return }
            call(idx)
        }
    }
    
    private func setup() -> Void {
        SpeakSegmentView.item = ["Last 3 days","This week","Last week"]
        SpeakSegmentChart.delegate = self
        SpeakSegmentChart.dataSource = self
        SpeakSegmentChart.register(UINib(nibName: SpeakProgressStudySecCell.id, bundle: nil), forCellWithReuseIdentifier: SpeakProgressStudySecCell.id)
    }
    
    var data:[SpeakDayModel] = [] {
        didSet{
            SpeakChartTatalB.setTitle("Target : \(SpeakElePublicManager.share.PublicData.MStudytime)", for: .normal)
            let ddd = data.sorted(by: {$0.studytime ?? 0 > $1.studytime ?? 0})
            maxPro = Double(ddd.first?.studytime ?? 0)
            let all = data.reduce(0) { $0 + ($1.studytime ?? 0) }
            let hour = all / 3600
            let min = (all % 3600) / 60
            SpeakTotalL.text = "\(hour)h \(min)m"
            if data.count > 0 {
                let avg = (all / data.count)
                let hour = avg / 3600
                let min = (avg % 3600) / 60
                SpeakAverageL.text = "\(hour)h \(min)m"
            }
            var count = 0
            for (i,db) in data.enumerated() {
                if let cell = SpeakSegmentChart.cellForItem(at: IndexPath(row: i, section: 0)) as? SpeakProgressStudySecCell{
                    count += 1
                    cell.color = colors[safe:i % 5] ?? .clear
                    let pro:Double = Double(db.studytime ?? 0)
                    cell.progress = (maxPro == 0 ? 0 : pro/maxPro)
                    cell.data = db
                }
            }
//            if count != data.count {
                SpeakSegmentChart.reloadData()
//            }
        }
    }
    
    private var maxPro = 0.0

    private let colors:[UIColor] = [
        .init(hex: 0x0066FF),
        .init(hex: 0xFF7700),
        .init(hex: 0x00BD13),
        .init(hex: 0xFFB200),
        .init(hex: 0xEB3B2F),
    ]
    
    @IBAction func SpeakTargetTaps(_ sender: Any) {
        let more = SpeakProfileMoreViewCtr(state: .Target)
        self.responderCtr()?.navigationController?.pushViewController(more, animated: true)
    }
}
 
extension SpeakProgressStudyCell : UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout {
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return data.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: SpeakProgressStudySecCell.id, for: indexPath) as! SpeakProgressStudySecCell
        let pro:Double = Double(self.data[safe:indexPath.row]?.studytime ?? 0)
        cell.color = colors[safe:indexPath.row % 5] ?? .clear
        cell.progress = (maxPro == 0 ? 0 : pro/maxPro)
        cell.data = self.data[safe:indexPath.row]
        return cell
    }

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
        return 0
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
        return UIEdgeInsets()
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        var width = collectionView.width
        width /= Double(data.count)
        return CGSizeMake(width, collectionView.height)
    }
}
