//
//  PollOptionView.swift
//  ComposeUI
//
//  Created by Shadowfacts on 3/25/23.
//

import SwiftUI

struct PollOptionView: View {
    @EnvironmentObject private var controller: PollController
    @EnvironmentObject private var poll: Poll
    @ObservedObject private var option: PollOption
    let remove: () -> Void
    
    init(option: PollOption, remove: @escaping () -> Void) {
        self.option = option
        self.remove = remove
    }
    
    var body: some View {
        HStack(spacing: 4) {
            Checkbox(radiusFraction: poll.multiple ? 0.1 : 0.5, background: controller.parent.config.backgroundColor)
                .animation(.default, value: poll.multiple)
            
            textField
            
            Button(action: remove) {
                Image(systemName: "minus.circle.fill")
            }
            .accessibilityLabel("Remove option")
            .buttonStyle(.plain)
            .foregroundColor(poll.options.count == 1 ? .gray : .red)
            .disabled(poll.options.count == 1)
            .hoverEffect()
        }
    }
    
    private var textField: some View {
        let index = poll.options.index(of: option)
        let placeholder = index != NSNotFound ? "Option \(index + 1)" : ""
        let maxLength = controller.parent.mastodonController.instanceFeatures.maxPollOptionChars
        return EmojiTextField(text: $option.text, placeholder: placeholder, maxLength: maxLength)
    }
    
    struct Checkbox: View {
        private let radiusFraction: CGFloat
        private let size: CGFloat = 20
        private let innerSize: CGFloat
        private let background: Color
        
        init(radiusFraction: CGFloat, background: Color) {
            self.radiusFraction = radiusFraction
            self.innerSize = self.size - 4
            self.background = background
        }
        
        var body: some View {
            ZStack {
                Rectangle()
                    .foregroundColor(.gray)
                    .frame(width: size, height: size)
                    .cornerRadius(radiusFraction * size)
                
                Rectangle()
                    .foregroundColor(background)
                    .frame(width: innerSize, height: innerSize)
                    .cornerRadius(radiusFraction * innerSize)
            }
        }
    }
}
