//
//  SQNavigationBar.swift
//  AlloVoisinsSwiftUI
//
//  Created by Victor on 14/10/2024.
//

import SwiftUI

struct SQNavigationBar: ViewModifier {
    @Environment(\.dismiss) private var dismiss
    let title: String
    let style: SQNavigationBarStyle
    let showBackButton: Bool
    let backAction: (() -> Void)?

    func body(content: Content) -> some View {
        content
            .navigationBarTitleDisplayMode(.inline)
            .toolbar {
                ToolbarItem(placement: .principal) {
                    SQText(title, size: 18, font: .bold)
                        .foregroundColor(style.foregroundColor)
                }
                if backAction != nil {
                    ToolbarItem(placement: .navigationBarLeading) {
                        if showBackButton {
                            Button(action: {
                                backAction?()
                            }) {
                                style.closeIcon
                            }
                        }
                    }
                } else {
                    if showBackButton {
                        ToolbarItem(placement: .navigationBarLeading) {
                            Button(action: {
                                dismiss()
                            }) {
                                style.closeIcon
                            }
                        }
                    }
                }
            }
            .toolbarBackground(style.backgroundColor, for: .navigationBar)
            .toolbarBackground(.visible, for: .navigationBar)
            .navigationBarBackButtonHidden()
    }
}

extension View {
    func sqNavigationBar(title: String, style: SQNavigationBarStyle = .white, showBackButton: Bool = true, backAction: (() -> Void)? = nil) -> some View {
        modifier(SQNavigationBar(title: title, style: style, showBackButton: showBackButton, backAction: backAction))
    }
}

enum SQNavigationBarStyle {
    case white
    case booster
    case boosterFreeTrialResiliation

    var backgroundColor: Color {
        switch self {
        case .white: return .white
        case .booster: return .sqRoyal(60)
        case .boosterFreeTrialResiliation: return .sqRoyal(60)
        }
    }

    var foregroundColor: Color {
        switch self {
        case .white: return .sqNeutral(100)
        case .booster: return .white
        case .boosterFreeTrialResiliation: return .white
        }
    }

    var closeIcon: SQIcon {
        switch self {
        case .white: return SQIcon(.chevron_left, size: .l, color: foregroundColor)
        case .booster: return SQIcon(.xmark, size: .l, color: foregroundColor)
        case .boosterFreeTrialResiliation: return SQIcon(.chevron_left, size: .l, color: foregroundColor)
        }
    }
}
