//
//  SearchFilterVC.swift
//  WoWonder
//
//  Created by UnikApp on 28/02/23.
//  Copyright © 2023 ScriptSun. All rights reserved.
//

import UIKit
import TTRangeSlider

struct SearchFilterModel {
    
    var gender: String = "All"
    var location: String = "All"
    var verified: String = "All"
    var status: String = "All"
    var profilePicture: String = "All"
    var ageTo: String = "70"
    var ageFrom: String = "0"
    var filterByAge: String = "No"
    
    init() {
        
    }
    
}

protocol SearchFilterVCDelegate {
    func handleSearchFilter(searchFilterModel: SearchFilterModel)
}

class SearchFilterVC: UIViewController {
    
    // MARK: - IBOutlets
    
    @IBOutlet weak var filterView: UIView!
    @IBOutlet weak var backButton: UIButton!
    @IBOutlet weak var clearButton: UIButton!
    @IBOutlet weak var genderView: UIView!
    @IBOutlet weak var genderCollectionView: UICollectionView!
    @IBOutlet weak var ageView: UIView!
    @IBOutlet weak var ageLabel: UILabel!
    @IBOutlet weak var ageSwitch: UISwitch!
    @IBOutlet weak var ageSlider: TTRangeSlider!
    @IBOutlet weak var locationControl: UIControl!
    @IBOutlet weak var locationLabel: UILabel!
    @IBOutlet weak var verifiedControl: UIControl!
    @IBOutlet weak var verifiedLabel: UILabel!
    @IBOutlet weak var statusControl: UIControl!
    @IBOutlet weak var statusLabel: UILabel!
    @IBOutlet weak var profilePictureControl: UIControl!
    @IBOutlet weak var profilePictureLabel: UILabel!
    @IBOutlet weak var applyFilterButton: UIButton!
    
    // MARK: - Properties
    
    var sheetHeight: CGFloat = 0
    var sheetBackgroundColor: UIColor = .color_fill
    var sheetCornerRadius: CGFloat = 20
    private var hasSetOriginPoint = false
    private var originPoint: CGPoint?
    var searchFilterModel = SearchFilterModel()
    var genderArray = ["All", "Male", "Female"]
    var delegate: SearchFilterVCDelegate?
    
    // MARK: - View Life Cycles
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        self.initialConfig()
    }
    
    override func viewDidLayoutSubviews() {
        if !hasSetOriginPoint {
            hasSetOriginPoint = true
            originPoint = view.frame.origin
        }
    }
    
    // MARK: - Selectors
    
    // Age Switch Action
    @IBAction func ageSwitchAction(_ sender: UISwitch) {
        self.view.endEditing(true)
        if sender.isOn == true {
            self.ageSlider.isHidden = false
            self.ageLabel.text = "Age"
            self.ageSlider.maxValue = 70
            self.ageSlider.minValue = 0
            self.ageSlider.selectedMinimum = 0
            self.ageSlider.selectedMaximum = 70
            self.searchFilterModel.filterByAge = "Yes"
        } else {
            self.ageSlider.isHidden = true
            self.ageLabel.text = "Age"
            self.searchFilterModel.filterByAge = "No"
        }
    }
    
    // Back Button Action
    @IBAction func backButtonAction(_ sender: UIButton) {
        self.view.endEditing(true)
        self.dismiss(animated: true, completion: nil)
    }
    
    // Clear Button Action
    @IBAction func clearButtonAction(_ sender: UIButton) {
        self.searchFilterModel.gender = "All"
        self.genderCollectionView.reloadData()
        
        self.ageLabel.text = "Age"
        self.ageSlider.isHidden = true
        self.ageSwitch.isOn = false
        self.searchFilterModel.ageTo = ""
        self.searchFilterModel.ageFrom = ""
        self.searchFilterModel.filterByAge = "No"
        
        self.searchFilterModel.location = "All"
        self.locationLabel.text = self.searchFilterModel.location
        
        self.searchFilterModel.verified = "All"
        self.verifiedLabel.text = self.searchFilterModel.verified
        
        self.searchFilterModel.status = "All"
        self.statusLabel.text = self.searchFilterModel.status
        
        self.searchFilterModel.profilePicture = "All"
        self.profilePictureLabel.text = self.searchFilterModel.profilePicture
    }
    
    // Location Button Action
    @IBAction func locationButtonAction(_ sender: UIButton) {
        self.view.endEditing(true)
        if let newVC = R.storyboard.popup.locationAlertVC() {
            newVC.delegate = self
            newVC.modalPresentationStyle = .overCurrentContext
            newVC.modalTransitionStyle = .crossDissolve
            self.present(newVC, animated: true)
        }
    }
    
    // Verified Button Action
    @IBAction func verifiedButtonAction(_ sender: UIButton) {
        self.view.endEditing(true)
        if let newVC = R.storyboard.popup.verifiedPopUpVC() {
            newVC.delegate = self
            newVC.modalPresentationStyle = .overCurrentContext
            newVC.modalTransitionStyle = .crossDissolve
            self.present(newVC, animated: true)
        }
    }
    
    // Status Button Action
    @IBAction func statusButtonAction(_ sender: UIButton) {
        self.view.endEditing(true)
        if let newVC = R.storyboard.popup.statusPopUpVC() {
            newVC.delegate = self
            newVC.modalPresentationStyle = .overCurrentContext
            newVC.modalTransitionStyle = .crossDissolve
            self.present(newVC, animated: true)
        }
    }
    
    // Profile Picture Button Action
    @IBAction func profilePictureButtonAction(_ sender: UIControl) {
        self.view.endEditing(true)
        if let newVC = R.storyboard.popup.profilePicturePopUpVC() {
            newVC.delegate = self
            newVC.modalPresentationStyle = .overCurrentContext
            newVC.modalTransitionStyle = .crossDissolve
            self.present(newVC, animated: true)
        }
    }
    
    // Apply Filter Button Action
    @IBAction func applyButtonFilterButtonAction(_ sender: UIButton) {
        self.view.endEditing(true)
        self.dismiss(animated: true) {
            self.delegate?.handleSearchFilter(searchFilterModel: self.searchFilterModel)
        }
    }
    
    // MARK: - Helper Functions
    
    // Initial Config
    func initialConfig() {
        self.sheetHeight = self.view.frame.height - self.view.safeAreaTop
        view.frame.size.height = sheetHeight
        view.isUserInteractionEnabled = true
        view.backgroundColor = sheetBackgroundColor
        view.roundCorners(corners: [.topLeft, .topRight], radius: sheetCornerRadius)
        self.setPanGesture()
        self.collectionViewSetup()
        self.setUpAgeUI()
        self.setData()
    }
    
    // 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)
        }
    }
    
    // Collection View Setup
    func collectionViewSetup() {
        self.genderCollectionView.delegate = self
        self.genderCollectionView.dataSource = self
        self.genderCollectionView.register(UINib(resource: R.nib.filterCell), forCellWithReuseIdentifier: R.reuseIdentifier.filterCell.identifier)
    }
    
    // Set Data
    func setData() {
        self.locationLabel.text = self.searchFilterModel.location
        self.verifiedLabel.text = self.searchFilterModel.verified
        self.statusLabel.text = self.searchFilterModel.status
        self.profilePictureLabel.text = self.searchFilterModel.profilePicture
        
        if self.searchFilterModel.filterByAge == "Yes" {
            self.ageSlider.selectedMinimum = Float(self.searchFilterModel.ageFrom) ?? 0.0
            self.ageSlider.selectedMaximum = Float(self.searchFilterModel.ageTo) ?? 0.0
            self.ageSlider.isHidden = false
            self.ageSwitch.isOn = true
        }
    }
    
    func setUpAgeUI() {
        self.ageSlider.delegate = self
        self.ageSwitch.isOn = false
        self.ageSlider.isHidden = true
    }

}

// MARK: - Extensions

// MARK: Collection View Setup
extension SearchFilterVC: UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return self.genderArray.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = self.genderCollectionView.dequeueReusableCell(withReuseIdentifier: R.reuseIdentifier.filterCell.identifier, for: indexPath) as! FilterCell
        let gender = self.genderArray[indexPath.row]
        cell.titleLabel.text = gender
        cell.cellView.iscircleCorner = true
        if self.searchFilterModel.gender == gender {
            cell.titleLabel.textColor = .gnt_white
            cell.cellView.backgroundColor = .accent
            cell.cellView.borderWidthV = 0
        } else {
            cell.titleLabel.textColor = .text_color
            cell.cellView.backgroundColor = .clear
            cell.cellView.borderColorV = .color_divider
            cell.cellView.borderWidthV = 1
        }
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        self.searchFilterModel.gender = self.genderArray[indexPath.row]
        self.genderCollectionView.reloadData()
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        let cellsInRow: CGFloat = 3
        let flowLayout: UICollectionViewFlowLayout = collectionViewLayout as! UICollectionViewFlowLayout
        let leftRightPadding: CGFloat = flowLayout.sectionInset.left + flowLayout.sectionInset.right
        let spaceBetweenCells: CGFloat = flowLayout.minimumLineSpacing * (cellsInRow - 1)
        let cellWidth = (collectionView.width - leftRightPadding - spaceBetweenCells) / cellsInRow
        let width = getWidthFromItem(title: self.genderArray[indexPath.row], font: UIFont(name: "BRSonoma-Medium", size: 14.0)!).width + 25
        if cellWidth < width {
            return CGSize(width: width, height: 32)
        } else {
            return CGSize(width: cellWidth, height: 32)
        }
    }
    
    // Get Width From String
    func getWidthFromItem(title: String, font: UIFont) -> CGSize {
        let itemSize = title.size(withAttributes: [
            NSAttributedString.Key.font: font
        ])
        return itemSize
    }
    
}

// MARK: TTRangeSliderDelegate Methods
extension SearchFilterVC: TTRangeSliderDelegate {
    
    func rangeSlider(_ sender: TTRangeSlider!, didChangeSelectedMinimumValue selectedMinimum: Float, andMaximumValue selectedMaximum: Float) {
        let min = String(format: "%i",Int(selectedMinimum))
        let max = String(format: "%i",Int(selectedMaximum))
        self.ageLabel.text = "Age \(min) - \(max)"
        self.searchFilterModel.ageFrom = min
        self.searchFilterModel.ageTo = max
    }
    
}

// MARK: LocationAlertVCDelegate Methods
extension SearchFilterVC: LocationAlertVCDelegate {
    
    func handleCountrySelection(country: CountryModel) {
        self.searchFilterModel.location = country.name
        self.locationLabel.text = country.name
    }
    
}

// MARK: ProfilePicturePopUpVCDelegate Methods
extension SearchFilterVC: ProfilePicturePopUpVCDelegate {
    
    func handleProfilePictiureTap(profilePicture: String) {
        self.searchFilterModel.profilePicture = profilePicture
        self.profilePictureLabel.text = self.searchFilterModel.profilePicture
    }
    
}

// MARK: VerifiedPopUpVCDelegate Methods
extension SearchFilterVC: VerifiedPopUpVCDelegate {
    
    func handleVerifiedTap(verified: String) {
        self.searchFilterModel.verified = verified
        self.verifiedLabel.text = self.searchFilterModel.verified
    }
    
}

// MARK: StatusPopUpVCDelegate Methods
extension SearchFilterVC: StatusPopUpVCDelegate {
    
    func handleStatusTap(status: String) {
        self.searchFilterModel.status = status
        self.statusLabel.text = self.searchFilterModel.status
    }
    
}
