//
//  MonthTotalTemplate.swift
//  Feels (iOS)
//
//  Created by Trey Tartt on 2/9/22.
//

import SwiftUI

struct MonthTotalTemplate: View, SharingTemplate {
    static var description: String {
        "This Month"
    }
    
    var isPreview: Bool
    var startDate: Date
    var endDate: Date
    var totalEntryCount: Int = 0
    
    private var month = Calendar.current.dateComponents([.month], from: Date()).month!
    
    @State var showSharingTemplate = false
    @Environment(\.presentationMode) var presentationMode
    
    private var moodMetrics = [MoodMetrics]()
    private var moodEntries = [MoodEntry]()
    
    let columns = [
        GridItem(.flexible(minimum: 5, maximum: .infinity), alignment: .center),
        GridItem(.flexible(minimum: 5, maximum: .infinity), alignment: .center),
        GridItem(.flexible(minimum: 5, maximum: .infinity), alignment: .center),
        GridItem(.flexible(minimum: 5, maximum: .infinity), alignment: .center),
        GridItem(.flexible(minimum: 5, maximum: .infinity), alignment: .center),
        GridItem(.flexible(minimum: 5, maximum: .infinity), alignment: .center),
        GridItem(.flexible(minimum: 5, maximum: .infinity), alignment: .center)
    ]
    
    init(isPreview: Bool, startDate: Date, endDate: Date, fakeData: Bool) {
        self.isPreview = isPreview
        self.startDate = startDate
        self.endDate = endDate
        
        var _moodEntries: [MoodEntry]?
        
        if fakeData {
            _moodEntries = PersistenceController.shared.randomEntries(count: 10)
        } else {
            
            _moodEntries = PersistenceController.shared.getData(startDate: startDate,
                                                                endDate: endDate,
                                                                includedDays: [1,2,3,4,5,6,7])
            
            //            _moodEntries = PersistenceController.shared.getData(startDate:Calendar.current.date(byAdding: .day, value: -33, to: Date())!,
            //                                                                endDate: Date(),
            //                                                                includedDays: [1,2,3,4,5,6,7])
            
        }
        
        moodEntries = _moodEntries ?? [MoodEntry]()
        
        totalEntryCount = moodEntries.count
        
        for (_, mood) in Mood.allValues.enumerated() {
            let moodEntries = moodEntries.filter({
                Int($0.moodValue) == mood.rawValue
            })
            let total = moodEntries.count
            let perc = (Float(total) / Float(totalEntryCount)) * 100
            moodMetrics.append(MoodMetrics(mood: mood, total: total, percent: perc))
        }
        
        moodMetrics = moodMetrics.sorted(by: {
            $0.mood.rawValue > $1.mood.rawValue
        })
    }
    
    var image: UIImage {
        let image = shareView.snapshot()
        return image
    }
    
    var preview: some View {
        circularViews
            .frame(maxWidth: .infinity, alignment: .center)
            .frame(height: 100)
    }
    
    private var circularViews: some View {
        HStack {
            ForEach(moodMetrics, id: \.mood) { model in
                ZStack {
                    Circle().fill(model.mood.color)
                    
                    Text("\(model.percent, specifier: "%.0f")%")
                        .font(.title)
                        .fontWeight(.bold)
                        .minimumScaleFactor(0.5)
                        .lineLimit(1)
                        .foregroundColor(Color(UIColor.white))
                        .padding(5)
                }
                .frame(maxWidth: .infinity, alignment: .center)
                .frame(height: 100)
            }
        }
    }
    
    var shareView: some View {
        VStack {
            Text(String(format: String(localized: "share_view_month_moods_total_template_title"), Random.monthName(fromMonthInt: month), moodEntries.count))
                .font(.title)
                .foregroundColor(Color(UIColor.label))
                .frame(maxWidth: .infinity, alignment: .center)
                .padding()
            
            VStack {
                LazyVGrid(columns: columns, spacing: 10) {
                    ForEach(moodEntries) { entry in
                        entry.mood.icon
                            .resizable()
                            .aspectRatio(contentMode: .fit)
                            .foregroundColor(entry.mood.color)
                    }
                }
            }
            .padding()
            
            circularViews
                .padding([.trailing, .leading, .top])
        }
    }
    
    var mainView: some View {
        VStack {
            shareView
                .background(Color(UIColor.secondarySystemBackground))
                .cornerRadius(10)
            Spacer()
            HStack(alignment: .center) {
                Button(action: {
                    showSharingTemplate = true
                }, label: {
                    Text("Share")
                        .font(.title)
                        .fontWeight(.bold)
                        .foregroundColor(Color.white)
                        .padding(.top, 20)
                })
                    .frame(maxWidth: .infinity, alignment: .center)
                    .background(
                        Color.green
                    )
                    .padding(.trailing, -5)
                
                Button(action: {
                    presentationMode.wrappedValue.dismiss()
                }, label: {
                    Text("Exit")
                        .font(.title)
                        .fontWeight(.bold)
                        .foregroundColor(Color.white)
                        .padding(.top, 20)
                })
                    .frame(maxWidth: .infinity, alignment: .center)
                    .background(
                        Color.red
                    )
                    .padding(.leading, -5)
            }
            .padding([.leading, .trailing], -20)
        }.sheet(isPresented: $showSharingTemplate) {
            ActivityViewController(activityItems: [self.image])
        }
    }
    
    var body: some View {
        if isPreview {
            preview
                .padding([.leading, .trailing], -20)
        } else {
            mainView
                .padding([.leading, .trailing])
        }
    }
}

struct MonthTotalTemplate_Previews: PreviewProvider {
    static var previews: some View {
        MonthTotalTemplate(isPreview: true, startDate: Date().startOfMonth(), endDate: Date().endOfMonth(), fakeData: true)
        
        MonthTotalTemplate(isPreview: false, startDate: Date().startOfMonth(), endDate: Date().endOfMonth(), fakeData: true)
    }
}
