//
//  ChatWithExpertViewController.swift
//  MyTatvaCare
//
//  Created by Nirav Ramani on 28/05/25.
//

import UIKit

class ChatWithExpertViewController: UIViewController {
    
    @IBOutlet weak var tableView: UITableView!
    @IBOutlet weak var buttonBack: UIButton!
    @IBOutlet weak var bottomButton: CustomOverlayButton!
    @objc var isOnlyThis: Bool = false
    let chatOptions = ["Purchasing New CGM", "Connecting My CGM", "Having troubles after connection"]
    var selectedIndex = -1
    
    enum enumTableSection: Int, CaseIterable {
        case separator
        case verticalLabel
        case label
        case chatOption
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        setupLayout()
        
    }
    
    func setupLayout() {
        buttonBack.setImage(loadImage(named: "ic_back"), for: .normal)
        
        tableView.delegate = self
        tableView.dataSource = self
        tableView.registerNibs([VerticalLabelsTVC.self,
                                SeparatorTVC.self,
                                ChatOptionTVC.self,
                                LabelTVC.self])
        tableView.reloadData()
        bottomButton.disable()
        buttonBack.titleLabel?.font = FontManager.font(ofSize: 16, weight: .medium)
        bottomButton.labelText = "Proceed"
        bottomButton.showLeftWhatsappImage()
        
        let payload = [
            "screen_name": "support screen",
            "status": "cgm_WA_support_clicked"
        ]

        NotificationCenter.default.post(
            name: Notification.Name("cgmWAsupportclicked"),
            object: nil,
            userInfo: payload
        )


        bottomButton.buttonTapCallback = {
            var help = ""
            if self.selectedIndex == 0 {
                help = "purchasing new cgm"
            } else if self.selectedIndex == 1{
                help = "connecting my cgm"
            } else {
                help = "having troubles after connection"
            }
            
            let payload = [
                "help": help,
                "status": "cgm_WA_support_proceed_clicked"
            ]

            NotificationCenter.default.post(
                name: Notification.Name("cgmWAsupportproceedclicked"),
                object: nil,
                userInfo: payload
            )
            
            
            if let url = URL(string: "https://wa.aisensy.com/aaa1qv") {
                if UIApplication.shared.canOpenURL(url) {
                    UIApplication.shared.open(url, options: [:], completionHandler: nil)
                } else {
                    print("Cannot open URL")
                }
            }
            //let vc = ConnectToTransmitterViewController.instantiate(fromStoryboard: Enum_stroyboard.Main.rawValue)
            //self.navigationController?.pushViewController(vc, animated: false)
        }
        
    }
    
    @IBAction func buttonBackTouchUpInside(_ sender: UIButton) {
        if isOnlyThis {
            if let rootVC = UIApplication.shared.connectedScenes
                .compactMap({ ($0 as? UIWindowScene)?.windows.first?.rootViewController })
                .first {
                rootVC.dismiss(animated: true, completion: nil)
            } else if let rootViewController = UIApplication.shared.keyWindow?.rootViewController {
                rootViewController.dismiss(animated: true, completion: nil)
            }
        } else {
            self.navigationController?.popViewController(animated: true)
        }
        
    }
}

extension ChatWithExpertViewController: UITableViewDelegate, UITableViewDataSource {
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return enumTableSection.allCases.count
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        switch enumTableSection(rawValue: section) {
        case .chatOption:
            return chatOptions.count
        default:
            return 1
        }
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return UITableView.automaticDimension
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        switch enumTableSection(rawValue: indexPath.section)! {
        case .separator:
            let cell: SeparatorTVC = tableView.dequeueReusableCell(for: indexPath)
            cell.selectionStyle = .none
            return cell
        case .verticalLabel:
            let cell: VerticalLabelsTVC = tableView.dequeueReusableCell(for: indexPath)
            cell.label1.isHidden = true
            cell.label2.text = "Chat with our experts"
            cell.label2.textAlignment = .left
            cell.label3.text = "We are here to help. Let us know where you are facing any difficulty and chat with our expert team who will guide you in this journey"
            cell.label3.textAlignment = .left
            cell.selectionStyle = .none
            return cell
        case .label:
            let cell: LabelTVC = tableView.dequeueReusableCell(for: indexPath)
            cell.descLabel.text = "What do you want help with?"
            cell.selectionStyle = .none
            return cell
        case .chatOption:
            let cell: ChatOptionTVC = tableView.dequeueReusableCell(for: indexPath)
            cell.descLabel.text = chatOptions[indexPath.row]
            cell.descLabel.textColor = CustomColor.shared.gray
            cell.setSelectedView(isSelected: selectedIndex == indexPath.row)
            cell.selectionStyle = .none
            return cell
        }
    }
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        switch enumTableSection(rawValue: indexPath.section) {
        case .chatOption:
            selectedIndex = indexPath.row
            bottomButton.enable()
            tableView.reloadData()
        default:
            break
        }
    }
}
