//
//  PollOptionView.swift
//  Tusker
//
//  Created by Shadowfacts on 4/25/21.
//  Copyright © 2021 Shadowfacts. All rights reserved.
//

import UIKit
import Pachyderm

class PollOptionView: UIView {
    
    private static let minHeight: CGFloat = 35
    private static let cornerRadius = 0.1 * minHeight
    private static let unselectedBackgroundColor = UIColor(white: 0.5, alpha: 0.25)
    
    private(set) var label: EmojiLabel!
    @Lazy private var checkbox: PollOptionCheckboxView = PollOptionCheckboxView().configure {
        $0.translatesAutoresizingMaskIntoConstraints = false
    }
    var checkboxIfInitialized: PollOptionCheckboxView? {
        _checkbox.valueIfInitialized
    }
    private var percentLabel: UILabel!
    @Lazy private var fillView: UIView = UIView().configure {
        $0.translatesAutoresizingMaskIntoConstraints = false
        $0.backgroundColor = .tintColor.withAlphaComponent(0.6)
        $0.layer.zPosition = -1
        $0.layer.cornerRadius = PollOptionView.cornerRadius
        $0.layer.cornerCurve = .continuous
    }
    private var labelLeadingToSelfConstraint: NSLayoutConstraint!
    private var fillViewWidthConstraint: NSLayoutConstraint?
    
    init() {
        super.init(frame: .zero)
        
        layer.cornerRadius = PollOptionView.cornerRadius
        layer.cornerCurve = .continuous
        backgroundColor = PollOptionView.unselectedBackgroundColor
        
        label = EmojiLabel()
        label.translatesAutoresizingMaskIntoConstraints = false
        label.numberOfLines = 0
        label.font = .preferredFont(forTextStyle: .callout)
        addSubview(label)
        labelLeadingToSelfConstraint = label.leadingAnchor.constraint(equalTo: leadingAnchor, constant: 8)
        
        percentLabel = UILabel()
        percentLabel.translatesAutoresizingMaskIntoConstraints = false
        percentLabel.text = "100%"
        percentLabel.font = label.font
        percentLabel.isHidden = true
        percentLabel.setContentCompressionResistancePriority(.required, for: .horizontal)
        percentLabel.setContentHuggingPriority(.required, for: .horizontal)
        addSubview(percentLabel)
        
        NSLayoutConstraint.activate([
            heightAnchor.constraint(greaterThanOrEqualToConstant: PollOptionView.minHeight),

            label.topAnchor.constraint(equalTo: topAnchor, constant: 4),
            label.bottomAnchor.constraint(equalTo: bottomAnchor, constant: -4),
            label.trailingAnchor.constraint(equalTo: percentLabel.leadingAnchor, constant: -4),

            percentLabel.topAnchor.constraint(equalTo: topAnchor),
            percentLabel.bottomAnchor.constraint(equalTo: bottomAnchor),
            percentLabel.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -8),
        ])
        
        isAccessibilityElement = true
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    func updateUI(poll: Poll, option: Poll.Option, ownVoted: Bool, mastodonController: MastodonController) {
        let showCheckbox = poll.ownVotes?.isEmpty == false || !poll.effectiveExpired
        if showCheckbox {
            checkbox.isChecked = ownVoted
            checkbox.voted = poll.voted ?? false
            
            labelLeadingToSelfConstraint.isActive = false
            if checkbox.superview != self {
                addSubview(checkbox)
                NSLayoutConstraint.activate([
                    checkbox.centerYAnchor.constraint(equalTo: centerYAnchor),
                    checkbox.leadingAnchor.constraint(equalTo: leadingAnchor, constant: 8),
                    label.leadingAnchor.constraint(equalTo: checkbox.trailingAnchor, constant: 8),
                ])
            }
        } else if !showCheckbox {
            labelLeadingToSelfConstraint.isActive = true
            _checkbox.valueIfInitialized?.removeFromSuperview()
        }
        
        label.text = option.title
        label.setEmojis(poll.emojis, identifier: poll.id)
        
        accessibilityLabel = option.title
        
        if (poll.voted ?? false) || poll.effectiveExpired,
           let optionVotes = option.votesCount {
            let frac: CGFloat
            if poll.multiple,
               let votersCount = poll.votersCount,
               mastodonController.instanceFeatures.pollVotersCount {
                frac = votersCount == 0 ? 0 : CGFloat(optionVotes) / CGFloat(votersCount)
            } else {
                frac = poll.votesCount == 0 ? 0 : CGFloat(optionVotes) / CGFloat(poll.votesCount)
            }
            let percent = String(format: "%.0f%%", frac * 100)

            percentLabel.isHidden = false
            percentLabel.text = percent

            if fillView.superview != self {
                addSubview(fillView)
                NSLayoutConstraint.activate([
                    fillView.leadingAnchor.constraint(equalTo: leadingAnchor),
                    fillView.topAnchor.constraint(equalTo: topAnchor),
                    fillView.bottomAnchor.constraint(equalTo: bottomAnchor),
                ])
            }
            fillViewWidthConstraint?.isActive = false
            fillViewWidthConstraint = fillView.widthAnchor.constraint(equalTo: widthAnchor, multiplier: frac)
            fillViewWidthConstraint!.isActive = true

            accessibilityLabel! += ", \(percent)"
        } else {
            percentLabel.isHidden = true
            _fillView.valueIfInitialized?.removeFromSuperview()
        }
    }
    
}
