//
//  ReportController.swift
//  DealifyDeliveryBoy
//
//  Created by DT Team  on 2/17/21.
//  Copyright © 2021 Amine. All rights reserved.
//

import UIKit

protocol ReportDelegate {
    func onReported()
}

class ReportController: MyUIViewController, V_OptionDelegate, EmptyLayoutDelegate, ErrorLayoutDelegate {
    
    
    func onReloadAction(action: EmptyLayout) {
        
    }
    
    func onReloadAction(action: ErrorLayout) {
        
    }
    
 
    var delegate:ReportDelegate?
    
    
    var viewManager: LoaderViewManager =  LoaderViewManager()
    
    func setupViewloader()  {
        
        //setup view loader, Error, Empty layouts
        viewManager.setup(parent: self.view)
        viewManager.getEmptyLayout().delegate = self
        viewManager.getErrorLayout().delegate = self
       
    }
    
    let topBarTitle: EdgeLabel = {
        
        let titleLabel = EdgeLabel()
        
        titleLabel.text = ""
        titleLabel.textColor = UIColor.white
        titleLabel.font = UIFont.systemFont(ofSize: 20)
        
        return titleLabel
        
    }()
    
    func setupNavBarTitles() {
        
        
        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 = "Report Order #\(order!.id)".localized
        
        
        navigationBarItem.titleView = topBarTitle
        
    }
    
    
    
    func setupNavBarButtons() {
        
        let color = AppDesignUtils.defaultModeColor(dark: .white, light: Colors.primaryColor)
        
        //arrow back icon
        var arrowImage: UIImage? = nil
        if Utils.isRTL(){
            arrowImage = UIImage.init(icon: .ionicons(.iosArrowForward), size: CGSize(width: 30, height: 30), textColor: color)
        }else{
            arrowImage = UIImage.init(icon: .ionicons(.iosArrowBack), size: CGSize(width: 30, height: 30), textColor: color)
        }
        
        
        let customBarButtonItem = UIBarButtonItem(image: arrowImage!, style: .plain, target: self, action: #selector(onBackHandler))
        customBarButtonItem.setIcon(icon: .ionicons(.iosArrowBack), iconSize: 25, color: color)
        
        
        navigationBarItem.leftBarButtonItems = []
        navigationBarItem.rightBarButtonItems = []
        navigationBarItem.leftBarButtonItems?.append(customBarButtonItem)
        
    }
    
    @objc func onBackHandler()  {
        self.dismiss(animated: true)
    }
    
    var order: Order?
    @IBOutlet weak var navigationBar: UINavigationBar!
    @IBOutlet weak var navigationBarItem: UINavigationItem!
    @IBOutlet weak var scrollView: UIScrollView!
    @IBOutlet weak var stackview: UIStackView!
    var custom_edit_field: UITextField?
    
    
    @IBOutlet weak var report_btn_container: UIView!
    @IBOutlet weak var report_location_btn: UIButton!
    
    @IBAction func report_action(_ sender: Any) {
        
        
        guard let order = self.order else {
            return
        }
        guard let sess = Session.getInstance(), let user = sess.user else {
            return
        }
    
        
        if selected_reason_key == "reason_other" {
            selected_reason_value = (custom_edit_field?.text)!
        }
        
        //call api
        //make it as ongoing
        let parameters = [
            "order_id": String(order.id),
            "status": String(OrderDeliveryStatus.REPORTED),
            "delivery_id": String(user.id),
            "message": "\(selected_reason_key): \(selected_reason_value)",
        ]
        
        self.viewManager.showAsLoading()
      
        let api = SimpleRequestApi()
        api.run(url: OrderConstances.Api.API_DELIVERY_UPDATE_STATUS, parameters: parameters) { (parser) in
        
            if parser?.success == 1{
                
                if let del = self.delegate{
                    del.onReported()
                }
                
                self.dismiss(animated: true)
            
            }
            
         
        }
        
        
    }
    
    func setupBotton(){
    
        self.report_location_btn.setTitle("Report".localized, for: .normal)
        self.report_location_btn.initBoldFont()
        self.report_location_btn.setTitleColor(.white, for: .normal)
        
        self.report_location_btn.backgroundColor = Colors.primaryColor
        self.report_btn_container.backgroundColor = Colors.primaryColor
        
    }
    
    var reasons: [String: String] = [
        "multiple_orders": "Multiple orders",
        "Difficult_route": "Difficult route",
        "The_roads_are_blocked": "The roads are blocked",
        "Distance_too_long": "Distance too long",
    ]
    
    override func viewDidLoad() {
        
        setupNavBarTitles()
        setupNavBarButtons()
        setupViewloader()
        setupBotton()
        
        stackview.removeAllArrangedSubviews()
        
        
        selected_reason_key = "multiple_orders"
        selected_reason_value = "Multiple orders"
        
        
    
        for (key, value) in reasons {
            let option = V_Option.newInstance(option: O_Option(label: value, value: key,custom_value: false))
            option.delegate = self
            stackview.addArrangedSubview(option)
        }
       
    
        let option2 = V_Option.newInstance(option: O_Option(label: "Other", value: "reason_other",custom_value: true))
        option2.o?.custom_value = true
        option2.delegate = self
        stackview.addArrangedSubview(option2)
        
        
        custom_edit_field = UITextField(frame: CGRect(x: 0, y: 0, width: stackview.frame.width, height: 50))
        custom_edit_field!.placeholder = "Write the reason...".localized
        let myColor = UIColor.gray.withAlphaComponent(0.6)
        custom_edit_field!.layer.borderColor = myColor.cgColor
        custom_edit_field!.layer.borderWidth = 1.0
        let paddingView = UIView(frame: CGRect.init(x: 0, y: 0, width: 10, height: custom_edit_field!.frame.height))
        custom_edit_field!.leftView = paddingView
        custom_edit_field!.leftViewMode = .always
        custom_edit_field!.addShadowView()
        custom_edit_field!.heightAnchor.constraint(equalToConstant: 50).isActive = true
        stackview.addArrangedSubview(custom_edit_field!)
        
        custom_edit_field!.isHidden = true
        
    }
    
    var selected_reason_key = ""
    var selected_reason_value = ""
    
    func onClicked(option: O_Option) {
        
        Utils.printDebug("\(option)")
        
        //uncheck_all
        for subview in self.stackview.subviews{
            
            
            if subview is V_Option{
               
                let opt_view = subview as! V_Option
                
                if option.value == opt_view.o!.value{
                    opt_view.check_radio()
                    
                    selected_reason_key = option.value
                    selected_reason_value = option.value
                    
                }else{
                    opt_view.uncheck_radio()
                }
                
                if opt_view.o!.custom_value && opt_view.is_checked{
                    
                    //display textedit
                    custom_edit_field!.isHidden = false
                    view.layoutIfNeeded()
                  
                }else{
                    
                    custom_edit_field!.isHidden = true
                    view.layoutIfNeeded()
                  
                }
               
            }
            
        }
        
    }
    
   
    
}
