//
//  MenuViewController.swift
//  VDSSample
//
//  Created by Matt Bruce on 8/1/22.
//

import Foundation
import UIKit
import VDS
import VDSColorTokens

struct MenuComponent {
    var title: String
    var completed: Bool
    var viewController: UIViewController.Type
}

protocol Initable {
    init()
}

class MenuCell: UITableViewCell {
    var completed: Bool = true {
        didSet {
            if completed {
                statusImage.image = UIImage(systemName: "checkmark.circle")
                statusImage.tintColor = VDSColor.paletteGreen26
            } else {
                statusImage.image = UIImage(systemName: "xmark.circle")
                statusImage.tintColor = VDSColor.paletteRed
            }
        }
    }

    var statusImage = UIImageView().with {
        $0.translatesAutoresizingMaskIntoConstraints = false
    }
    var label = Label().with {
        $0.textStyle = .bodyLarge
    }

    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        setup()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    func setup(){
        addSubview(statusImage)
        addSubview(label)
        statusImage.pinLeading(16)
        label.pinLeading(statusImage.trailingAnchor, 10)
        label.pinTop()
        label.pinBottom()
        label.pinTrailing()
        statusImage.width(20)
        statusImage.height(20)
        statusImage.centerYAnchor.constraint(equalTo: centerYAnchor).isActive = true
    }
}

class MenuViewController: UITableViewController, TooltipLaunchable {
    override func viewDidLoad() {
        title = "VDS Sample: Build \(Bundle.main.build ?? "none")"
        let tooltip =  VDS.Tooltip()
        let bundle = VDS.Bundle(for: VDS.Badge.self)
        tooltip.title = "Release Notes: \(bundle.build ?? "")"
        tooltip.content = bundle.contents("ReleaseNotes")
        navigationItem.rightBarButtonItem = UIBarButtonItem(customView: tooltip)  // UIBarButtonItem(barButtonSystemItem: .compose, target: self, action: #selector(buildInfoTapped))
        super.viewDidLoad()
        overrideUserInterfaceStyle = .light
        tableView.register(MenuCell.self, forCellReuseIdentifier: "cell")
    }
        
    let items: [MenuComponent] = [
        MenuComponent(title: "DropShadow Tester", completed: true, viewController: DropShadowViewController.self),
        MenuComponent(title: "Badge", completed: true, viewController: BadgeViewController.self),
        MenuComponent(title: "Badge Indicator", completed: true, viewController: BadgeIndicatorViewController.self),
        MenuComponent(title: "Button", completed: true, viewController: ButtonViewController.self),
        MenuComponent(title: "ButtonGroup", completed: true, viewController: ButtonGroupViewController.self),
        MenuComponent(title: "ButtonIcon", completed: false, viewController: ButtonIconViewController.self),
        MenuComponent(title: "Checkbox", completed: true, viewController: CheckboxViewController.self),
        MenuComponent(title: "CheckboxGroup", completed: true, viewController: CheckboxGroupViewController.self),
        MenuComponent(title: "Icon", completed: true, viewController: IconViewController.self),
        MenuComponent(title: "InputField", completed: false, viewController: InputFieldViewController.self),
        MenuComponent(title: "Label", completed: true, viewController: LabelViewController.self),
        MenuComponent(title: "Line", completed: true, viewController: LineViewController.self),
        MenuComponent(title: "Notification", completed: true, viewController: NotificationViewController.self),
        MenuComponent(title: "RadioBoxGroup", completed: true, viewController: RadioBoxGroupViewController.self),
        MenuComponent(title: "RadioButtonGroup", completed: true, viewController: RadioButtonViewController.self),
        MenuComponent(title: "RadioSwatchGroup", completed: true, viewController: RadioSwatchGroupViewController.self),
        //MenuComponent(title: "TabsContainer", completed: false, viewController: TabsContainerViewController.self),
        MenuComponent(title: "Tabs", completed: true, viewController: TabsViewController.self),
        MenuComponent(title: "TextArea", completed: false, viewController: TextAreaViewController.self),
        MenuComponent(title: "TextLink", completed: true, viewController: TextLinkViewController.self),
        MenuComponent(title: "TextLinkCaret", completed: true, viewController: TextLinkCaretViewController.self),
        MenuComponent(title: "TileContainer", completed: false, viewController: TileContainerViewController.self),
        MenuComponent(title: "Tilelet", completed: false, viewController: TileletViewController.self),
        MenuComponent(title: "TitleLockup", completed: true, viewController: TitleLockupViewController.self),
        MenuComponent(title: "Toggle", completed: true, viewController: ToggleViewController.self),
        MenuComponent(title: "Tooltip", completed: true, viewController: TooltipViewController.self),
        MenuComponent(title: "TrailingTooltipLabel", completed: true, viewController: TrailingTooltipLabelViewController.self),

    ]
    
    override func numberOfSections(in tableView: UITableView) -> Int {
        1
    }
    
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        items.count
    }
    
    override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        50.0
    }

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        guard items.count > indexPath.row,
              let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as? MenuCell
            else { return UITableViewCell() }
        
        let item = items[indexPath.row]
        cell.label.text = item.title
        cell.completed = item.completed
        cell.accessoryType = .disclosureIndicator
        return cell
    }
    
    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        guard items.count > indexPath.row else { return }
        let item = items[indexPath.row]
        if let split = splitViewController {
            if let type = item.viewController as? StoryboardInitable.Type {
                let viewController = type.instantiate()
                viewController.title = item.title
                split.showDetailViewController(viewController, sender: nil)
            } else if let type = item.viewController as? Initable.Type {
                if let viewController = type.init() as? UIViewController {
                    viewController.title = item.title
                    split.showDetailViewController(viewController, sender: nil)
                }
            }
        } else {
            if let type = item.viewController as? StoryboardInitable.Type {
                let viewController = type.instantiate()
                viewController.title = item.title
                self.navigationController?.pushViewController(viewController, animated: true)
            } else if let type = item.viewController as? Initable.Type {
                if let viewController = type.init() as? UIViewController {
                    viewController.title = item.title
                    self.navigationController?.pushViewController(viewController, animated: true)
                }
            }
        }
    }
}

extension Bundle {
    var versionNumber: String? {
        infoDictionary?["CFBundleShortVersionString"] as? String
    }
    var buildNumber: String? {
        infoDictionary?["CFBundleVersion"] as? String
    }
    
    var build: String? {
        guard let versionNumber, let buildNumber else { return nil }
        return "\(versionNumber).\(buildNumber)"
    }
    
    func contents(_ fileName: String, fileExtension: String = "txt" ) -> String {
        guard let fileURL = url(forResource: fileName, withExtension: fileExtension) else { return "none" }
        do {
            return try String(contentsOf: fileURL)
        } catch {
            print("error reading releaseNotes")
            return "none"
        }
    }
}
