//
//  HomeViewTwo.swift
//  Feels (iOS)
//
//  Created by Trey Tartt on 2/18/22.
//

import SwiftUI

struct MonthView: View {
    @AppStorage(UserDefaultsStore.Keys.needsOnboarding.rawValue, store: GroupUserDefaults.groupDefaults) private var needsOnboarding = true
    
    @AppStorage(UserDefaultsStore.Keys.theme.rawValue, store: GroupUserDefaults.groupDefaults) private var theme: Theme = .system
    
    @AppStorage(UserDefaultsStore.Keys.moodTint.rawValue, store: GroupUserDefaults.groupDefaults) private var moodTint: MoodTints = .Default
    @AppStorage(UserDefaultsStore.Keys.textColor.rawValue, store: GroupUserDefaults.groupDefaults) private var textColor: Color = DefaultTextColor.textColor

    @AppStorage(UserDefaultsStore.Keys.shape.rawValue, store: GroupUserDefaults.groupDefaults) private var shape: BGShape = .circle
    
    @StateObject private var shareImage = StupidAssShareObservableObject()

    // store a value that gets changed when user updates custom colors to update the view since the moodTint doesn't change
    @AppStorage(UserDefaultsStore.Keys.customMoodTintUpdateNumber.rawValue, store: GroupUserDefaults.groupDefaults) private var customMoodTintUpdateNumber: Int = 0
    
    
    @StateObject private var selectedDetail = StupidAssDetailViewObservableObject()
    @State private var showingSheet = false
    @StateObject private var onboardingData = OnboardingDataDataManager.shared
    @StateObject private var filteredDays = DaysFilterClass.shared

    class StupidAssDetailViewObservableObject: ObservableObject {
        @Published var fuckingWrapped: MonthDetailView? = nil
        @Published var showFuckingSheet = false
    }
    
    let columns = [
        GridItem(.flexible(minimum: 5, maximum: 400)),
        GridItem(.flexible(minimum: 5, maximum: 400)),
        GridItem(.flexible(minimum: 5, maximum: 400)),
        GridItem(.flexible(minimum: 5, maximum: 400)),
        GridItem(.flexible(minimum: 5, maximum: 400)),
        GridItem(.flexible(minimum: 5, maximum: 400)),
        GridItem(.flexible(minimum: 5, maximum: 400))
    ]
    
    @ObservedObject var viewModel: DayViewViewModel
    
    var body: some View {
        ZStack {
            if viewModel.hasNoData {
                VStack {
                    Spacer()
                    Text(String(localized: "month_view_no_data"))
                        .font(.title)
                        .padding()
                        .fixedSize(horizontal: false, vertical: true)
                        .foregroundColor(textColor)
                    Spacer()
                }
            } else {
                ScrollView {
                    VStack(spacing: 5) {
                        ForEach(viewModel.grouped.sorted(by: { $0.key < $1.key }), id: \.key) { year, months in
                            
                            // for reach month
                            ForEach(months.sorted(by: { $0.key < $1.key }), id: \.key) { month, entries in
                                Section() {
                                    homeViewTwoMonthListView(month: month, year: year, entries: entries)
                                }
                            }
                            .padding(.bottom)
                        }
                        .padding()
                        .background(
                            RoundedRectangle(cornerRadius: 10)
                                .foregroundColor(
                                    theme.currentTheme.secondaryBGColor
                                )
                        )
                    }
                    .padding([.leading, .trailing])
                }
            }
        }
        .onAppear(perform: {
            EventLogger.log(event: "show_month_view")
        })
        .padding([.top, .bottom])
        .background(
            theme.currentTheme.bg
                .edgesIgnoringSafeArea(.all)
        )
        .sheet(isPresented: $selectedDetail.showFuckingSheet,
                onDismiss: didDismiss) {
            selectedDetail.fuckingWrapped
        }
        .sheet(isPresented: self.$shareImage.showFuckingSheet) {
            if let uiImage = self.shareImage.fuckingWrappedShrable {
                ShareSheet(photo: uiImage)
            }
        }
    }
    
    
    func didDismiss() {
        selectedDetail.showFuckingSheet = false
        selectedDetail.fuckingWrapped = nil
    }
}

extension MonthView {
    private var topView: some View {
        VStack {
            if ShowBasedOnVoteLogics.isMissingCurrentVote(onboardingData: onboardingData.savedOnboardingData) {
                Text("Vote")
            }
            Text("dis top")
                .foregroundColor(theme.currentTheme.secondaryBGColor)
        }
    }
    
    private var settingsButtonView: some View {
        HStack {
            Spacer()
            VStack {
                Button(action: {
                    showingSheet.toggle()
                }, label: {
                    Image(systemName: "gear")
                        .foregroundColor(Color(UIColor.darkGray))
                        .font(.system(size: 20))
                }).sheet(isPresented: $showingSheet) {
                    SettingsView()
                }
                .padding(.top, 60)
                .padding(.trailing)
                Spacer()
            }
        }
    }
}

// view that make up the list body
extension MonthView {
    private func homeViewTwoSectionHeaderView(month: Int, year: Int) -> some View {
        ZStack {
            Text("\(Random.monthName(fromMonthInt: month)) \(String(year))")
                .font(.body)
                .foregroundColor(textColor)
                .frame(maxWidth: .infinity, alignment: .leading)
            Text(String(customMoodTintUpdateNumber))
                .hidden()
        }
    }
    
    private func shareViewImage(month: Int, year: Int, entries: [MoodEntry]) -> some View {
        ZStack {
            VStack {
                HStack {
                    homeViewTwoSectionHeaderView(month: month, year: year)
                }
                Divider()
                LazyVGrid(columns: columns, spacing: 15) {
                    ForEach(entries, id: \.self) { entry in
                        shape.view(withText: Text(""), bgColor: entry.mood == .placeholder ? .clear : moodTint.color(forMood: entry.mood),
                                   textColor: .clear)
                        .frame(minHeight: 25, idealHeight: 25, maxHeight: 50, alignment: .center)
                    }
                }
                Spacer()
            }
            .padding()
            .background(
                RoundedRectangle(cornerRadius: 10)
                    .foregroundColor(
                        theme.currentTheme.secondaryBGColor
                    )
            )
            .padding()
        }
        .background(
            theme.currentTheme.bg
        )
        .padding(.bottom, 55)
    }
    
    private func homeViewTwoMonthListView(month: Int, year: Int, entries: [MoodEntry]) -> some View {
        VStack {
            HStack {
                homeViewTwoSectionHeaderView(month: month, year: year)
                
//                Image(systemName: "square.and.arrow.up")
//                    .foregroundColor(textColor)
//                    .onTapGesture {
//                        let impactMed = UIImpactFeedbackGenerator(style: .heavy)
//                        impactMed.impactOccurred()
//
//                        let _image = shareViewImage(month: month, year: year, entries: entries).asImage(size: CGSize(width: 400, height: 260))
//                        self.shareImage.showFuckingSheet = true
//                        self.shareImage.fuckingWrappedShrable = _image
//                    }
            }
            Divider()
            LazyVGrid(columns: columns, spacing: 15) {
                ForEach(entries, id: \.self) { entry in
                    if filteredDays.currentFilters.contains(Int(entry.weekDay)) {
                        shape.view(withText: Text(""),
                                   bgColor: entry.mood == .placeholder ? .clear : moodTint.color(forMood: entry.mood),
                                   textColor: .clear)
                        .frame(minHeight: 25, idealHeight: 25, maxHeight: 50, alignment: .center)
                    } else {
                        shape.view(withText: Text(""),
                                   bgColor: .clear,
                                   textColor: .clear)
                        .frame(minHeight: 25, idealHeight: 25, maxHeight: 50, alignment: .center)
                    }
                }
            }
        }
        .contentShape(Rectangle())
        .onTapGesture{
            let deailView = MonthDetailView(monthInt: month,
                                            yearInt: year,
                                            entries: entries,
                                            parentViewModel: viewModel)
            
            selectedDetail.fuckingWrapped = deailView
            selectedDetail.showFuckingSheet = true
        }
    }
}

struct HomeViewTwo_Previews: PreviewProvider {
    static var previews: some View {
        MonthView(viewModel: DayViewViewModel(addMonthStartWeekdayPadding: true))
    }
}
