//
//  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)
                        .sqSize(18)
                        .sqFont(.bold)
                        .foregroundColor(style.foregroundColor)
                }
                if backAction != nil {
                    ToolbarItem(placement: .navigationBarLeading) {
                        if showBackButton {
                            Button(action: {
                                backAction?()
                            }) {
                                style.leadingIcon
                            }
                        }
                    }
                }

                if style == .modal || style == .booster {
                    ToolbarItem(placement: .topBarTrailing) {
                        Button {
                            dismiss()
                        } label: {
                            style.trailingIcon
                        }
                    }
                }
            }
            .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 modal
    case booster
    case boosterFreeTrialResiliation

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

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

    var leadingIcon: SQIcon {
        switch self {
        default: return SQIcon(.chevron_left, size: .l, color: foregroundColor)
        }
    }

    var trailingIcon: SQIcon {
        switch self {
        case .modal, .booster: return .init(.xmark, size: .l, color: foregroundColor)
        default:
            return .init(.xmark, size: .l, color: .clear)
        }
    }
}
