//
//  ReflectGraphicWidget.swift
//  ReflectWidget
//
//  Graphic mood widget (small only)
//

import WidgetKit
import SwiftUI
import Intents

// MARK: - Widget Configuration

struct ReflectGraphicWidget: Widget {
    let kind: String = "ReflectGraphicWidget"

    var body: some WidgetConfiguration {
        IntentConfiguration(kind: kind,
                            intent: ConfigurationIntent.self,
                            provider: Provider()) { entry in
            ReflectGraphicWidgetEntryView(entry: entry)
        }
                            .configurationDisplayName("Mood Graphic")
                            .description("")
                            .supportedFamilies([.systemSmall])
                            .contentMarginsDisabled()
    }
}

// MARK: - Entry View

struct ReflectGraphicWidgetEntryView: View {
    @Environment(\.sizeCategory) var sizeCategory
    @Environment(\.widgetFamily) var family

    var entry: Provider.Entry

    @ViewBuilder
    var body: some View {
        SmallGraphicWidgetView(entry: entry)
    }
}

// MARK: - Small Graphic Widget View

struct SmallGraphicWidgetView: View {
    var entry: Provider.Entry
    var timeLineView: [WatchTimelineView]

    init(entry: Provider.Entry) {
        self.entry = entry
        let realData = TimeLineCreator.createViews(daysBack: 2)
        // Check if we have any real mood data (not all missing)
        let hasRealData = realData.contains { view in
            let moodTint: MoodTintable.Type = UserDefaultsStore.moodTintable()
            return view.color != moodTint.color(forMood: .missing)
        }
        timeLineView = hasRealData ? realData : TimeLineCreator.createSampleViews(count: 2)
    }

    private var iconViewModel: IconViewModel {
        if let first = timeLineView.first {
            return IconViewModel(backgroundImage: first.graphic,
                                 bgColor: first.color,
                                 bgOverlayColor: first.secondaryColor,
                                 centerImage: first.graphic,
                                 innerColor: first.color)
        } else {
            return IconViewModel.great
        }
    }

    var body: some View {
        Color.clear
            .containerBackground(for: .widget) {
                IconView(iconViewModel: iconViewModel)
            }
    }
}

// MARK: - Previews

#Preview("Graphic - Great", as: .systemSmall) {
    ReflectGraphicWidget()
} timeline: {
    SimpleEntry(
        date: Date(),
        configuration: ConfigurationIntent(),
        timeLineViews: nil,
        hasSubscription: true,
        hasVotedToday: true,
        promptText: ""
    )
}
