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

import UIKit
import Pachyderm

class StatusEditHistoryViewController: UIViewController, CollectionViewController {
    
    private let statusID: String
    private let mastodonController: MastodonController
    
    private var state = State.unloaded
    
    private(set) var collectionView: UICollectionView!
    private var dataSource: UICollectionViewDiffableDataSource<Section, Item>!
    
    init(statusID: String, mastodonController: MastodonController) {
        self.statusID = statusID
        self.mastodonController = mastodonController
        
        super.init(nibName: nil, bundle: nil)
        
        title = "Edit History"
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        var config = UICollectionLayoutListConfiguration(appearance: .grouped)
        config.backgroundColor = .appGroupedBackground
        config.itemSeparatorHandler = { [unowned self] indexPath, sectionConfig in
            guard let item = self.dataSource.itemIdentifier(for: indexPath) else {
                return sectionConfig
            }
            var config = sectionConfig
            if item.hideSeparators {
                config.topSeparatorVisibility = .hidden
                config.bottomSeparatorVisibility = .hidden
            }
            return config
        }
        if let status = mastodonController.persistentContainer.status(for: statusID),
           status.url?.host != mastodonController.instanceURL.host {
            config.footerMode = .supplementary
        }
        let layout = UICollectionViewCompositionalLayout { sectionIndex, environment in
            let section = NSCollectionLayoutSection.list(using: config, layoutEnvironment: environment)
            section.readableContentInset(in: environment)
            return section
        }
        collectionView = UICollectionView(frame: .zero, collectionViewLayout: layout)
        collectionView.delegate = self
        collectionView.translatesAutoresizingMaskIntoConstraints = false
        view.addSubview(collectionView)
        NSLayoutConstraint.activate([
            collectionView.leadingAnchor.constraint(equalTo: view.leadingAnchor),
            collectionView.trailingAnchor.constraint(equalTo: view.trailingAnchor),
            collectionView.topAnchor.constraint(equalTo: view.topAnchor),
            collectionView.bottomAnchor.constraint(equalTo: view.bottomAnchor),
        ])
        
        dataSource = createDataSource()
    }
    
    private func createDataSource() -> UICollectionViewDiffableDataSource<Section, Item> {
        let editCell = UICollectionView.CellRegistration<StatusEditCollectionViewCell, (StatusEdit, CollapseState, Int)> { [unowned self] cell, indexPath, itemIdentifier in
            cell.delegate = self
            cell.updateUI(edit: itemIdentifier.0, state: itemIdentifier.1, index: itemIdentifier.2)
        }
        let loadingCell = UICollectionView.CellRegistration<LoadingCollectionViewCell, Void> { cell, indexPath, itemIdentifier in
            cell.indicator.startAnimating()
        }
        let dataSource = UICollectionViewDiffableDataSource<Section, Item>(collectionView: collectionView) { collectionView, indexPath, itemIdentifier in
            switch itemIdentifier {
            case .edit(let edit, let state, index: let index):
                return collectionView.dequeueConfiguredReusableCell(using: editCell, for: indexPath, item: (edit, state, index))
            case .loadingIndicator:
                return collectionView.dequeueConfiguredReusableCell(using: loadingCell, for: indexPath, item: ())
            }
        }
        let footerCell = UICollectionView.SupplementaryRegistration<UICollectionViewListCell>(elementKind: UICollectionView.elementKindSectionFooter) { supplementaryView, elementKind, indexPath in
            var config = supplementaryView.defaultContentConfiguration()
            config.text = "Edit history for posts originating from instances other than your own may not be complete."
            supplementaryView.contentConfiguration = config
        }
        dataSource.supplementaryViewProvider = { collectionView, elementKind, indexPath in
            return collectionView.dequeueConfiguredReusableSupplementary(using: footerCell, for: indexPath)
        }
        return dataSource
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        
        clearSelectionOnAppear(animated: animated)
        
        if case .unloaded = state {
            Task {
                await load()
            }
        }
    }
    
    private func load() async {
        guard case .unloaded = state else {
            return
        }
        state = .loading
        
        var snapshot = NSDiffableDataSourceSnapshot<Section, Item>()
        snapshot.appendSections([.edits])
        snapshot.appendItems([.loadingIndicator])
        await apply(snapshot)
        
        let req = Status.history(statusID)
        do {
            let (edits, _) = try await mastodonController.run(req)
            
            var snapshot = NSDiffableDataSourceSnapshot<Section, Item>()
            snapshot.appendSections([.edits])
            // show them in reverse chronological order
            snapshot.appendItems(edits.reversed().enumerated().map {
                .edit($1, .unknown, index: $0)
            })
            await apply(snapshot)
            
            state = .loaded
            
        } catch {
            state = .unloaded
            let config = ToastConfiguration(from: error, with: "Error Loading Edits", in: self) { [weak self] toast in
                toast.dismissToast(animated: true)
                await self?.load()
            }
            self.showToast(configuration: config, animated: true)
        }
    }
    
    private func apply(_ snapshot: NSDiffableDataSourceSnapshot<Section, Item>) async {
        await MainActor.run {
            self.dataSource.apply(snapshot)
        }
    }
    
    enum State {
        case unloaded
        case loading
        case loaded
    }
}

extension StatusEditHistoryViewController {
    enum Section {
        case edits
    }
    enum Item: Hashable, Equatable {
        case edit(StatusEdit, CollapseState, index: Int)
        case loadingIndicator
        
        static func ==(lhs: Item, rhs: Item) -> Bool {
            switch (lhs, rhs) {
            case (.edit(_, _, let a), .edit(_, _, let b)):
                return a == b
            case (.loadingIndicator, .loadingIndicator):
                return true
            default:
                return false
            }
        }
        
        func hash(into hasher: inout Hasher) {
            switch self {
            case .edit(_, _, index: let index):
                hasher.combine(0)
                hasher.combine(index)
            case .loadingIndicator:
                hasher.combine(1)
            }
        }
        
        var hideSeparators: Bool {
            switch self {
            case .loadingIndicator:
                return true
            default:
                return false
            }
        }
    }
}

extension StatusEditHistoryViewController: UICollectionViewDelegate {
    func collectionView(_ collectionView: UICollectionView, shouldSelectItemAt indexPath: IndexPath) -> Bool {
        return false
    }
}

extension StatusEditHistoryViewController: TuskerNavigationDelegate {
    nonisolated var apiController: MastodonController! { mastodonController }
}

extension StatusEditHistoryViewController: StatusEditCollectionViewCellDelegate {
    func statusEditCellNeedsReconfigure(_ cell: StatusEditCollectionViewCell, animated: Bool, completion: (() -> Void)?) {
        if let indexPath = collectionView.indexPath(for: cell) {
            var snapshot = dataSource.snapshot()
            snapshot.reconfigureItems([dataSource.itemIdentifier(for: indexPath)!])
            dataSource.apply(snapshot, animatingDifferences: animated, completion: completion)
        }
    }
}
