//
//  DayFilterPickerView.swift
//  Reflect (iOS)
//
//  Created by Trey Tartt on 4/2/22.
//

import SwiftUI

struct DayFilterPickerView: View {
    @AppStorage(UserDefaultsStore.Keys.theme.rawValue, store: GroupUserDefaults.groupDefaults) private var theme: Theme = .system
    @StateObject private var filteredDays = DaysFilterClass.shared

    private var textColor: Color { theme.currentTheme.labelColor }
    
    let weekdays = [(Calendar.current.shortWeekdaySymbols[0], 1),
                    (Calendar.current.shortWeekdaySymbols[1], 2),
                    (Calendar.current.shortWeekdaySymbols[2], 3),
                    (Calendar.current.shortWeekdaySymbols[3], 4),
                    (Calendar.current.shortWeekdaySymbols[4], 5),
                    (Calendar.current.shortWeekdaySymbols[5], 6),
                    (Calendar.current.shortWeekdaySymbols[6], 7)]
    
    var body: some View {
        VStack {
            HStack {
                ForEach(weekdays.indices, id: \.self) { dayIdx in
                    let day = String(weekdays[dayIdx].0)
                    let value = weekdays[dayIdx].1
                    let isSelected = filteredDays.currentFilters.contains(value)
                    Button(action: {
                        if isSelected {
                            filteredDays.removeFilter(filter: value)
                        } else {
                            filteredDays.addFilter(newFilter: value)
                        }
                        let impactMed = UIImpactFeedbackGenerator(style: .heavy)
                        impactMed.impactOccurred()
                    }) {
                        Text(day.capitalized)
                            .frame(maxWidth: .infinity)
                            .padding(.vertical, 12)
                            .background(Color(uiColor: .tertiarySystemBackground))
                            .foregroundColor(isSelected ? .green : .red)
                            .cornerRadius(8)
                    }
                    .buttonStyle(.plain)
                }
            }
            Text(String(localized: "day_picker_view_text"))
                .padding(.top)
                .foregroundColor(textColor)
        }
        .padding()
        .background(theme.currentTheme.secondaryBGColor)
        .fixedSize(horizontal: false, vertical: true)
        .cornerRadius(Constants.viewsCornerRaidus, corners: [.topLeft, .topRight, .bottomLeft, .bottomRight])
    }
}

struct DayFilterPickerView_Previews: PreviewProvider {
    static var previews: some View {
        DayFilterPickerView()
    }
}
