//
//  ViewAnswersViewController.swift
//  LMS
//
//  Created by Suraj Kumar Mandal on 20/10/23.
//

import UIKit

class ViewAnswersViewController: UIViewController {
    
    @IBOutlet var answersTableView: UITableView!
    @IBOutlet var continueButton: UIButton!
    
    var viewModel = ViewAnswersViewModel()
    
    var answersModel = [AssessmentResultModel]()
    var userId = Int()
    var sessionId = String()
    var assessmentId = Int()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        // Do any additional setup after loading the view.
        answersTableView.delegate = self
        answersTableView.dataSource = self
        
        // Enable self-sizing cells
        answersTableView.rowHeight = UITableView.automaticDimension
        answersTableView.estimatedRowHeight = 60 // You can adjust the estimated height as needed
    }
    
    override func viewWillAppear(_ animated: Bool) {
        getSubmittedAnswers()
    }
    
    func getSubmittedAnswers() {
        if Reachability.isConnectedToNetwork() {
            viewModel.getSubmittedAnswers(userId: userId, sessionId: sessionId, assessmentId: assessmentId) {
                // Update your UI components with the responseData
                self.answersModel = self.viewModel.answersModel
                print(self.answersModel)
                self.answersTableView.reloadData()
            }
        } 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 continueAction(_ sender: Any) {
        let vc = self.storyboard?.instantiateViewController(withIdentifier: "NewAssessmentViewController") as! NewAssessmentViewController
        self.navigationController?.pushViewController(vc, animated: true)
    }
    
}

extension ViewAnswersViewController: UITableViewDelegate, UITableViewDataSource {
    // MARK: - UITableViewDataSource
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return answersModel.count
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        // Add 1 for the question cell and 4 for the choice cells
        let choiceCount = answersModel[section].options?.count ?? 0
        return choiceCount + 1
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let answer = answersModel[indexPath.section]
        
        if indexPath.row == 0 {
            guard let cell = tableView.dequeueReusableCell(withIdentifier: "ViewAnswerQuestionTableViewCell", for: indexPath) as? ViewAnswerQuestionTableViewCell else {
                return UITableViewCell()
            }
            
            cell.questionLabel.text = "Q. \(answer.question ?? "")"
            
            return cell
        } else {
            guard let cell = tableView.dequeueReusableCell(withIdentifier: "ViewAnswerOptionsTableViewCell", for: indexPath) as? ViewAnswerOptionsTableViewCell else {
                return UITableViewCell()
            }
            
            let options = answer.options?[indexPath.row - 1].trimmingCharacters(in: .whitespaces)
            let selectedAnswer = answer.selectedAnswers?[0].trimmingCharacters(in: .whitespaces) as? String ?? ""
            let correctAnswer = answer.answers?[0] as? String ?? ""
            
            if options == selectedAnswer && options == correctAnswer {
                cell.choiceLabel.textColor = #colorLiteral(red: 0.4666666687, green: 0.7647058964, blue: 0.2666666806, alpha: 1)
                cell.dotImageView.tintColor = #colorLiteral(red: 0.4666666687, green: 0.7647058964, blue: 0.2666666806, alpha: 1)
            } else if options != selectedAnswer && options == correctAnswer {
                cell.choiceLabel.textColor = #colorLiteral(red: 0.4666666687, green: 0.7647058964, blue: 0.2666666806, alpha: 1)
                cell.dotImageView.tintColor = #colorLiteral(red: 0.4666666687, green: 0.7647058964, blue: 0.2666666806, alpha: 1)
            } else if options == selectedAnswer && options != correctAnswer {
                cell.choiceLabel.textColor = #colorLiteral(red: 0.7450980544, green: 0.1568627506, blue: 0.07450980693, alpha: 1)
                cell.dotImageView.tintColor = #colorLiteral(red: 0.7450980544, green: 0.1568627506, blue: 0.07450980693, alpha: 1)
            } else {
                cell.choiceLabel.textColor = UIColor.black
                cell.dotImageView.tintColor = UIColor.black
            }
            
            cell.choiceLabel?.text = answer.options?[indexPath.row - 1]
            
            return cell
        }
    }
    
    // MARK: - UITableViewDelegate
    
    func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {
        return 60.0 // An estimated height for your cells
    }
    
//    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
//        let answer = answersModel[indexPath.section]
//        
//        if indexPath.row == 0 {
//            // Calculate the dynamic height based on the label's content.
//            let cell = tableView.dequeueReusableCell(withIdentifier: "ViewAnswerQuestionTableViewCell") as! ViewAnswerQuestionTableViewCell
//            cell.questionLabel.text = "Q. \(answer.question ?? "")"
//            cell.setNeedsLayout()
//            cell.layoutIfNeeded()
//            let labelSize = cell.questionLabel.systemLayoutSizeFitting(UIView.layoutFittingCompressedSize)
//            return labelSize.height + 10.0 // Adjust this value for spacing as needed
//        } else {
//            // Calculate the dynamic height based on the label's content.
//            let cell = tableView.dequeueReusableCell(withIdentifier: "ViewAnswerOptionsTableViewCell") as! ViewAnswerOptionsTableViewCell
//            cell.choiceLabel.text = answer.options?[indexPath.row - 1]
//            cell.setNeedsLayout()
//            cell.layoutIfNeeded()
//            let labelSize = cell.choiceLabel.systemLayoutSizeFitting(UIView.layoutFittingCompressedSize)
//            return labelSize.height + 10.0 // Adjust this value for spacing as needed
//        }
//    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        let answer = answersModel[indexPath.section]
        
        if indexPath.row == 0 {
            // Calculate the height based on label content and constraints in your custom cell
            let cell = tableView.dequeueReusableCell(withIdentifier: "ViewAnswerQuestionTableViewCell") as! ViewAnswerQuestionTableViewCell
            
            // Set the cell's label text to the data for the current row
            cell.questionLabel.text = "Q. \(answer.question ?? "")"
            
            // Calculate the required height based on the label's content
            let labelSize = cell.questionLabel.sizeThatFits(CGSize(width: cell.questionLabel.frame.size.width, height: CGFloat.greatestFiniteMagnitude))
            
            return labelSize.height + 10
        } else {
            let cell = tableView.dequeueReusableCell(withIdentifier: "ViewAnswerOptionsTableViewCell") as! ViewAnswerOptionsTableViewCell
            cell.choiceLabel.text = answer.options?[indexPath.row - 1]
            
            // Calculate the required height based on the label's content
            let labelSize = cell.choiceLabel.sizeThatFits(CGSize(width: cell.choiceLabel.frame.size.width, height: CGFloat.greatestFiniteMagnitude))

            return labelSize.height + 10 // Add extra space for padding, adjust as needed
        }
    }
    
}