//
//  NonEMIViewController.swift
//  Product Calculator
//
//  Created by Suraj Kumar Mandal on 07/12/21.
//

import UIKit
import SideMenu

class NonEMIViewController: UIViewController {

    @IBOutlet var loanAmountTF: UITextField!
    @IBOutlet var interestRateTF: UITextField!
    @IBOutlet var loanTermTF: UITextField!
    @IBOutlet var interestPayoutFrequencyTF: UITextField!
    @IBOutlet var loanStartDateTF: UITextField!
    
    fileprivate let customPicker = ToolbarPickerView()
    var menu = Int()
    
    var viewModel = NonEMIViewModel()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        // Do any additional setup after loading the view.
        viewModel.delegate = self
        
        loanAmountTF.delegate = self
        interestRateTF.delegate = self
        loanTermTF.delegate = self
        interestPayoutFrequencyTF.delegate = self
        interestPayoutFrequencyTF.delegate = self
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        
        navigationController?.navigationBar.barStyle = .black
        setupUI()
    }
    
    override var preferredStatusBarStyle: UIStatusBarStyle {
        return .lightContent
    }
    
    func setupUI() {
        self.navigationItem.title = AppConstant.MENU_TITLE[menu]
        self.navigationItem.hidesBackButton = true
        let menuBarButtonItem = UIBarButtonItem(image: UIImage(systemName: "line.3.horizontal"), style: .plain, target: self, action: #selector(openMenu))
        self.navigationItem.leftBarButtonItem  = menuBarButtonItem
        if #available(iOS 13, *) {
            let appearance = UINavigationBarAppearance()
            appearance.backgroundColor = .systemBlue
            appearance.titleTextAttributes = [.foregroundColor: UIColor.white]
            appearance.largeTitleTextAttributes = [.foregroundColor: UIColor.white]
            
            navigationController?.navigationBar.tintColor = .white
            navigationController?.navigationBar.standardAppearance = appearance
            navigationController?.navigationBar.compactAppearance = appearance
            navigationController?.navigationBar.scrollEdgeAppearance = appearance
        }
        
        //Date Picker
        loanStartDateTF.datePicker(target: self,
                                 doneAction: #selector(doneAction),
                                 cancelAction: #selector(cancelAction),
                                 datePickerMode: .date)
        loanStartDateTF.delegate = self
        
        //Picker View
        createPickerView()
    }
    
    @objc func openMenu(_ sender: Any) {
        let menu = storyboard!.instantiateViewController(withIdentifier: "SideMenuNavigationController") as! SideMenuNavigationController
        present(menu, animated: true, completion: nil)
    }
    
    func createPickerView() {
        self.interestPayoutFrequencyTF.inputView = self.customPicker
        self.interestPayoutFrequencyTF.inputAccessoryView = self.customPicker.toolbar
        
        self.customPicker.delegate = self
        self.customPicker.dataSource = self
        self.customPicker.toolbarDelegate = self
    }
    
    @objc
    func cancelAction() {
        self.loanStartDateTF.resignFirstResponder()
    }
    
    @objc
    func doneAction() {
        if let datePickerView = self.loanStartDateTF.inputView as? UIDatePicker {
            let dateFormatter = DateFormatter()
            dateFormatter.dateFormat = AppConstant.dateFormat1
            let dateString = dateFormatter.string(from: datePickerView.date)
            self.loanStartDateTF.text = dateString
            
            print(datePickerView.date)
            print(dateString)
            
            self.loanStartDateTF.resignFirstResponder()
        }
    }
    
    func dataValidation() {
        if loanAmountTF.text?.isEmpty == true {
            self.view.makeToast("Enter loan amount!")
        } else if interestRateTF.text?.isEmpty == true {
            self.view.makeToast("Enter interest rate!")
        } else if loanTermTF.text?.isEmpty == true {
            self.view.makeToast("Enter loan term!")
        } else if interestPayoutFrequencyTF.text?.isEmpty == true {
            self.view.makeToast("Select interest payout frequency!")
        } else if loanStartDateTF.text?.isEmpty == true {
            self.view.makeToast("Select loan start date!")
        } else {
            if Reachability.isConnectedToNetwork() {
                let interest = interestRateTF.text!
                let interestRate = Double(interest)!/100.0
                viewModel.getNonEMILoan(loanAmount: loanAmountTF.text!, interestRate: String(interestRate), loanTenure: loanTermTF.text!, interestPaymentFrequency: interestPayoutFrequencyTF.text!, loanStartDate: loanStartDateTF.text!)
            } else {
                Alert.showInternetFailureAlert(on: self)
            }
        }
    }
    
    
    /*
     // MARK: - Navigation
     
     // In a storyboard-based application, you will often want to do a little preparation before navigation
     override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
     // Get the new view controller using segue.destination.
     // Pass the selected object to the new view controller.
     }
     */
    
    @IBAction func saveAction(_ sender: Any) {
        self.dataValidation()
    }
    
    @IBAction func undoAction(_ sender: Any) {
        loanAmountTF.text = nil
        interestRateTF.text = nil
        loanTermTF.text = nil
        interestPayoutFrequencyTF.text = nil
        interestPayoutFrequencyTF.text = nil
    }
    
}

extension NonEMIViewController: UIPickerViewDelegate, UIPickerViewDataSource {
    // MARK: UIPickerView Delegation
    
    func numberOfComponents(in pickerView: UIPickerView) -> Int {
        return 1
    }
    
    func pickerView( _ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
        return AppConstant.INTEREST_PAYOUT_FREQUENCY.count
    }
    
    func pickerView( _ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
        return AppConstant.INTEREST_PAYOUT_FREQUENCY[row]
    }
    
    func pickerView( _ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
        interestPayoutFrequencyTF.text = AppConstant.INTEREST_PAYOUT_FREQUENCY[row]
    }
}

extension NonEMIViewController: UITextFieldDelegate {
    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        switch textField {
        case interestPayoutFrequencyTF:
            return false
        default:
            return true
        }
    }
    
    // when user select a textfield, this method will be called
    func textFieldDidBeginEditing(_ textField: UITextField) {
        switch textField {
        case interestPayoutFrequencyTF:
            customPicker.reloadAllComponents()
        default:
            break
        }
    }
}

extension NonEMIViewController: ToolbarPickerViewDelegate {
    func didTapDone() {
        let row = self.customPicker.selectedRow(inComponent: 0)
        self.customPicker.selectRow(row, inComponent: 0, animated: false)
        self.interestPayoutFrequencyTF.text = AppConstant.INTEREST_PAYOUT_FREQUENCY[row]
        self.interestPayoutFrequencyTF.resignFirstResponder()
    }
    
    func didTapCancel() {
        self.interestPayoutFrequencyTF.text = nil
        self.interestPayoutFrequencyTF.resignFirstResponder()
    }
}

extension NonEMIViewController: NonEMIViewProtocol {
    func navigate(_ data: EMILoanOriginalModel) {
        DispatchQueue.main.async {
            let nonEMISummaryVC = self.storyboard?.instantiateViewController(withIdentifier: "NonEMISummaryViewController") as! NonEMISummaryViewController
            nonEMISummaryVC.nonEmiModel = data
            self.navigationController?.pushViewController(nonEMISummaryVC, animated: true)
        }
    }
    
    func startLoader() {
        ActivityIndicator.start()
    }
    
    func stopLoader() {
        ActivityIndicator.stop()
    }
    
    func showError(error: String) {
        self.view.makeToast(error)
    }
}
