//
//  RouletteSettingsOptionView.swift
//  SodaLive
//
//  Created by klaus on 2023/12/05.
//

import SwiftUI

struct RouletteSettingsOptionView: View {
    
    @ObservedObject var option: RouletteOption
    
    let index: Int
    let onClickDelete: () -> Void
    let calculateTotalPercentage: () -> Void
    
    var body: some View {
        VStack(spacing: 6.7) {
            HStack(spacing: 0) {
                Text("옵션 \(index + 1)")
                    .font(.custom(Font.medium.rawValue, size: 14.7))
                    .foregroundColor(Color(hex: "eeeeee"))
                
                Spacer()
                
                if index > 1 {
                    Text("삭제")
                        .font(.custom(Font.medium.rawValue, size: 14.7))
                        .foregroundColor(Color(hex: "ff5c49"))
                        .onTapGesture { onClickDelete() }
                }
            }
            
            HStack(spacing: 8) {
                TextField("옵션을 입력하세요", text: $option.title)
                    .autocapitalization(.none)
                    .disableAutocorrection(true)
                    .font(.custom(Font.medium.rawValue, size: 13.3))
                    .foregroundColor(Color(hex: "eeeeee"))
                    .keyboardType(.default)
                    .padding(.horizontal, 13.3)
                    .padding(.vertical, 16.7)
                    .frame(maxWidth: .infinity)
                    .background(Color(hex: "222222"))
                    .cornerRadius(6.7)
                
                HStack(spacing: 0) {
                    TextField("0.00", text: $option.percentage)
                    .autocapitalization(.none)
                    .disableAutocorrection(true)
                    .font(.custom(Font.medium.rawValue, size: 13.3))
                    .foregroundColor(Color(hex: "eeeeee"))
                    .keyboardType(.decimalPad)
                    .onChange(of: option.percentage) { newValue in
                        if newValue.count > 5 {
                            option.percentage = String(newValue.prefix(5))
                        }
                        
                        calculateTotalPercentage()
                    }
                    
                    Text("%")
                        .font(.custom(Font.medium.rawValue, size: 13.3))
                        .foregroundColor(Color(hex: "eeeeee"))
                }
                .padding(.horizontal, 13.3)
                .padding(.vertical, 16.7)
                .frame(maxWidth: 85)
                .background(Color(hex: "222222"))
                .cornerRadius(6.7)
            }
        }
    }
}

struct RouletteSettingsOptionView_Previews: PreviewProvider {
    static var previews: some View {
        RouletteSettingsOptionView(
            option: RouletteOption(title: "옵션1", percentage: ""),
            index: 2,
            onClickDelete: {},
            calculateTotalPercentage: {}
        )
    }
}
