//
//  FollowNotificationGroupCollectionViewCell.swift
//  Tusker
//
//  Created by Shadowfacts on 5/7/23.
//  Copyright © 2023 Shadowfacts. All rights reserved.
//

import UIKit
import Pachyderm

class FollowNotificationGroupCollectionViewCell: UICollectionViewListCell {
    
    private let iconView = UIImageView(image: UIImage(systemName: "person.fill.badge.plus")).configure {
        $0.contentMode = .scaleAspectFit
        NSLayoutConstraint.activate([
            $0.heightAnchor.constraint(equalToConstant: 30),
            $0.widthAnchor.constraint(equalToConstant: 30),
        ])
    }
    
    private let avatarStack = UIStackView().configure {
        $0.axis = .horizontal
        $0.alignment = .fill
        $0.spacing = 8
    }
    
    private let timestampLabel = UILabel().configure {
        $0.textColor = .secondaryLabel
        $0.font = UIFont(descriptor: .preferredFontDescriptor(withTextStyle: .body).addingAttributes([
            .traits: [
                UIFontDescriptor.TraitKey.weight: UIFont.Weight.light.rawValue,
            ]
        ]), size: 0)
        $0.adjustsFontForContentSizeCategory = true
    }
    
    private lazy var hStack = UIStackView(arrangedSubviews: [
        avatarStack,
        UIView().configure {
            $0.backgroundColor = .clear
            $0.setContentHuggingPriority(.init(249), for: .horizontal)
        },
        timestampLabel,
    ]).configure {
        $0.axis = .horizontal
        $0.alignment = .fill
        $0.heightAnchor.constraint(equalToConstant: 30).isActive = true
    }
    
    private lazy var actionLabel = MultiSourceEmojiLabel().configure {
        $0.font = .preferredFont(forTextStyle: .body)
        $0.adjustsFontForContentSizeCategory = true
        $0.numberOfLines = 2
        $0.lineBreakMode = .byTruncatingTail
        $0.combiner = { [unowned self] in self.updateActionLabel(names: $0) }
    }
    
    private lazy var vStack = UIStackView(arrangedSubviews: [
        hStack,
        actionLabel,
    ]).configure {
        $0.axis = .vertical
        $0.alignment = .fill
    }
    
    weak var delegate: (TuskerNavigationDelegate & MenuActionProvider)?
    private var mastodonController: MastodonController { delegate!.apiController }
    
    private var group: NotificationGroup!
    
    private var updateTimestampWorkItem: DispatchWorkItem?
    
    deinit {
        updateTimestampWorkItem?.cancel()
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        iconView.translatesAutoresizingMaskIntoConstraints = false
        contentView.addSubview(iconView)
        vStack.translatesAutoresizingMaskIntoConstraints = false
        contentView.addSubview(vStack)
        NSLayoutConstraint.activate([
            iconView.topAnchor.constraint(equalTo: vStack.topAnchor),
            iconView.trailingAnchor.constraint(equalTo: contentView.leadingAnchor, constant: 16 + 50),
            
            vStack.leadingAnchor.constraint(equalTo: iconView.trailingAnchor, constant: 8),
            vStack.trailingAnchor.constraint(equalTo: contentView.trailingAnchor, constant: -16),
            vStack.topAnchor.constraint(equalTo: contentView.topAnchor, constant: 8),
            vStack.bottomAnchor.constraint(equalTo: contentView.bottomAnchor, constant: -8),
        ])
        
        NotificationCenter.default.addObserver(self, selector: #selector(updateUIForPreferences), name: .preferencesChanged, object: nil)
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func updateConfiguration(using state: UICellConfigurationState) {
        backgroundConfiguration = .appListPlainCell(for: state)
    }
    
    func updateUI(group: NotificationGroup) {
        guard group.kind == .follow else {
            fatalError()
        }
        self.group = group
        
        let people = group.notifications.compactMap { mastodonController.persistentContainer.account(for: $0.account.id) }

        actionLabel.setEmojis(pairs: people.map {
            ($0.displayOrUserName, $0.emojis)
        }, identifier: group.id)
        updateTimestamp()
        
        let visibleAvatars = Array(people.lazy.compactMap(\.avatar).prefix(10))
        for (index, avatarURL) in visibleAvatars.enumerated() {
            let imageView: CachedImageView
            if index < avatarStack.arrangedSubviews.count {
                imageView = avatarStack.arrangedSubviews[index] as! CachedImageView
            } else {
                imageView = CachedImageView(cache: .avatars)
                imageView.contentMode = .scaleAspectFill
                imageView.layer.masksToBounds = true
                imageView.layer.cornerRadius = Preferences.shared.avatarStyle.cornerRadiusFraction * 30
                imageView.layer.cornerCurve = .continuous
                avatarStack.addArrangedSubview(imageView)
                imageView.widthAnchor.constraint(equalTo: imageView.heightAnchor).isActive = true
            }
            imageView.update(for: avatarURL)
        }
        while avatarStack.arrangedSubviews.count > visibleAvatars.count {
            avatarStack.arrangedSubviews.last!.removeFromSuperview()
        }
    }
    
    private func updateActionLabel(names: [NSAttributedString]) -> NSAttributedString {
        // todo: figure out how to localize this
        let str = NSMutableAttributedString(string: "Followed by ")
        switch names.count {
        case 1:
            str.append(names.first!)
        case 2:
            str.append(names.first!)
            str.append(NSAttributedString(string: " and "))
            str.append(names.last!)
        default:
            for (index, name) in names.enumerated() {
                str.append(name)
                if index < names.count - 2 {
                    str.append(NSAttributedString(string: ", "))
                } else if index == names.count - 2 {
                    str.append(NSAttributedString(string: ", and "))
                }
            }
        }
        return str
    }
    
    @objc private func updateUIForPreferences() {
        for view in avatarStack.arrangedSubviews {
            view.layer.cornerRadius = Preferences.shared.avatarStyle.cornerRadius(for: view)
        }
    }
    
    private func updateTimestamp() {
        guard let notification = group.notifications.first else {
                fatalError("Missing cached notification")
        }
        
        timestampLabel.text = notification.createdAt.timeAgoString()
        
        let delay: DispatchTimeInterval?
        switch notification.createdAt.timeAgo().1 {
        case .second:
            delay = .seconds(10)
        case .minute:
            delay = .seconds(60)
        default:
            delay = nil
        }
        if let delay = delay {
            if updateTimestampWorkItem == nil {
                updateTimestampWorkItem = DispatchWorkItem { [weak self] in
                    self?.updateTimestamp()
                }
            }
            DispatchQueue.main.asyncAfter(deadline: .now() + delay, execute: updateTimestampWorkItem!)
        } else {
            updateTimestampWorkItem = nil
        }
    }
    
    override func prepareForReuse() {
        super.prepareForReuse()
        updateTimestampWorkItem?.cancel()
    }
    
    // MARK: Accessibility
    
    override var accessibilityLabel: String? {
        get {
            let first = group.notifications.first!
            var str = "Followed by "
            str += first.account.displayNameWithoutCustomEmoji
            if group.notifications.count > 1 {
                str += " and \(group.notifications.count - 1) more"
            }
            str += ", \(first.createdAt.formatted(.relative(presentation: .numeric)))"
            return str
        }
        set {}
    }

}
