//
//  See LICENSE folder for this template’s licensing information.
//
//  Abstract:
//   playground 番号とユーザー名を登録するビュー
//   playground BluetoothによるconnectionViewの表示

import UIKit
import PlaygroundSupport

import UIKit
import PlaygroundSupport

protocol SetNameViewDelegate: AnyObject {
    func didSaveSettings(userName: String?, userNumber: String?)
    func didCloseSetNameView()
}

public class SetNameView: UIView, PlaygroundLiveViewSafeAreaContainer, TablePickerViewControllerDelegate {
    
    weak var delegate: SetNameViewDelegate?
    
    func didSelectNumber(_ number: Int) {
        numberLabel.text = "\(number)"
    }
    
    private var titleLabel = UILabel()
    private var closeButton = UIButton()
    private var textField = UITextField()
    private var explaneLabel = UILabel()
    private var numberLabel = UILabel()
    private var settingButton = UIButton()
    
    private var userName: String? = nil
    private var userNumber: String? = nil

    private let scrollView = UIScrollView()
    private let contentView = UIView()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        self.alpha = 0.0  // 初期状態を透明に設定
        setupView()
    }
    
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        self.alpha = 0.0  // 初期状態を透明に設定
        setupView()
    }
    
    private func setupView() {
        // 背景色と角丸の設定
        self.backgroundColor = UIColor.systemBackground.withAlphaComponent(0.97)
        self.layer.cornerRadius = 10
        self.layer.masksToBounds = true
        
        if let keyValue = PlaygroundKeyValueStore.current["userName"],
            case .string(let storedUserName) = keyValue {
            userName = storedUserName
        } else {
            userName = nil
        }
        
        if let keyValue = PlaygroundKeyValueStore.current["userNumber"],
            case .string(let storedNumber) = keyValue {
            userNumber = storedNumber
        } else {
            userNumber = nil
        }
        
        // スクロールビューの設定
        scrollView.translatesAutoresizingMaskIntoConstraints = false
        addSubview(scrollView)
        
        // コンテンツビューの設定
        contentView.translatesAutoresizingMaskIntoConstraints = false
        scrollView.addSubview(contentView)
        
        // タイトルビューの設定
        let headerView = UIView()
        headerView.backgroundColor = UIColor.systemGray5.withAlphaComponent(0.8)
        //headerView.layer.cornerRadius = 10
        headerView.layer.masksToBounds = true
        
        titleLabel.text = "ユーザー設定"
        titleLabel.font = .boldSystemFont(ofSize: 20)
        titleLabel.textColor = .label
        titleLabel.textAlignment = .center
        
        closeButton.setImage(UIImage(systemName: "xmark"), for: .normal)
        closeButton.addTarget(self, action: #selector(closeButtonTapped), for: .touchUpInside)
        closeButton.imageView?.contentMode = .scaleAspectFit
        
        headerView.addSubview(titleLabel)
        headerView.addSubview(closeButton)
        addSubview(headerView)
        
        // headerViewのレイアウト
        headerView.translatesAutoresizingMaskIntoConstraints = false
        titleLabel.translatesAutoresizingMaskIntoConstraints = false
        closeButton.translatesAutoresizingMaskIntoConstraints = false
        NSLayoutConstraint.activate([
            headerView.topAnchor.constraint(equalTo: self.topAnchor),
            headerView.leadingAnchor.constraint(equalTo: self.leadingAnchor),
            headerView.trailingAnchor.constraint(equalTo: self.trailingAnchor),
            headerView.heightAnchor.constraint(equalToConstant: 60),
            
            titleLabel.centerXAnchor.constraint(equalTo: headerView.centerXAnchor),
            titleLabel.centerYAnchor.constraint(equalTo: headerView.centerYAnchor),
            
            closeButton.trailingAnchor.constraint(equalTo: headerView.trailingAnchor, constant: -10),
            closeButton.centerYAnchor.constraint(equalTo: headerView.centerYAnchor),
            closeButton.widthAnchor.constraint(equalToConstant: 40),
            closeButton.heightAnchor.constraint(equalToConstant: 40)
        ])
        
        numberLabel.text = userNumber ?? "-"
        textField.text = userName

        settingButton.setTitle("保存する", for: .normal)
        settingButton.addTarget(self, action: #selector(tapSettingButton(_:)), for: .touchUpInside)
        settingButton.setTitleColor(.white, for: .normal) // テキスト色を白に設定
        settingButton.backgroundColor = .systemBlue // 背景色をブルーに設定
        settingButton.titleLabel?.font = UIFont.boldSystemFont(ofSize: 18) // フォントサイズとスタイルを変更
        settingButton.layer.cornerRadius = 10 // 角丸を設定
        settingButton.layer.shadowColor = UIColor.black.cgColor // 影の色を設定
        settingButton.layer.shadowOffset = CGSize(width: 0, height: 2) // 影のオフセットを設定
        settingButton.layer.shadowOpacity = 0.5 // 影の不透明度を設定
        settingButton.layer.shadowRadius = 4 // 影の半径を設定

        contentView.addSubview(explaneLabel)
        contentView.addSubview(textField)
        contentView.addSubview(settingButton)
        contentView.addSubview(numberLabel)
        
        explaneLabel.text = "　現在設定されている［番号］と［ユーザー名］を表示しています。変更する場合は、入力欄の値を変更して、［保存する］ボタンを押してください。"
        explaneLabel.textColor = .label
        explaneLabel.lineBreakMode = .byWordWrapping
        explaneLabel.numberOfLines = 0
        explaneLabel.font = .systemFont(ofSize: 20.0)
        
        numberLabel.textColor = .label // 文字色を白に設定
        numberLabel.backgroundColor = .systemFill // 背景色を黒に設定
        numberLabel.layer.borderWidth = 2.0 // ボーダーの幅を設定
        numberLabel.layer.borderColor = UIColor.separator.cgColor
        numberLabel.layer.cornerRadius = 10.0
        numberLabel.clipsToBounds = true
        numberLabel.textAlignment = .center
        numberLabel.isUserInteractionEnabled = true
        let tapGesture = UITapGestureRecognizer(target: self, action: #selector(showNumberPicker))
        numberLabel.addGestureRecognizer(tapGesture)

        let paddingView = UIView(frame: CGRect(x: 0, y: 0, width: 15, height: textField.frame.height))
        textField.leftView = paddingView
        textField.leftViewMode = .always
        textField.backgroundColor = .systemFill // 背景色を黒に設定
        textField.textColor = .label
        textField.layer.cornerRadius = 10.0
        textField.layer.borderWidth = 1.0
        textField.clipsToBounds = true
        textField.placeholder = "ユーザー名を入力"
        
        explaneLabel.translatesAutoresizingMaskIntoConstraints = false
        numberLabel.translatesAutoresizingMaskIntoConstraints = false
        textField.translatesAutoresizingMaskIntoConstraints = false
        settingButton.translatesAutoresizingMaskIntoConstraints = false
        
        NSLayoutConstraint.activate([
            explaneLabel.topAnchor.constraint(equalTo: contentView.topAnchor, constant: 20),
            explaneLabel.leadingAnchor.constraint(equalTo: contentView.leadingAnchor, constant: 20),
            explaneLabel.trailingAnchor.constraint(equalTo: contentView.trailingAnchor, constant: -20),
            explaneLabel.heightAnchor.constraint(greaterThanOrEqualToConstant: 80),
            
            numberLabel.topAnchor.constraint(equalTo: explaneLabel.bottomAnchor, constant: 40),
            numberLabel.leadingAnchor.constraint(equalTo: contentView.leadingAnchor, constant: 40),
            numberLabel.widthAnchor.constraint(equalToConstant: 50),
            numberLabel.heightAnchor.constraint(equalToConstant: 50),

            textField.topAnchor.constraint(equalTo: explaneLabel.bottomAnchor, constant: 40),
            textField.leadingAnchor.constraint(equalTo: numberLabel.trailingAnchor, constant: 20),
            textField.trailingAnchor.constraint(equalTo: contentView.trailingAnchor, constant: -40),
            textField.heightAnchor.constraint(equalToConstant: 50),

            settingButton.topAnchor.constraint(equalTo: textField.bottomAnchor, constant: 20),
            settingButton.centerXAnchor.constraint(equalTo: contentView.centerXAnchor),
            settingButton.widthAnchor.constraint(equalToConstant: 140),
            settingButton.heightAnchor.constraint(equalToConstant: 50),
            settingButton.bottomAnchor.constraint(equalTo: contentView.bottomAnchor, constant: -20)
        ])
        
        // スクロールビューのレイアウト
        NSLayoutConstraint.activate([
            scrollView.topAnchor.constraint(equalTo: headerView.bottomAnchor),
            scrollView.leadingAnchor.constraint(equalTo: self.leadingAnchor),
            scrollView.trailingAnchor.constraint(equalTo: self.trailingAnchor),
            scrollView.bottomAnchor.constraint(equalTo: self.bottomAnchor),
            
            contentView.topAnchor.constraint(equalTo: scrollView.topAnchor),
            contentView.leadingAnchor.constraint(equalTo: scrollView.leadingAnchor),
            contentView.trailingAnchor.constraint(equalTo: scrollView.trailingAnchor),
            contentView.bottomAnchor.constraint(equalTo: scrollView.bottomAnchor),
            contentView.widthAnchor.constraint(equalTo: scrollView.widthAnchor)
        ])
        
        // ビューが親ビューに追加された後にアニメーションを開始
        UIView.animate(withDuration: 0.3) {
            self.alpha = 1.0
        }
    }
    
    @objc func closeButtonTapped() {
        // `SetNameView`を非表示にするアニメーションを開始
        UIView.animate(withDuration: 0.3, animations: {
            self.alpha = 0.0
        }, completion: { _ in
            // アニメーション完了後に`SetNameView`を親ビューから削除
            self.removeFromSuperview()
            // デリゲートに通知
            self.delegate?.didCloseSetNameView()
        })
    }
    
    @objc func tapSettingButton(_ sender: UIButton) {
        var saved = false
        
        if let text = textField.text, !text.isEmpty {
            PlaygroundKeyValueStore.current["userName"] = .string(text)
            saved = true
        }
        
        if let numberText = numberLabel.text, numberText != "-" {
            PlaygroundKeyValueStore.current["userNumber"] = .string(numberText)
            saved = true
        }
        
        if saved {
            let alert = UIAlertController(title: "保存完了", message: "設定が保存されました。", preferredStyle: .alert)
            alert.addAction(UIAlertAction(title: "OK", style: .default, handler: { _ in
                //親ビューに通知
                self.delegate?.didSaveSettings(userName: self.textField.text, userNumber: self.numberLabel.text)
                // アラートを閉じた後にSetNameViewを非表示にするアニメーションを開始
                UIView.animate(withDuration: 0.3, animations: {
                    self.alpha = 0.0
                }, completion: { _ in
                    // アニメーション完了後にSetNameViewを親ビューから削除
                    self.removeFromSuperview()
                })
            }))
            if let vc = self.parentViewController {
                vc.present(alert, animated: true, completion: nil)
            }
        }
    }
    
    @objc func showNumberPicker() {
        let alert = UIAlertController(title: "番号選択", message: nil, preferredStyle: .alert)
        
        let pickerVC = TablePickerViewController()
        pickerVC.delegate = self
        
        let height: NSLayoutConstraint = NSLayoutConstraint(item: pickerVC.view!, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: 250)
        pickerVC.view.addConstraint(height)
        
        alert.setValue(pickerVC, forKey: "contentViewController")
        
        alert.addAction(UIAlertAction(title: "キャンセル", style: .cancel, handler: nil))
        
        if let vc = self.parentViewController {
            vc.present(alert, animated: true, completion: nil)
        }
    }
}

extension UIView {
    var parentViewController: UIViewController? {
        var parentResponder: UIResponder? = self
        while let responder = parentResponder {
            parentResponder = responder.next
            if let viewController = parentResponder as? UIViewController {
                return viewController
            }
        }
        return nil
    }
}
