//
//  IconViewController.swift
//  VDSSample
//
//  Created by Matt Bruce on 1/9/23.
//

import Foundation
import UIKit
import VDS
import VDSColorTokens
import Combine

class IconViewController: BaseViewController<Icon> {
    
    lazy var colorPickerSelectorView = {
        PickerSelectorView(title: "",
                           picker: self.picker,
                           items: UIColor.VDSColor.allCases)
    }()
    
    lazy var namePickerSelectorView = {
        PickerSelectorView(title: "",
                           picker: self.picker,
                           items: Icon.Name.all.sorted{ $0.rawValue < $1.rawValue })
    }()
    
    lazy var sizePickerSelectorView = {
        PickerSelectorView(title: "",
                           picker: self.picker,
                           items: Icon.Size.allCases)
    }()
    
    var customSizeField = TextField()
    
    override func allTextFields() -> [TextField]? { [customSizeField] }

    override func viewDidLoad() {
        super.viewDidLoad()
        addContentTopView(view: .makeWrapper(for: component))
        setupPicker()
        setupModel()
    }
    
    override func setupForm(){
        super.setupForm()  
        addFormRow(label: "Surface", view: surfacePickerSelectorView)
        addFormRow(label: "Size", view: sizePickerSelectorView)
        addFormRow(label: "Custom Size", view: customSizeField)
        addFormRow(label: "Color", view: colorPickerSelectorView)
        addFormRow(label: "Name", view: namePickerSelectorView)
        
        customSizeField.textPublisher.sink { [weak self] value in
            if let intValue = Int(value) {
                self?.component.customSize = intValue
            } else if value.isEmpty {
                self?.component.customSize = nil
            }
        }.store(in: &subscribers)
    }
    
    func setupModel() {
        let name = Icon.Name.accessibility
        let color = UIColor.VDSColor.paletteBlack
        component.color = color.uiColor
        component.name = name
        
        //setup UI
        surfacePickerSelectorView.text = component.surface.rawValue
        sizePickerSelectorView.text = component.size.rawValue
        colorPickerSelectorView.text = color.rawValue
        namePickerSelectorView.text = name.rawValue
    }
    func setupPicker(){

        surfacePickerSelectorView.onPickerDidSelect = {  [weak self] item in
            self?.component.surface = item
            self?.contentTopView.backgroundColor = item.color
        }
        
        sizePickerSelectorView.onPickerDidSelect = {  [weak self] item in
            self?.component.size = item
        }
        
        colorPickerSelectorView.onPickerDidSelect = {  [weak self] item in
            self?.component.color = item.uiColor
        }
        
        namePickerSelectorView.onPickerDidSelect = {  [weak self] item in
            self?.component.name = item
        }
    }
}
