import Foundation
import SwiftUI

public struct Checkbox: View{
    @Binding var checked: Bool
    var disabled: Bool
    var onChange: ((Bool)->Void)?
    var indeterminate: Bool
    var title: String


    public init(_ checked: Binding<Bool>,disabled: Bool = false, onChange: ( (Bool) -> Void)? = nil,
                indeterminate: Bool = false,
                title: String = ""){
        self._checked = checked
        self.disabled = disabled
        self.onChange = onChange
        self.indeterminate = indeterminate
        self.title = title
    }

    func onCheck(){
        checked.toggle()
        onChange?(checked)
    }

    public var body: some View {
        HStack(spacing: Spacing.S) {
            // Checkbox
            ZStack {
                RoundedRectangle(cornerRadius: Radius.XS)
                    .fill(backgroundColor)
                    .frame(width: 20, height: 20)
                    .overlay(
                        RoundedRectangle(cornerRadius: Radius.XS)
                            .stroke(borderColor, lineWidth: Spacing.XXS)
                    )

                if checked {
                    Image(systemName: indeterminate ? "minus.square.fill" : "checkmark.square.fill")
                        .resizable()
                        .foregroundColor(backgroundColor)
                        .background(Colors.black01)
                        .frame(width: 20, height: 20)
                }
            }

            .onTapGesture {
                if !disabled {
                    onCheck()
                }
            }

            // Title
            if !title.isEmpty {
                Text(title)
                    .font(.description1)
            }
        }
    }

    private var borderColor: Color {
        if disabled {
            return Colors.black03
        } else if checked {
            return Colors.primary
        } else {
            return Colors.text
        }
    }

    private var backgroundColor: Color {
        if disabled && checked {
            return Colors.pink08
        } else if checked {
            return Colors.primary
        } else {
            return Color.clear
        }
    }
}
