//
//  OCReportController.swift
//  NearbyStoresPro
//
//  Created by Amine  on 11/12/2021.
//  Copyright © 2021 Amine. All rights reserved.
//

import UIKit
import Atributika
import AssistantKit



class OCReportController: MyUIViewController, UITableViewDelegate, UITableViewDataSource{
    
    var report_reasons: [String] = [
        "Scam or fraud",
        "Sale of illegal",
        "Regulated goods",
        "Something else"
    ]

    
    @IBOutlet weak var navigationBar: UINavigationBar!
    @IBOutlet weak var navigationBarItem: UINavigationItem!
    @IBOutlet weak var uitableView: UITableView!
    @IBOutlet weak var thankYou_label: UILabel!
    @IBOutlet weak var DONE_btn: UIButton!
    @IBAction func doneAction(_ sender: Any) {
        
        self.dismiss(animated: true)
        
    }
    
    static func startVC(controller: MyUIViewController, ro: ReportObject) {

        let sb = UIStoryboard(name: "OCReport", bundle: nil)
        
        if sb.instantiateInitialViewController() != nil {
            let ms: OCReportController = sb.instantiateViewController(withIdentifier: "OCReportVC") as! OCReportController
            ms.reportObject = ro
            controller.present(ms, animated: true)
        }else{
            
        }

    }
    
    var reportObject: ReportObject?

    // These strings will be the data for the table view cells
       
       let cellReuseIdentifier = "cell"

       override func viewDidLoad() {
           super.viewDidLoad()
        
        thankYou_label.textColor = Colors.black
        thankYou_label.initBolodFont(size: 16)
        thankYou_label.text = "Thanks for letting us know".localized
        
        DONE_btn.backgroundColor = Colors.primaryColor
        DONE_btn.setTitleColor(.white, for: .normal)
        DONE_btn.setTitle("DONE".localized, for: .normal)
        
        
        thankYou_label.isHidden = true
        DONE_btn.isHidden = true

           // It is possible to do the following three things in the Interface Builder
           // rather than in code if you prefer.
           uitableView.register(UITableViewCell.self, forCellReuseIdentifier: cellReuseIdentifier)
            uitableView.delegate = self
            uitableView.dataSource = self
        
        
        if let ro = reportObject{
            setupCustomNavBar(title: "\("Report".localized): \(ro.title)")
            setupNavBarButtons()
        }else{
            dismiss(animated: true)
        }
       
       }
    
    let topBarTitle: EdgeLabel = {
        
        let titleLabel = EdgeLabel()
        
        titleLabel.text = ""
        titleLabel.textColor = UIColor.white
        titleLabel.font = UIFont.systemFont(ofSize: 20)
        
        return titleLabel
        
    }()
    
    func setupCustomNavBar(title: String) {
        
        
        let rect = CGRect(x: 0, y: 0, width: view.frame.width - 32, height: view.frame.height)
        topBarTitle.frame = rect
        topBarTitle.textColor = AppDesignUtils.defaultModeColor(dark: .white, light: Colors.primaryColor)

        topBarTitle.font = UIFont(name: AppConfig.Design.Fonts.regular, size: 17)
        topBarTitle.leftTextInset = 5
        
        
        topBarTitle.text = title
        
        navigationBarItem.titleView = topBarTitle
        
    }
    
    
    func setupNavBarButtons() {
        
        //arrow back icon
        var arrowImage: UIImage? = nil
        if Utils.isRTL(){
            arrowImage = UIImage.init(icon: .ionicons(.iosArrowForward), size: CGSize(width: 30, height: 30), textColor: Colors.darkColor)
        }else{
            arrowImage = UIImage.init(icon: .ionicons(.iosArrowBack), size: CGSize(width: 30, height: 30), textColor: Colors.darkColor)
        }
        
        
        let _color = AppDesignUtils.defaultModeColor(dark: .white, light: Colors.primaryColor)

        let customBackButtonItem = UIBarButtonItem(image: arrowImage!, style: .plain, target: self, action: #selector(onBackHandler))
        customBackButtonItem.setIcon(icon: .ionicons(.iosArrowBack), iconSize: 25, color: _color)
        
    
        navigationBarItem.leftBarButtonItems = []
        navigationBarItem.rightBarButtonItems = []
        
        if(config.backHome){
            navigationBarItem.leftBarButtonItems?.append(customBackButtonItem)
        }
    
    }
    
    @objc func onBackHandler()  {
        
        if let controller = self.navigationController{
            controller.popViewController(animated: true)
        }else{
            self.dismiss(animated: true)
        }
        
    }
    

       // number of rows in table view
       func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
           return self.report_reasons.count
       }

       // create a cell for each table view row
       func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

        let cell:UITableViewCell = (uitableView.dequeueReusableCell(withIdentifier: cellReuseIdentifier) as UITableViewCell?)!

           cell.textLabel?.text = self.report_reasons[indexPath.row]

           return cell
       }

       // method to run when table view cell is tapped
       func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
           print("You tapped cell number \(indexPath.row).")
        
        
        let selected_reason = report_reasons[indexPath.row]
       
        if(selected_reason == "Something else"){
            
            
            //1. Create the alert controller.
            let alert = UIAlertController(title: "Report".localized, message: "Help us to understand the problem".localized, preferredStyle: .alert)

            //2. Add the text field. You can configure it however you need.
    
            alert.addTextField { (textField) in
                textField.text = ""
            }

            // 3. Grab the value from the text field, and print it when the user clicks OK.
            alert.addAction(UIAlertAction(title: "OK".localized, style: .default, handler: { [weak alert] (_) in
                let textField = alert?.textFields![0] // Force unwrapping because we know it exists.
                
                
                if let or = self.reportObject{
                    self.uploadReport(
                        title: or.title,
                        content: "<b>Reported content:</b> \""+or.link+"\", <b>Problem:</b> \""+textField!.text!+"\" ",
                        owner_user_id: or.owner_user_id,
                        reported_by_user_id: or.reported_by_user_id
                    )
                }
                
                //print("Text field: \(textField!.text)")
            }))

            // 4. Present the alert.
            self.present(alert, animated: true, completion: nil)
            
        }else{
            if let or = reportObject{
                uploadReport(
                    title: or.title,
                    content: "Reported content \""+or.link+"\" reason: \""+selected_reason+"\" ",
                    owner_user_id: or.owner_user_id,
                    reported_by_user_id: or.reported_by_user_id
                )
            }
        }
       
    }
    
    func uploadReport(
        title: String,
        content: String,
        owner_user_id: Int,
        reported_by_user_id: Int
    ) {
        
        
        MyProgress.show(parent: self.view)
        
        let paramaters = [
            "title": title,
            "owner_user_id": "\(owner_user_id)",
            "reported_by_user_id": "\(reported_by_user_id)",
            "content": content,
        ]
        
        let api = SimpleRequestApi()
        api.run(url: AppConfig.Api.base_url_api+"/"+Constances.Api.API_VERSION+"/setting/content_report"
                , parameters: paramaters) { parser in
            
            
            MyProgress.dismiss()
        
            self.uitableView.isHidden = true
            self.thankYou_label.isHidden = false
            self.DONE_btn.isHidden = false
            
        }
        
        
    }

   
    
}
