//
//  EMILoanViewController.swift
//  Product Calculator
//
//  Created by Suraj Kumar Mandal on 01/12/21.
//

import UIKit
import SideMenu
import Toast_Swift

class EMILoanViewController: UIViewController {
    
    @IBOutlet var loanCategoryTF: UITextField!
    @IBOutlet var loanDescriptionTF: UITextFieldWithDoneButton!
    @IBOutlet var loanProviderTF: UITextFieldWithDoneButton!
    @IBOutlet var loanAmountTypeTF: UITextField!
    @IBOutlet var loanStartDateTF: UITextField!
    @IBOutlet var originalLoanTenureTF: UITextFieldWithDoneButton!
    @IBOutlet var originalLoanAmountTF: UITextFieldWithDoneButton!
    @IBOutlet var originalInterestRateTF: UITextFieldWithDoneButton!
    
    @IBOutlet var loanStartDateLabel: UILabel!
    @IBOutlet var originalLoanTenureLabel: UILabel!
    @IBOutlet var originalLoanAmountLabel: UILabel!
    @IBOutlet var originalInterestRateLabel: UILabel!
    
    fileprivate let customPicker = ToolbarPickerView()
    var activeTextField = 0
    var menu = Int()
    
    var viewModel = EMILoanViewModel()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        // Do any additional setup after loading the view.
        viewModel.delegate = self
        
        loanCategoryTF.delegate = self
        loanDescriptionTF.delegate = self
        loanProviderTF.delegate = self
        loanAmountTypeTF.delegate = self
        loanStartDateTF.delegate = self
        originalLoanTenureTF.delegate = self
        originalLoanAmountTF.delegate = self
        originalInterestRateTF.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.loanCategoryTF.inputView = self.customPicker
        self.loanCategoryTF.inputAccessoryView = self.customPicker.toolbar
        
        self.loanAmountTypeTF.inputView = self.customPicker
        self.loanAmountTypeTF.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
            //self.dateOfBirth = dateString
            
            print(datePickerView.date)
            print(dateString)
            
            self.loanStartDateTF.resignFirstResponder()
        }
    }
    
    func dataValidation() {
        if loanCategoryTF.text?.isEmpty == true {
            self.view.makeToast("Select loan category!")
        } else if loanDescriptionTF.text?.isEmpty == true {
            self.view.makeToast("Fill loan description!")
        } else if loanProviderTF.text?.isEmpty == true {
            self.view.makeToast("Fill loan provider!")
        } else if loanAmountTypeTF.text?.isEmpty == true {
            self.view.makeToast("Select loan amount type!")
        } else if loanStartDateTF.text?.isEmpty == true {
            self.view.makeToast("Select loan start date!")
        } else if originalLoanTenureTF.text?.isEmpty == true {
            self.view.makeToast("Fill original loan tenure!")
        } else if originalLoanAmountTF.text?.isEmpty == true {
            self.view.makeToast("Fill original loan amount!")
        } else if originalInterestRateTF.text?.isEmpty == true {
            self.view.makeToast("Fill original interest rate!")
        } else {
            if Reachability.isConnectedToNetwork() {
                if loanAmountTypeTF.text == "Original Loan Amount(Rs)" {
                    let interest = originalInterestRateTF.text!
                    let interestPercent = Double(interest)!/100.0
                    viewModel.getEMIOriginalLoan(loanFlag: "Y", originalInterestRate: String(interestPercent), originalLoanAmount: originalLoanAmountTF.text!, loanStartDate: loanStartDateTF.text!, loanTenure: originalLoanTenureTF.text!)
                } else {
                    let interest = originalLoanAmountTF.text!
                    let interestPercent = Double(interest)!/100.0
                    viewModel.getEMIOutstandingLoan(loanFlag: "N", originalInterestRate: String(interestPercent), originalLoanAmount: originalLoanTenureTF.text!, loanDayout: loanStartDateTF.text!, loanEMIAmt: originalInterestRateTF.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) {
        loanCategoryTF.text = nil
        loanDescriptionTF.text = nil
        loanProviderTF.text = nil
        loanAmountTypeTF.text = nil
        loanStartDateTF.text = nil
        originalLoanTenureTF.text = nil
        originalLoanAmountTF.text = nil
        originalInterestRateTF.text = nil
    }
    
}

extension EMILoanViewController: UIPickerViewDelegate, UIPickerViewDataSource {
    // MARK: UIPickerView Delegation
    
    func numberOfComponents(in pickerView: UIPickerView) -> Int {
        return 1
    }
    
    func pickerView( _ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
        switch activeTextField
        {
        case 1:
            return AppConstant.LOAN_CATEGORY.count
        case 2:
            return AppConstant.LOAN_AMOUNT_TYPE.count
        default:
            return 0
        }
    }
    
    func pickerView( _ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
        switch activeTextField
        {
        case 1:
            return AppConstant.LOAN_CATEGORY[row]
        case 2:
            return AppConstant.LOAN_AMOUNT_TYPE[row]
        default:
            return ""
        }
    }
    
    func pickerView( _ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
        switch activeTextField
        {
        case 1:
            loanCategoryTF.text = AppConstant.LOAN_CATEGORY[row]
        case 2:
            loanAmountTypeTF.text = AppConstant.LOAN_AMOUNT_TYPE[row]
            if loanAmountTypeTF.text == "Original Loan Amount(Rs)" {
                loanStartDateLabel.text = "Loan Start Date :"
                originalLoanTenureLabel.text = "Original Loan Tenure(Years) :"
                originalLoanAmountLabel.text = "Original Loan Amount(Rs) :"
                originalInterestRateLabel.text = "Original Interest Rate(%) :"
            } else {
                loanStartDateLabel.text = "Reference Date :"
                originalLoanTenureLabel.text = "Outstanding Principal Today(Rs) :"
                originalLoanAmountLabel.text = "Current Interest Rate(%) :"
                originalInterestRateLabel.text = "Current EMI Amount(Rs) :"
            }
        default:
            break
        }
    }
}

extension EMILoanViewController: UITextFieldDelegate {
    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        switch textField {
        case loanCategoryTF:
            return false
        case loanAmountTypeTF:
            return false
        default:
            return true
        }
    }
    
    // when user select a textfield, this method will be called
    func textFieldDidBeginEditing(_ textField: UITextField) {
        switch textField {
        case loanCategoryTF:
            activeTextField = 1
            customPicker.reloadAllComponents()
        case loanAmountTypeTF:
            activeTextField = 2
            customPicker.reloadAllComponents()
        default:
            activeTextField = 0
        }
    }
}

extension EMILoanViewController: ToolbarPickerViewDelegate {
    func didTapDone() {
        switch activeTextField {
        case 1:
            let row = self.customPicker.selectedRow(inComponent: 0)
            self.customPicker.selectRow(row, inComponent: 0, animated: false)
            self.loanCategoryTF.text = AppConstant.LOAN_CATEGORY[row]
            self.loanCategoryTF.resignFirstResponder()
        case 2:
            let row = self.customPicker.selectedRow(inComponent: 0)
            self.customPicker.selectRow(row, inComponent: 0, animated: false)
            self.loanAmountTypeTF.text = AppConstant.LOAN_AMOUNT_TYPE[row]
            self.loanAmountTypeTF.resignFirstResponder()
        default:
            return
        }
    }
    
    func didTapCancel() {
        switch activeTextField {
        case 1:
            self.loanCategoryTF.text = nil
            self.loanCategoryTF.resignFirstResponder()
        case 2:
            self.loanAmountTypeTF.text = nil
            self.loanAmountTypeTF.resignFirstResponder()
        default:
            return
        }
    }
}

extension EMILoanViewController: EMILoanViewProtocol {
    func navigateOriginal(_ data: EMILoanOriginalModel) {
        DispatchQueue.main.async {
            let emiOriginalSummaryVC = self.storyboard?.instantiateViewController(withIdentifier: "EMILoanSummaryViewController") as! EMILoanSummaryViewController
            emiOriginalSummaryVC.emiOriginalModel = data
            self.navigationController?.pushViewController(emiOriginalSummaryVC, animated: true)
        }
    }
    
    func navigateOutstanding(_ data: EMILoanOutstandingModel) {
        DispatchQueue.main.async {
            let emiOutstandingSummaryVC = self.storyboard?.instantiateViewController(withIdentifier: "EMILoanSummaryViewController") as! EMILoanSummaryViewController
            emiOutstandingSummaryVC.emiOutstandingModel = data
            self.navigationController?.pushViewController(emiOutstandingSummaryVC, animated: true)
        }
    }
    
    func startLoader() {
        ActivityIndicator.start()
    }
    
    func stopLoader() {
        ActivityIndicator.stop()
    }
    
    func showError(error: String) {
        self.view.makeToast(error)
    }
}

