//
//  ChangeThemeColorViewController.swift
//  WoWonder
//
//  Created by Mac on 17/11/22.
//  Copyright © 2022 ScriptSun. All rights reserved.
//

import UIKit

protocol ChangeThemeColorDelegate {
    func handleChangeThemeColor(hex: String)
}

class ChangeThemeColorViewController: UIViewController {
    
    // MARK: - IBOutlets
    
    @IBOutlet weak var collectionView: UICollectionView!
    @IBOutlet weak var collectionViewHeight: NSLayoutConstraint!
    
    // MARK: - Properties
    
    var sheetHeight: CGFloat = 0
    var sheetBackgroundColor: UIColor = .color_fill
    var sheetCornerRadius: CGFloat = 20
    private var hasSetOriginPoint = false
    private var originPoint: CGPoint?
    var colorArray = [
        "#b582af", "#a84849", "#a52729", "#f9c270", "#70a0e0", "#56c4c5", "#f33d4c", "#a1ce79", "#a085e2", "#ed9e6a", "#2b87ce", "#f2812b", "#0ba05d", "#0e71ea", "#aa2294", "#f9a722", "#008484", "#5462a5", "#fc9cde", "#51bcbc", "#C9605E", "#01a5a5", "#056bba", "#C83747"
    ]
    var delagete: ChangeThemeColorDelegate?
    
    // MARK: - View Life Cycles
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        // Do any additional setup after loading the view.
        
        self.initialConfig()
    }
    
    override func viewDidLayoutSubviews() {
        if !hasSetOriginPoint {
            hasSetOriginPoint = true
            originPoint = view.frame.origin
        }
    }
    
    // MARK: - Initial Config
    
    // Initial Config
    func initialConfig() {
        self.sheetHeight = UIScreen.main.bounds.width + 77 + self.view.safeAreaBottom
        self.view.frame.size.height = self.sheetHeight
        self.view.isUserInteractionEnabled = true
        self.view.backgroundColor = self.sheetBackgroundColor
        self.view.roundCorners(corners: [.topLeft, .topRight], radius: self.sheetCornerRadius)
        self.registerCell()
        self.setPanGesture()
    }
    
    // Register Cell
    func registerCell() {
        self.collectionView.delegate = self
        self.collectionView.dataSource = self
        self.collectionView.register(UINib(nibName: "ThemeColorCell", bundle: nil), forCellWithReuseIdentifier: "ThemeColorCell")
        self.collectionViewHeight.constant = UIScreen.main.bounds.width
    }
    
    // Set Pan Gesture
    func setPanGesture() {
        let panGesture = UIPanGestureRecognizer(target: self, action: #selector(panGestureRecognizerAction))
        view.addGestureRecognizer(panGesture)
    }
    
    // Gesture Recognizer
    @objc func panGestureRecognizerAction(sender: UIPanGestureRecognizer) {
        let translation = sender.translation(in: view)
        // Not allowing the user to drag the view upward
        guard translation.y >= 0 else { return }
        view.frame.origin = CGPoint(
            x: 0,
            y: self.originPoint!.y + translation.y
        )
        if sender.state == .ended {
            self.dismiss(animated: true, completion: nil)
        }
    }
    
}

// MARK: - Extensions

// MARK: Collection View Setup
extension ChangeThemeColorViewController: UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return self.colorArray.count + 1
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = self.collectionView.dequeueReusableCell(withReuseIdentifier: "ThemeColorCell", for: indexPath) as! ThemeColorCell
        cell.colorView.layer.cornerRadius = (cell.colorView.frame.height / 2)
        if indexPath.row == self.colorArray.count {
            cell.colorView.backgroundColor = UIColor(hex: "CDCDD7").withAlphaComponent(0.7)
            cell.resetImageView.isHidden = false
        } else {
            cell.colorView.backgroundColor = UIColor(hex: self.colorArray[indexPath.row])
            cell.resetImageView.isHidden = true
        }        
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        self.dismiss(animated: true) {
            if indexPath.row == self.colorArray.count {
                self.delagete?.handleChangeThemeColor(hex: "")
            } else {
                self.delagete?.handleChangeThemeColor(hex: self.colorArray[indexPath.row])
            }
        }
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        let paddingSpace: CGFloat = 12 * (5 + 1)
        let availableWidth = collectionView.frame.width - paddingSpace
        let widthPerItem = availableWidth / 5
        return CGSize(width: widthPerItem, height: widthPerItem)
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
        return UIEdgeInsets(top: 12.0, left: 12.0, bottom: 12.0, right: 12.0)
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
        return 12
    }
    
}
