//
//  UserIntrestVC.swift
//  WOKA
//
//  Created by MacBook Pro on 30/04/24.
//

import UIKit
struct Temp{
    let text : String?
    var selected : Bool?
}

class UserIntrestVC: UIViewController {
    
    @IBOutlet weak var boyView: UIView!
    @IBOutlet weak var girlView: UIView!
    @IBOutlet weak var datePicker: UIDatePicker!
    @IBOutlet weak var collectionView: UICollectionView!
    @IBOutlet weak var nextBtn: LocalisedElementsButton!
    @IBOutlet weak var scrollView: UIScrollView!
    @IBOutlet weak var fullName: UILabel!
    
    @IBOutlet weak var contentHeight: NSLayoutConstraint!
    @IBOutlet weak var intrestStackView: UIStackView!
    @IBOutlet weak var selectAsManyYouWant: UILabel!
    
    @IBOutlet weak var boyText: UILabel!
    @IBOutlet weak var GirlText: UILabel!
    var vm = UserIntrestVM()
    var test = [Temp(text: "ADVENTURES", selected: false),
                Temp(text: "CARTOONS", selected: false),
                Temp(text: "SUPER HEROES", selected: false),
                Temp(text: "SPORTS", selected: false),
                Temp(text: "SCIENCE", selected: false),
                Temp(text: "TRAVEL", selected: false),
                Temp(text: "ADVENTURES", selected: false),
                Temp(text: "CARTOONS", selected: false),
                Temp(text: "SUPER HEROES", selected: false),
                Temp(text: "SPORTS", selected: false),
                Temp(text: "SCIENCE", selected: false),
                Temp(text: "TRAVEL", selected: false)]
    
    override func viewDidLoad() {
        super.viewDidLoad()
        vm.vc = self
        vm.initView()
        
        boyView.roundCorner(radius: 25)
        girlView.roundCorner(radius: 25)
        datePicker.setValue(UIColor.appColor(.TextDarkBlue), forKeyPath: "textColor")
        
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        navigationController?.setNavigationBarHidden(false, animated: animated)
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        navigationController?.setNavigationBarHidden(true, animated: animated)
        
        if self.isMovingFromParent {
            // Back button was pressed
            PersistentStorage.shared.addOthersCount()
        }
    }
    
    @IBAction func nextBtnTapped(_ sender: LocalisedElementsButton) {
        PersistentStorage.shared.addOthersCount()
        let dob = DateFormatterLib.dateModsDate(date: datePicker.date, dateReturnFormat: .yyyy_MM_dd, stringOrDate: .string).0
        /*
         Append the DOB to RegData
         */
        AuthFunc.shareInstance.regData.birthdate = dob
        
        // Check for Gender.
//        if AuthFunc.shareInstance.regData.gender == nil{
//            let sb = UIStoryboard(name: K.StoryBoard.customAlerts, bundle: nil)
//            let vcPush = sb.instantiateViewController(withIdentifier: K.StoryBoardID.CustomAlerts.alertCustomVC) as! AlertCustomVC
//            
//            vcPush.contentLabel = K.ConstantString.genderSel.localized(loc: AuthFunc.shareInstance.languageSelected.rawValue)
//            vcPush.mainTitleText = K.ConstantString.error.localized(loc: AuthFunc.shareInstance.languageSelected.rawValue)
//            //                vcPush.onDoneBlock = { isDone in }
//            vcPush.modalPresentationStyle = .overCurrentContext
//            vcPush.modalTransitionStyle = .crossDissolve
//            self.present(vcPush, animated: true)
//            return
//        }
        
        // Check for Intrest.
        if AuthFunc.shareInstance.userType == .kid || vm.createChildAccount == true{
            if AuthFunc.shareInstance.regData.interest_topic_id == nil || AuthFunc.shareInstance.regData.interest_topic_id?.count == 0{
                let sb = UIStoryboard(name: K.StoryBoard.customAlerts, bundle: nil)
                let vcPush = sb.instantiateViewController(withIdentifier: K.StoryBoardID.CustomAlerts.alertCustomVC) as! AlertCustomVC
                
                vcPush.contentLabel = K.ConstantString.intrest.localized(loc: AuthFunc.shareInstance.languageSelected.rawValue)
                vcPush.mainTitleText = K.ConstantString.error.localized(loc: AuthFunc.shareInstance.languageSelected.rawValue)
                //                vcPush.onDoneBlock = { isDone in }
                vcPush.modalPresentationStyle = .overCurrentContext
                vcPush.modalTransitionStyle = .crossDissolve
                self.present(vcPush, animated: true)
                return
            }
        }
        
        // Check for DOB.
        if AuthFunc.shareInstance.regData.birthdate == nil{
            let sb = UIStoryboard(name: K.StoryBoard.customAlerts, bundle: nil)
            let vcPush = sb.instantiateViewController(withIdentifier: K.StoryBoardID.CustomAlerts.alertCustomVC) as! AlertCustomVC
            
            vcPush.contentLabel = K.ConstantString.dob
            vcPush.mainTitleText = K.ConstantString.error
            //                vcPush.onDoneBlock = { isDone in }
            vcPush.modalPresentationStyle = .overCurrentContext
            vcPush.modalTransitionStyle = .crossDissolve
            self.present(vcPush, animated: true)
            return
        }

        let sb = UIStoryboard(name: K.StoryBoard.authenticationSB, bundle: nil)
        let vc = sb.instantiateViewController(withIdentifier: K.StoryBoardID.Authentication.selectAvatarVC) as! SelectAvatarVC
        vc.vm.createChildAccount = self.vm.createChildAccount
        self.navigationController?.pushViewController(vc, animated: true)
    }
}

// MARK: - CollectionView Delegate

extension UserIntrestVC : UICollectionViewDelegate , UICollectionViewDataSource{
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return vm.intrestTopics.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: K.CellIdentifier.Authentication.yourIntrestCell, for: indexPath) as! YourIntrestCell
        cell.setData(data: vm.intrestTopics[indexPath.row])
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        vm.intrestTopics[indexPath.row].isSelected?.toggle()
        PersistentStorage.shared.addOthersCount()
        //Append remove intrest ID
        if let id = vm.intrestTopics[indexPath.row].id{
            if let topicID = AuthFunc.shareInstance.regData.interest_topic_id, let index = topicID.firstIndex(of: id){
                AuthFunc.shareInstance.regData.interest_topic_id?.remove(at: index)
            }else{
                if AuthFunc.shareInstance.regData.interest_topic_id == nil {
                    AuthFunc.shareInstance.regData.interest_topic_id = []
                }
                AuthFunc.shareInstance.regData.interest_topic_id?.append(id)
            }
        }
//        print(AuthFunc.shareInstance.regData.interest_topic_id)
        UIView.performWithoutAnimation {
            self.collectionView.reloadItems(at: [IndexPath(row: indexPath.row, section: 0)])
        }
    }
}

// MARK: - Collection Flow Layout

extension UserIntrestVC : UICollectionViewDelegateFlowLayout{
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        // Generate a random string for testing purposes
        let randomText = test[indexPath.row].text!
        
        // Define the font for the text
        let font = UIFont.systemFont(ofSize: 14) // You can adjust the font size as needed
        
        // Calculate the width of the text
        let textWidth = randomText.size(withAttributes: [.font: font]).width
        
        // Set the cell width based on the text width and any additional padding
        let cellWidth = textWidth + 25 // Add any additional spacing you want
        
        return CGSize(width: cellWidth, height: 45)
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
        section == 0 ? 15 : 5
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
        UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10)
    }

}


extension UIView {
    func startShimmeringViewAnimation() {
        
        let gradientLayer = CAGradientLayer()
//        gradientLayer.frame = bounds
        gradientLayer.frame = CGRect(x: -bounds.width, y: 0, width: 3 * bounds.width, height: bounds.height)

        gradientLayer.startPoint = CGPoint(x: 0.0, y: 1.0)
        gradientLayer.endPoint = CGPoint(x: 1.0, y: 1.0)
        let gradientColorOne = #colorLiteral(red: 0.7529411765, green: 0.7529411765, blue: 0.7529411765, alpha: 1).cgColor
        let gradientColorTwo = #colorLiteral(red: 1, green: 1, blue: 1, alpha: 1).cgColor
        gradientLayer.colors = [gradientColorOne, gradientColorTwo, gradientColorOne]
        gradientLayer.locations = [0.0, 0.5, 1.0]
        layer.addSublayer(gradientLayer)
        
        startShimmerAnimation(on: gradientLayer)
    }
    
    func stopShimmeringViewAnimation() {
        guard let gradientLayer = layer.sublayers?.first(where: { $0 is CAGradientLayer }) else {
            return
        }
        gradientLayer.removeAllAnimations()
        gradientLayer.removeFromSuperlayer()
    }
    
    private func startShimmerAnimation(on layer: CALayer) {
        let animation = CABasicAnimation(keyPath: "locations")
        animation.fromValue = [-1.0, -0.5, 0.0]
        animation.toValue = [1.0, 1.5, 2.0]
        animation.repeatCount = .infinity
        animation.duration = 1.25
        layer.add(animation, forKey: animation.keyPath)
    }

}


import UIKit

class ShimmerView: UIView {
    
    override class var layerClass: AnyClass {
        return CAGradientLayer.self
    }

    var gradientLayer: CAGradientLayer {
        return layer as! CAGradientLayer
    }

    override func layoutSubviews() {
        super.layoutSubviews()
        
        gradientLayer.colors = [UIColor.clear.cgColor, UIColor.white.cgColor, UIColor.clear.cgColor]
        gradientLayer.locations = [0.0, 0.5, 1.0]
        gradientLayer.startPoint = CGPoint(x: 0.0, y: 0.5)
        gradientLayer.endPoint = CGPoint(x: 1.0, y: 0.5)
        
        let animation = CABasicAnimation(keyPath: "transform.translation.x")
        animation.duration = 1.0
        animation.fromValue = -frame.width
        animation.toValue = frame.width
        animation.repeatCount = Float.infinity
        gradientLayer.add(animation, forKey: "shimmerAnimation")
    }
}
