import UIKit
import SwiftUI

enum ColorName: String, CaseIterable {
    enum Variation: String, CaseIterable {
        case primary
        case secondary
        case tertiary
    }
    case text
    case background
    case bannerShade = "banner-shade"
    case shadow
    case tint = "AccentColor"
    case textOnTint = "text-on-tint"
    case separator
    
    internal var hasVariations: Bool {
        switch self {
        case .text, .background:
            return true
        default:
            return false
        }
    }

    var uiColor: UIColor {
        return UIColor(named: name(for: .primary)) ?? .green
    }

    func uiColorForVariation(_ variation: Variation) -> UIColor {
        return UIColor(named: name(for: variation)) ?? .green
    }

    var color: Color {
        return Color(name(for: .primary))
    }
    
    func color(variation: Variation = .primary, colorScheme: ColorScheme? = nil) -> Color {
        let uiColor: UIColor
        if let colorScheme = colorScheme {
            uiColor = uiColorForVariation(variation).resolvedColor(with: colorScheme.traitCollection)
        } else {
            uiColor = uiColorForVariation(variation)
        }
        return Color(uiColor)
    }

    internal func name(for variation: Variation) -> String {
        if !hasVariations {
            return self.rawValue
        }
        return "\(self.rawValue)-\(variation.rawValue)"
    }

    static let allVariations: [String] = {
        var names: [String] = []
        ColorName.allCases.forEach { colorName in
            if colorName.hasVariations {
                Variation.allCases.forEach { variation in
                    names.append(colorName.name(for: variation))
                }
            } else {
                names.append(colorName.rawValue)
            }
        }
        return names
    }()
}

extension ColorScheme {
    var traitCollection: UITraitCollection {
        let userInterfaceStyle: UIUserInterfaceStyle
        
        switch self {
        case .dark:
            userInterfaceStyle = .dark
        case .light:
            userInterfaceStyle = .light
        @unknown default:
            userInterfaceStyle = .unspecified
        }
        return UITraitCollection(userInterfaceStyle: userInterfaceStyle)
    }
}
