//
//  StoryViewController.swift
//  WoWonder
//
//  Created by UnikApp on 13/12/22.
//  Copyright © 2022 ScriptSun. All rights reserved.
//

import UIKit
import Async
import Toast_Swift
import SDWebImage
import WowonderMessengerSDK
import DropDown

class StoryViewController: BaseVC {
    
    // MARK: - IBOutlets
    
    @IBOutlet weak var searchButton: UIButton!
    @IBOutlet weak var moreButton: UIButton!
    @IBOutlet weak var findFriendButton: UIButton!
    @IBOutlet weak var tableView: UITableView!
    @IBOutlet weak var emptyView: UIView!
    @IBOutlet weak var userImageView: UIImageView!
    
    // MARK: - Properties
    
    private var imagePicker = UIImagePickerController()
    private var storiesArray: [UserData] = []
    private let dropDown = DropDown()
    private var dropDownDataSource = [
        "Request",
        "Broadcast"
    ]
    
    // MARK: - View Life Cycles
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        // Do any additional setup after loading the view.
        
        self.initialConfig()
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        
        self.fetchData()
    }
    
    // MARK: - Selectors
    
    // Seacrh Button Action
    @IBAction func searchButtonAction(_ sender: UIButton) {
        self.view.endEditing(true)
        if let newVC = R.storyboard.dashboard.searchRandomVC() {
            self.navigationController?.pushViewController(newVC, animated: true)
        }
    }
    
    // More Button Action
    @IBAction func moreButtonAction(_ sender: UIButton) {
        self.view.endEditing(true)
        self.dropDown.show()
    }
    
    // Find Friend Button Action
    @IBAction func findFriendButtonAction(_ sender: UIButton) {
        self.view.endEditing(true)
        if let newVC = R.storyboard.dashboard.findFriendsViewController() {
            newVC.findFriendFilterModel.distance = "1"
            self.navigationController?.pushViewController(newVC, animated: true)
        }
    }
    
    @IBAction func newStoryButtonAction(_ sender: UIControl) {
        if let newVC = R.storyboard.story.storyBottomViewController() {
            newVC.modalPresentationStyle = .custom
            newVC.transitioningDelegate = self
            newVC.delegate = self
            self.present(newVC, animated: true)
        }
    }
    
    // MARK: - Helper Functions
    
    // Initial Config
    func initialConfig() {
        self.setupDropDown()
        self.tableViewSetup()
        self.setData()
    }
    
    // TableView Setup
    func tableViewSetup() {
        self.tableView.delegate = self
        self.tableView.dataSource = self
        self.tableView.refreshControl = UIRefreshControl()
        self.tableView.refreshControl?.addTarget(self, action: #selector(self.refreshData), for: .valueChanged)
        self.tableView.register( UINib(resource: R.nib.storiesTableCell), forCellReuseIdentifier: R.reuseIdentifier.stories_TableCell.identifier)
    }
    
    private func setupDropDown() {
        self.dropDown.dataSource = self.dropDownDataSource
        self.dropDown.anchorView = self.moreButton
        self.dropDown.width = 160
        self.dropDown.bottomOffset = CGPoint(x: -124, y: 34)
        self.dropDown.direction = .bottom
        self.dropDown.sizeToFit()
        self.dropDown.selectionAction = { [unowned self] (index: Int, item: String) in
            if item == "Request" {
                if let newVC = R.storyboard.dashboard.requestViewController() {
                    self.navigationController?.pushViewController(newVC, animated: true)
                }
            }
            if item == "Broadcast" {
                if let newVC = R.storyboard.broadcast.broadcastVC() {
                    self.navigationController?.pushViewController(newVC, animated: true)
                }
            }
            self.dropDown.deselectRow(at: index)
            self.view.endEditing(true)
            self.dropDown.hide()
        }
    }
    
    @objc func refreshData() {
        self.fetchData()
    }
    
    // Set Data
    func setData() {
        let url = URL(string: AppInstance.instance.userProfile?.avatar ?? "")
        let indicator = SDWebImageActivityIndicator.medium
        self.userImageView.sd_imageIndicator = indicator
        DispatchQueue.global(qos: .userInteractive).async {
            self.userImageView.sd_setImage(with: url, placeholderImage: UIImage(named: ""))
        }
    }
    
}

// MARK: - Extensions

// MARK: Api Call
extension StoryViewController {
    
    private func fetchData() {
        if Connectivity.isConnectedToNetwork() {
            Async.background {
                StoriesManager.instance.getStories(session_Token: AppInstance.instance.sessionId ?? "", limit: 10, completionBlock: { (success, sessionError, serverError, error) in
                    if success != nil {
                        Async.main {
                            self.dismissProgressDialog {
                                self.storiesArray = success?.stories ?? []
                                self.tableView.reloadData()
                                self.tableView.refreshControl?.endRefreshing()
                            }
                        }
                    } else if sessionError != nil {
                        Async.main {
                            self.dismissProgressDialog {
                                self.view.makeToast(sessionError?.errors?.error_text)
                            }
                        }
                    } else if serverError != nil {
                        Async.main {
                            self.dismissProgressDialog {
                                self.view.makeToast(serverError?.errors?.error_text)
                            }
                        }
                    } else {
                        Async.main {
                            self.dismissProgressDialog {
                                self.view.makeToast(error?.localizedDescription)
                            }
                        }
                    }
                })
            }
        } else {
            self.dismissProgressDialog {
                self.view.makeToast(InterNetError)
            }
        }
    }
    
}

// MARK: StoryBottomdDelegate Methods
extension StoryViewController: StoryBottomDelegate {
    
    func handleAddStoryOptionTap(index: Int, optionName: String) {
        switch index {
        case 0:
            if let newVC = R.storyboard.colorEditor.colorEditorVC() {
                self.navigationController?.pushViewController(newVC, animated: true)
            }
        case 1:
            if let newVC = R.storyboard.popup.galleryAlertVC() {
                newVC.modalPresentationStyle = .overCurrentContext
                newVC.modalTransitionStyle = .crossDissolve
                newVC.delegate = self
                self.present(newVC, animated: true)
            }
        case 2:
            if let newVC = R.storyboard.story.deepARCameraController() {
                self.navigationController?.pushViewController(newVC, animated: true)
            }
        default:
            break
        }
    }
    
}

// MARK: - GalleryAlertVCDelegate Methods
extension StoryViewController: GalleryAlertVCDelegate {
    
    func handleImageGalleryTap(_ sender: UIButton) {
        if let newVC = R.storyboard.popup.imageAlertVC() {
            newVC.modalPresentationStyle = .overCurrentContext
            newVC.modalTransitionStyle = .crossDissolve
            newVC.delegate = self
            self.present(newVC, animated: true)
        }
    }
    
    func handleVideoGalleryTap(_ sender: UIButton) {
        if let newVC = R.storyboard.popup.videoAlertVC() {
            newVC.modalPresentationStyle = .overCurrentContext
            newVC.modalTransitionStyle = .crossDissolve
            newVC.delegate = self
            self.present(newVC, animated: true)
        }
    }
    
}

// MARK: ImageAlertVCDelegate Methods
extension StoryViewController: ImageAlertVCDelegate {
    
    func handleImageFromGalleryTap(_ sender: UIButton) {
        self.setupImagePicker(imagePickerSourceType: .PHOTO_LIBRARY)
    }
    
    func handleTakePictureFromCameraTap(_ sender: UIButton) {
        self.setupImagePicker(imagePickerSourceType: .CAMERA)
    }
    
    func setupImagePicker(imagePickerSourceType: ImagePickerSourceType) {
        self.view.endEditing(true)
        self.imagePicker.delegate = self
        switch imagePickerSourceType {
        case .CAMERA:
            if UIImagePickerController.isSourceTypeAvailable(.camera) {
                self.imagePicker.sourceType = .camera
            } else {
                if let messageAlertVC = R.storyboard.popup.messageAlertVC() {
                    messageAlertVC.messageText = "You don't have camera"
                    self.present(messageAlertVC, animated: true, completion: nil)
                    messageAlertVC.confirmButton.isHidden = true
                    return
                }
            }
        case .PHOTO_LIBRARY:
            self.imagePicker.sourceType = .photoLibrary
        }
        self.imagePicker.mediaTypes = ["public.image"]
        self.imagePicker.allowsEditing = false
        self.present(self.imagePicker, animated: true, completion: nil)
    }
    
}

// MARK: VideoAlertVCDelegate Methods
extension StoryViewController: VideoAlertVCDelegate {
    
    func handleVideoFromGalleryTap(_ sender: UIButton) {
        self.setupVideoPicker(imagePickerSourceType: .PHOTO_LIBRARY)
    }
    
    func handleRecordVideoFromCameraTap(_ sender: UIButton) {
        self.setupVideoPicker(imagePickerSourceType: .CAMERA)
    }
    
    func setupVideoPicker(imagePickerSourceType: ImagePickerSourceType) {
        self.view.endEditing(true)
        self.imagePicker.delegate = self
        switch imagePickerSourceType {
        case .CAMERA:
            if UIImagePickerController.isSourceTypeAvailable(.camera) {
                self.imagePicker.sourceType = .camera
            } else {
                if let messageAlertVC = R.storyboard.popup.messageAlertVC() {
                    messageAlertVC.messageText = "You don't have camera"
                    self.present(messageAlertVC, animated: true, completion: nil)
                    messageAlertVC.confirmButton.isHidden = true
                    return
                }
            }
        case .PHOTO_LIBRARY:
            self.imagePicker.sourceType = .photoLibrary
        }
        self.imagePicker.mediaTypes = ["public.movie"]
        self.imagePicker.allowsEditing = false
        self.present(self.imagePicker, animated: true, completion: nil)
    }
    
}

// MARK: UIImagePickerControllerDelegate & UINavigationControllerDelegate Methods
extension StoryViewController: UIImagePickerControllerDelegate & UINavigationControllerDelegate {
    
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
        picker.dismiss(animated: true) {
            if let image = info[.originalImage] as? UIImage {
                if let newVC = R.storyboard.story.addNewStoryVC() {
                    newVC.selectedImage = image
                    self.navigationController?.pushViewController(newVC, animated: true)
                }
            }
            if let videoURL = info[.mediaURL] as? URL {
                if let newVC = R.storyboard.story.videoEditorVC() {
                    newVC.isStory = true
                    newVC.videoUrl = videoURL
                    self.navigationController?.pushViewController(newVC, animated: true)
                }
            }
        }
    }
    
    func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
        picker.dismiss(animated: true, completion: nil)
    }
    
}

// MARK: TableView Setup
extension StoryViewController: UITableViewDelegate, UITableViewDataSource {
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if self.storiesArray.count == 0 {
            self.tableView.backgroundView = self.emptyView
        } else {
            self.tableView.backgroundView = nil
        }
        return self.storiesArray.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: R.reuseIdentifier.stories_TableCell.identifier) as! Stories_TableCell
        let object = self.storiesArray[indexPath.row]
        cell.setData(object: object)
        return cell
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        AppInstance.instance.addCount = AppInstance.instance.addCount! + 1
        if let newVC = R.storyboard.story.storyPreviewVC() {
            newVC.delegate = self
            newVC.arrayStories = self.storiesArray
            newVC.selectedStoryIndex = indexPath.row
            newVC.modalTransitionStyle = .coverVertical
            newVC.modalPresentationStyle = .overCurrentContext
            self.present(newVC, animated: true, completion: nil)
        }
    }
    
}

// MARK: UIViewControllerTransitioningDelegate Methods
extension StoryViewController: UIViewControllerTransitioningDelegate {
    
    func presentationController(forPresented presented: UIViewController, presenting: UIViewController?, source: UIViewController) -> UIPresentationController? {
        BottomSheetPresentationController(presentedViewController: presented, presenting: presenting)
    }
    
}

// MARK: StoryPreviewVCDelegate
extension StoryViewController: StoryPreviewVCDelegate {
    
    func handleStoryPreviewVCDismiss() {
        self.fetchData()
    }
    
}
