//
//  Selectable.swift
//  PadelClub
//
//  Created by Razmig Sarkissian on 01/04/2024.
//

import Foundation
import SwiftUI
import TipKit

protocol Selectable {
    func selectionLabel(index: Int) -> String
    func badgeValue() -> Int?
    func badgeImage() -> Badge?
    func badgeValueColor() -> Color?
    func displayImageIfValueZero() -> Bool
    func systemImage() -> String?
    func associatedTip() -> (any Tip)?
}

extension Selectable {
    func associatedTip() -> (any Tip)? {
        return nil
    }
    
    func systemImage() -> String? {
        return nil
    }

    func displayImageIfValueZero() -> Bool {
        return false
    }
}

enum Badge {
    case checkmark
    case xmark
    case custom(systemName: String, color: Color)
    
    func systemName() -> String {
        switch self {
        case .checkmark:
            return "checkmark.circle.fill"
        case .xmark:
            return "xmark.circle.fill"
        case .custom(let systemName, _):
            return systemName
        }
    }
    
    func color() -> Color {
        switch self {
        case .checkmark:
            .green
        case .xmark:
            .logoRed
        case .custom(_, let color):
            color
        }
    }
}

struct SelectionTipViewModifier: ViewModifier {
    let selectable: Selectable
    let action: () -> Void
    func body(content: Content) -> some View {
        if let tip = selectable.associatedTip() {
            if #available(iOS 18.0, *) {
                content
                    .popoverTip(tip, arrowEdge: .top) { _ in 
                        action()
                        tip.invalidate(reason: .tipClosed)
                    }
            } else {
                content
            }
        } else {
            content
        }
    }
}

extension View {
    func selectableTipViewModifier(selectable: Selectable, action: @escaping () -> Void) -> some View {
        modifier(SelectionTipViewModifier(selectable: selectable, action: action))
    }
}

