//
//  HeaderStatsView.swift
//  Reflect
//
//  Created by Trey Tartt on 1/8/22.
//

import SwiftUI
import Charts

struct MoodBarData: Identifiable {
    let id = UUID()
    let mood: Mood
    let count: Int
    let color: Color
}

struct HeaderStatsView: View {
    let barData: [MoodBarData]
    let textColor: Color

    init(fakeData: Bool, backDays: Int, moodTint: [Color], textColor: Color) {
        self.textColor = textColor

        var moodEntries: [MoodEntryModel]?

        if fakeData {
            moodEntries = DataController.shared.randomEntries(count: 10)
        } else {
            guard let daysAgoDate = Calendar.current.date(byAdding: .day, value: -backDays, to: Date()),
                  let daysAgo = Calendar.current.date(bySettingHour: 0, minute: 0, second: 0, of: daysAgoDate) else {
                self.barData = []
                return
            }
            moodEntries = DataController.shared.getData(startDate: daysAgo, endDate: Date(), includedDays: [1,2,3,4,5,6,7])
        }

        var data: [MoodBarData] = []
        if let moodEntries = moodEntries {
            for (index, mood) in Mood.allValues.enumerated() {
                let count = moodEntries.filter { Int($0.moodValue) == mood.rawValue }.count
                let color = index < moodTint.count ? moodTint[index] : .gray
                data.append(MoodBarData(mood: mood, count: count, color: color))
            }
        }
        self.barData = data
    }

    var body: some View {
        Chart(barData) { item in
            BarMark(
                x: .value("Mood", item.mood.widgetDisplayName),
                y: .value("Count", item.count)
            )
            .foregroundStyle(item.color)
            .cornerRadius(10)
            .annotation(position: .top) {
                Text("\(item.count)")
                    .font(.title.bold())
                    .foregroundColor(textColor)
            }
        }
        .chartXAxis(.hidden)
        .chartYAxis(.hidden)
        .chartLegend(.hidden)
        .chartYScale(domain: 0...(maxCount + 1))
    }

    private var maxCount: Int {
        max(barData.map(\.count).max() ?? 1, 1)
    }
}

struct HeaderStatsView_Previews: PreviewProvider {
    static var previews: some View {
        HeaderStatsView(
            fakeData: true,
            backDays: 30,
            moodTint: [Color.green, Color.blue, Color.yellow, Color.red, Color.orange],
            textColor: .white
        )
        .frame(minHeight: 85, maxHeight: 90)
    }
}
