//
//  AllMoods.swift
//  Feels (iOS)
//
//  Created by Trey Tartt on 2/6/22.
//

import SwiftUI
import Algorithms

struct LongestStreakTemplate: View, SharingTemplate {
    var image: UIImage {
        return  UIImage(systemName: "square.and.arrow.up")!
    }
    
    static var description: String {
        "Longest Streak"
    }
    
    private let itemFormatter: DateFormatter = {
        let formatter = DateFormatter()
        formatter.dateStyle = .short
        return formatter
    }()
    
    var isPreview: Bool
    var startDate: Date
    var endDate: Date
    var fakeData: Bool
    
    @State var moodEntries = [MoodEntry]()
    @State var selectedMood: Mood = .great
    
    @State var showSharingTemplate = false
    @Environment(\.presentationMode) var presentationMode
    
    
    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)
    ]
    
    init(isPreview: Bool, startDate: Date, endDate: Date, fakeData: Bool) {
        self.isPreview = isPreview
        self.startDate = startDate
        self.endDate = endDate
        self.fakeData = fakeData
        
        configureData(fakeData: self.fakeData, mood: self.selectedMood)
    }
    
    private func configureData(fakeData: Bool, mood: Mood) {
        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])
        }
        let data = _moodEntries ?? [MoodEntry]()
        
        var splitArrays = createSubArrays(fromMoodEntries: data, splitOn: mood)
        splitArrays = splitArrays.sorted(by: {
            $0.count > $1.count
        } )
        self.moodEntries = splitArrays.first ?? [MoodEntry]()
    }
    
    private func createSubArrays(fromMoodEntries: [MoodEntry], splitOn: Mood) -> [[MoodEntry]] {
        var splitArrays = [[MoodEntry]]()
        var currentSplit = [MoodEntry]()
        for entry in fromMoodEntries {
            if entry.mood == splitOn {
                currentSplit.append(entry)
            } else {
                splitArrays.append(currentSplit)
                currentSplit.removeAll()
            }
        }
        // append the last grouping
        splitArrays.append(currentSplit)
        return splitArrays
    }
    
    var preview: some View {
        HStack {
            VStack {
                LazyVGrid(columns: columns, spacing: 0) {
                    ForEach(moodEntries) { entry in
                        entry.mood.icon
                            .resizable()
                            .aspectRatio(contentMode: .fit)
                            .foregroundColor(entry.mood.color)
                    }
                }
            }
        }
        .frame(height: 88)
        .clipped()
        .onAppear(perform: {
            self.configureData(fakeData: self.fakeData, mood: self.selectedMood)
        })
    }
    
    var shareView: some View {
        VStack {
            Text(String(format: String(localized: "share_view_longest_streak_template_title"), self.selectedMood.strValue))
                .font(.title)
                .foregroundColor(Color(UIColor.label))
                .frame(maxWidth: .infinity, alignment: .center)
                .padding()
            
            HStack {
                Text(self.moodEntries.first?.forDate ?? Date(), formatter: itemFormatter)
                    .font(.title)
                    .foregroundColor(Color(UIColor.label))
                    .frame(maxWidth: .infinity, alignment: .center)
                    .padding(.top, 1)
                
                Text("-")
                    .font(.title)
                    .foregroundColor(Color(UIColor.label))
                    .frame(maxWidth: .infinity, alignment: .center)
                    .padding(.top, 1)
                
                Text(self.moodEntries.last?.forDate ?? Date(), formatter: itemFormatter)
                    .font(.title)
                    .foregroundColor(Color(UIColor.label))
                    .frame(maxWidth: .infinity, alignment: .center)
                    .padding(.top, 1)
            }
            .padding()
            
            HStack {
                VStack {
                    LazyVGrid(columns: columns, spacing: 0) {
                        ForEach(moodEntries) { entry in
                            entry.mood.icon
                                .resizable()
                                .aspectRatio(contentMode: .fit)
                                .foregroundColor(entry.mood.color)
                        }
                    }
                }
            }
            .padding()
        }
        .onAppear(perform: {
            self.configureData(fakeData: self.fakeData, mood: self.selectedMood)
        })
    }
    
    var mainView: some View {
        VStack {
            shareView
                .background(Color(UIColor.secondarySystemBackground))
                .cornerRadius(10)
            Spacer()
            Menu(content: {
                ForEach(Mood.allValues) { mood in
                    Button(mood.strValue, action: {
                        selectedMood = mood
                        configureData(fakeData: self.fakeData, mood: self.selectedMood)
                    })
                }
            }, label: {
                Text("Moods")
                    .font(.title)
                    .fontWeight(.bold)
                    .foregroundColor(Color(UIColor.white))
            })
                .frame(maxWidth: .infinity, alignment: .center)
                .background(
                    Color.green
                )
                .padding([.leading, .trailing], -5)
            
            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 CurrentStreakSharingTemplate_Previews: PreviewProvider {
    static var previews: some View {
        LongestStreakTemplate(isPreview: false, startDate: Date(), endDate: Date(), fakeData: true)
        
        LongestStreakTemplate(isPreview: true, startDate: Date(), endDate: Date(), fakeData: true)
    }
}
