import UIKit

@MainActor
final class SettingsViewController: UITableViewController {
    private let context: AppContext
    private let appearanceControl = UISegmentedControl(items: ["Auto", "Light", "Dark"])

    init(context: AppContext) {
        self.context = context
        super.init(style: .insetGrouped)
        title = "Settings"
    }

    @available(*, unavailable)
    required init?(coder: NSCoder) { fatalError("init(coder:) is not supported") }

    override func viewDidLoad() {
        super.viewDidLoad()
        let settings = context.core.settings()
        appearanceControl.selectedSegmentIndex = Int(settings.appearance)
        appearanceControl.addTarget(self, action: #selector(appearanceChanged), for: .valueChanged)
    }

    override func numberOfSections(in tableView: UITableView) -> Int { 1 }
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { 1 }

    override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
        "Appearance"
    }

    override func tableView(_ tableView: UITableView, titleForFooterInSection section: Int) -> String? {
        "Follow iOS automatically or choose a fixed appearance."
    }

    override func tableView(
        _ tableView: UITableView,
        cellForRowAt indexPath: IndexPath
    ) -> UITableViewCell {
        let cell = UITableViewCell(style: .default, reuseIdentifier: nil)
        appearanceControl.translatesAutoresizingMaskIntoConstraints = false
        cell.contentView.addSubview(appearanceControl)
        NSLayoutConstraint.activate([
            appearanceControl.leadingAnchor.constraint(equalTo: cell.contentView.leadingAnchor, constant: 16),
            appearanceControl.trailingAnchor.constraint(equalTo: cell.contentView.trailingAnchor, constant: -16),
            appearanceControl.topAnchor.constraint(equalTo: cell.contentView.topAnchor, constant: 8),
            appearanceControl.bottomAnchor.constraint(equalTo: cell.contentView.bottomAnchor, constant: -8),
        ])
        return cell
    }

    @objc private func appearanceChanged() {
        do {
            try context.core.setAppearance(index: UInt32(appearanceControl.selectedSegmentIndex))
            context.applyAppearance()
        } catch {
            show(error: error)
        }
    }
}
