import UIKit
import TTRangeSlider

struct FindFriendFilterModel {
    
    var gender: String = "All"
    var distance: String = "All"
    var status: String = "All"
    var relationship: String = "All"
    
    init() {
        
    }
    
}

protocol FindFriendsFilterVCDelegate {
    func handleFindFriendsFilterData(filterParam: FindFriendFilterModel)
}

class FindFriendsFilterVC: UIViewController {
    
    // MARK: - IBOutlets
    
    @IBOutlet weak var genderCollectionView: UICollectionView!
    @IBOutlet weak var statusCollectionView: UICollectionView!
    @IBOutlet weak var relationshipCollectionView: UICollectionView!
    @IBOutlet weak var filterView: UIView!
    @IBOutlet weak var ageLabel: UILabel!
    @IBOutlet weak var valuteCountKMLabel: UILabel!
    @IBOutlet weak var filterBtn: UIButton!
    @IBOutlet weak var distanceSlider: UISlider!
    
    // MARK: - Properties
    
    var sheetHeight: CGFloat = 0
    var sheetBackgroundColor: UIColor = .color_fill
    var sheetCornerRadius: CGFloat = 20
    private var hasSetOriginPoint = false
    private var originPoint: CGPoint?
    var genderArray = ["All", "Female", "Male"]
    var statusArray = ["All", "Online", "Offline"]
    var relationshipArray = ["All", "Single", "Relationship", "Married", "Engaged"]
    var findFriendFilterModel = FindFriendFilterModel()
    var delegate: FindFriendsFilterVCDelegate?
    
    
    // MARK: - View Life Cycles
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        self.initialConfig()
    }
    
    override func viewDidLayoutSubviews() {
        if !hasSetOriginPoint {
            hasSetOriginPoint = true
            originPoint = view.frame.origin
        }
    }
    
    // MARK: - Selectors
    
    // Apply Filter Button Action
    @IBAction func applyFilterButtonAction(_ sender: UIButton) {
        self.view.endEditing(true)
        self.dismiss(animated: true) {
            self.delegate?.handleFindFriendsFilterData(filterParam: self.findFriendFilterModel)
        }
    }
    
    // Reset Filter Button Action
    @IBAction func resetFilterButtonAction(_ sender: UIButton) {
        self.view.endEditing(true)
        self.findFriendFilterModel.gender = "All"
        self.findFriendFilterModel.status = "All"
        self.findFriendFilterModel.relationship = "All"
        self.findFriendFilterModel.distance = "0"
        self.distanceSlider.value = Float(self.findFriendFilterModel.distance) ?? 0.0
        self.valuteCountKMLabel.text = self.findFriendFilterModel.distance + "km"
        self.genderCollectionView.reloadData()
        self.statusCollectionView.reloadData()
        self.relationshipCollectionView.reloadData()
        self.dismiss(animated: true) {
            self.delegate?.handleFindFriendsFilterData(filterParam: self.findFriendFilterModel)
        }
    }
    
    // Distance Slider Action
    @IBAction func distanceSliderAction(_ sender: UISlider) {
        self.view.endEditing(true)
        let value = round(sender.value)
        self.valuteCountKMLabel.text = "\(value)km"
        self.findFriendFilterModel.distance = "\(value)"
    }
            
    // 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.setupDistanceSlider()
    }
    
    func setupDistanceSlider() {
        self.distanceSlider.value = Float(self.findFriendFilterModel.distance) ?? 0.0
        self.valuteCountKMLabel.text = self.findFriendFilterModel.distance + "km"
    }
    
    // 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)
        
        self.statusCollectionView.delegate = self
        self.statusCollectionView.dataSource = self
        self.statusCollectionView.register(UINib(resource: R.nib.filterCell), forCellWithReuseIdentifier: R.reuseIdentifier.filterCell.identifier)
        
        self.relationshipCollectionView.delegate = self
        self.relationshipCollectionView.dataSource = self
        self.relationshipCollectionView.register(UINib(resource: R.nib.filterCell), forCellWithReuseIdentifier: R.reuseIdentifier.filterCell.identifier)
    }
    
}

// MARK: Collection View Setup
extension FindFriendsFilterVC: UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        switch collectionView {
        case self.genderCollectionView:
            return self.genderArray.count
        case self.statusCollectionView:
            return self.statusArray.count
        case self.relationshipCollectionView:
            return self.relationshipArray.count
        default:
            return 0
        }
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        switch collectionView {
        case self.genderCollectionView:
            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.findFriendFilterModel.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
        case self.statusCollectionView:
            let cell = self.statusCollectionView.dequeueReusableCell(withReuseIdentifier: R.reuseIdentifier.filterCell.identifier, for: indexPath) as! FilterCell
            let status = self.statusArray[indexPath.row]
            cell.titleLabel.text = status
            cell.cellView.cornerRadiusV = 10
            if self.findFriendFilterModel.status == status {
                cell.titleLabel.textColor = .accent
                cell.cellView.backgroundColor = .accent.withAlphaComponent(0.1)
                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
        case self.relationshipCollectionView:
            let cell = self.genderCollectionView.dequeueReusableCell(withReuseIdentifier: R.reuseIdentifier.filterCell.identifier, for: indexPath) as! FilterCell
            let relationship = self.relationshipArray[indexPath.row]
            cell.titleLabel.text = relationship
            cell.cellView.cornerRadiusV = 10
            if self.findFriendFilterModel.relationship == relationship {
                cell.titleLabel.textColor = .accent
                cell.cellView.backgroundColor = .accent.withAlphaComponent(0.1)
                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
        default:
            return UICollectionViewCell()
        }
        
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        switch collectionView {
        case self.genderCollectionView:
            self.findFriendFilterModel.gender = self.genderArray[indexPath.row]
            self.genderCollectionView.reloadData()
        case self.statusCollectionView:
            self.findFriendFilterModel.status = self.statusArray[indexPath.row]
            self.statusCollectionView.reloadData()
        case self.relationshipCollectionView:
            self.findFriendFilterModel.relationship = self.relationshipArray[indexPath.row]
            self.relationshipCollectionView.reloadData()
        default:
            break
        }
    }
    
    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
        switch collectionView {
        case self.genderCollectionView:
            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)
            }
        case self.statusCollectionView:
            let width = getWidthFromItem(title: self.statusArray[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)
            }
        case self.relationshipCollectionView:
            let width = getWidthFromItem(title: self.relationshipArray[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)
            }
        default:
            return CGSize.zero
        }
    }
    
    // Get Width From String
    func getWidthFromItem(title: String, font: UIFont) -> CGSize {
        let itemSize = title.size(withAttributes: [
            NSAttributedString.Key.font: font
        ])
        return itemSize
    }
    
}

extension UIView {
    
    func roundCorners(corners: UIRectCorner, radius: CGFloat) {
        let path = UIBezierPath(roundedRect: bounds, byRoundingCorners: corners, cornerRadii: CGSize(width: radius, height: radius))
        let mask = CAShapeLayer()
        mask.path = path.cgPath
        layer.mask = mask
    }
    
}
