//
//  AV_AddVC.swift
//  anniversary_Project
//
//  Created by 忆海16 on 2024/4/15.
//

import UIKit
import BRPickerView
import Photos
import SVProgressHUD
import WCDBSwift

import Alamofire
import FirebaseRemoteConfig

class AV_AddVC: AV_RootVC {
    
    
    @IBOutlet weak var scheduleImagV: UIImageView!
    
    
    @IBOutlet weak var schedLabel: UILabel!
    
    
    @IBOutlet weak var birthdayImagV: UIImageView!
    
    
    @IBOutlet weak var birthdayLabel: UILabel!
    
    
    @IBOutlet weak var memoryImagV: UIImageView!
    
    
    @IBOutlet weak var memoryLabel: UILabel!
    
    
    @IBOutlet weak var titleLabel: UITextField!
    
    
    @IBOutlet weak var datetextF: UITextField!
    
    
    @IBOutlet weak var switchSelect: UISwitch!
    
    
    @IBOutlet weak var deleteBtn: UIButton!
    
    
    @IBOutlet weak var cameraImagV: UIImageView!
    
    
    @IBOutlet weak var scheduleV: UIView!
    
    
    @IBOutlet weak var birthdayV: UIView!
    
    
    @IBOutlet weak var memoryV: UIView!
    
    
    
    var type:String = "Schedule"
    
    var isremind:Bool = true
    
    var model:UserModel?
    var typeedit:Int = 0
    
    var dataUpdateClosure: ((UserModel) -> Void)?
    
    var retryAttempt = 0.0
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        cameraImagV.layer.cornerRadius = 8
        cameraImagV.clipsToBounds = true
        cameraImagV.isUserInteractionEnabled = true
        let tapGesture = UITapGestureRecognizer(target: self, action: #selector(imageTouch))
        cameraImagV.addGestureRecognizer(tapGesture)
        
    }
    
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
    
        
        
        if typeedit == 0{
            self.cameraImagV.image = UIImage(named: "camera")
        }else{
            self.titleLabel.text = model?.name
            self.datetextF.text = model?.date
            self.switchSelect.isOn = ((model?.notificationEnabled) != nil)
            let image = model?.getImage()
            self.cameraImagV.image = image
        }
        
        self.scheduleImagV.image = UIImage(named: "schedule_s")
        self.schedLabel.alpha = 1.0
        
        self.birthdayImagV.image = UIImage(named: "birthday_n")
        self.birthdayLabel.alpha = 0.5
        
        self.memoryImagV.image = UIImage(named: "memor_n")
        self.memoryLabel.alpha = 0.5
        
        scheduleV.layer.cornerRadius = 8
        scheduleV.layer.borderWidth = 1
        scheduleV.layer.borderColor = UIColor.hexSting(color: "#4B92FE", alpha: 0.5).cgColor
        scheduleV.backgroundColor = .white
        
        birthdayV.layer.cornerRadius = 8
        birthdayV.layer.borderWidth = 0
        birthdayV.layer.borderColor = UIColor.hexSting(color: "#4B92FE", alpha: 0.5).cgColor
        birthdayV.backgroundColor = .hexSting(color: "#FAFAFA", alpha: 1)
        
        memoryV.layer.cornerRadius = 8
        memoryV.layer.borderWidth = 0
        memoryV.layer.borderColor = UIColor.hexSting(color: "#4B92FE", alpha: 0.5).cgColor
        memoryV.backgroundColor = .hexSting(color: "#FAFAFA", alpha: 1)
        
        if self.cameraImagV.image == UIImage(named: "camera"){
            self.deleteBtn.isHidden = true
        }else{
            self.deleteBtn.isHidden = false
        }
    }
    
    @IBAction func back(_ sender: Any) {

            if self.typeedit == 0{
                self.dismiss(animated: true)
            }else{
                self.navigationController?.popViewController(animated: true)
            }
        
    }
    
    @IBAction func sure(_ sender: Any) {
        
        if let title = self.titleLabel.text, title.count > 0 && title.count <= 50 {
            if self.datetextF.text!.count != 0{
                if cameraImagV.image != UIImage(named: "camera"){
                    //                    print("---成功")
                    
                    if self.typeedit == 0{
                        let user = UserModel()
                        let uuid = UUID()
                        user.uid = uuid.uuidString
                        user.name = self.titleLabel.text!
                        user.date = self.datetextF.text!
                        user.notificationEnabled = self.isremind
                        user.type = self.type
                        user.setImage(image: self.cameraImagV.image!)
                        PrWCDBBaseManager.shared.insertToDb(objects: [user], intoTable: userModelTableName)
                        self.titleLabel.text = ""
                        self.datetextF.text = ""
                        self.cameraImagV.image = UIImage(named: "camera")
                        self.deleteBtn.isHidden = true
                        
                        SVProgressHUD.showSuccess(withStatus: "Added successfully")
                        DispatchQueue.global().asyncAfter(wallDeadline: .now() + 1.5) {
                            SVProgressHUD.dismiss()
                        }
                        LuxADManager.shareInstance().showADByRandomMode(callback: {
                            actionType  in
                            self.dismiss(animated: true)
                        })
                        
                    }else{
                        let user = UserModel()
                        //                        let uuid = UUID()
                        user.uid = model!.uid
                        user.name = self.titleLabel.text!
                        user.date = self.datetextF.text!
                        user.notificationEnabled = self.isremind
                        user.type = self.type
                        user.setImage(image: self.cameraImagV.image!)
                        let condition: Condition = UserModel.Properties.uid == model!.uid
                        PrWCDBBaseManager.shared.updateToDb(table: userModelTableName, on: [UserModel.Properties.name,UserModel.Properties.date,UserModel.Properties.type,UserModel.Properties.notificationEnabled,UserModel.Properties.imageBase64], with: user, where: condition)
                        self.titleLabel.text = ""
                        self.datetextF.text = ""
                        self.cameraImagV.image = UIImage(named: "camera")
                        self.deleteBtn.isHidden = true
                        
                        SVProgressHUD.showInfo(withStatus: "update completed")
                        DispatchQueue.global().asyncAfter(wallDeadline: .now() + 1.5) {
                            SVProgressHUD.dismiss()
                        }
                        self.navigationController?.popViewController(animated: true)
                        dataUpdateClosure?(user)
                        
                        
                    }
                    
                }else{
                    SVProgressHUD.showInfo(withStatus: "Please choose your commemorative picture")
                    DispatchQueue.global().asyncAfter(deadline: .now() + 1.5) {
                        SVProgressHUD.dismiss()
                    }
                }
                
            }else{
                SVProgressHUD.showInfo(withStatus: "Please select anniversary date")
                DispatchQueue.global().asyncAfter(deadline: .now() + 1.5) {
                    SVProgressHUD.dismiss()
                }
            }
            
        } else {
            SVProgressHUD.showInfo(withStatus: "Please enter a title within 30 characters")
            DispatchQueue.global().asyncAfter(deadline: .now() + 1.5) {
                SVProgressHUD.dismiss()
            }
        }
        
        
    }
    
    @objc func imageTouch(){
        let imagePicker = UIImagePickerController()
        imagePicker.sourceType = .photoLibrary
        imagePicker.delegate = self
        present(imagePicker, animated: true, completion: nil)
        
        if self.cameraImagV.image == UIImage(named: "camera"){
            self.deleteBtn.isHidden = true
        }else{
            self.deleteBtn.isHidden = false
        }
        
    }
    
    
    @IBAction func dateSelect(_ sender: UIButton) {
        titleLabel.resignFirstResponder()
        let datePicker = BRDatePickerView()
        datePicker.pickerMode = .YMD
        datePicker.title = "Select Date"
        datePicker.selectDate = Date()
        datePicker.isAutoSelect = true // 自动选择，滚动选择器时立即返回结果，默认为 false
        datePicker.resultBlock = { selectDate, selectValue in
            print("选择的值：\(selectValue ?? "")")
            self.datetextF.text = selectValue
        }
        let customestyle = BRPickerStyle()
        customestyle.cancelBtnTitle = "Cancel"
        customestyle.doneBtnTitle = "Sure"
        datePicker.pickerStyle = customestyle
        datePicker.show()
    }
    
    
    @IBAction func switchSele(_ sender: Any) {
        if switchSelect.isOn {
            print("Switch is ON")
            self.isremind = true
        } else {
            print("Switch is OFF")
            self.isremind = false
        }
        
    }
    
    
    
    
    @IBAction func scheduleBtn(_ sender: UIButton) {
        self.type = "Schedule"
        
        self.scheduleImagV.image = UIImage(named: "schedule_s")
        self.schedLabel.alpha = 1.0
        
        self.birthdayImagV.image = UIImage(named: "birthday_n")
        self.birthdayLabel.alpha = 0.5
        
        self.memoryImagV.image = UIImage(named: "memor_n")
        self.memoryLabel.alpha = 0.5
        scheduleV.layer.cornerRadius = 8
        scheduleV.layer.borderWidth = 1
        scheduleV.layer.borderColor = UIColor.hexSting(color: "#4B92FE", alpha: 0.5).cgColor
        scheduleV.backgroundColor = .white
        
        birthdayV.layer.cornerRadius = 8
        birthdayV.layer.borderWidth = 0
        birthdayV.layer.borderColor = UIColor.hexSting(color: "#4B92FE", alpha: 0.5).cgColor
        birthdayV.backgroundColor = .hexSting(color: "#FAFAFA", alpha: 1)
        
        memoryV.layer.cornerRadius = 8
        memoryV.layer.borderWidth = 0
        memoryV.layer.borderColor = UIColor.hexSting(color: "#4B92FE", alpha: 0.5).cgColor
        memoryV.backgroundColor = .hexSting(color: "#FAFAFA", alpha: 1)
        
    }
    
    
    @IBAction func birthdatBtn(_ sender: UIButton) {
        self.type = "Birthday"
        self.scheduleImagV.image = UIImage(named: "schedule_n")
        self.schedLabel.alpha = 0.5
        
        self.birthdayImagV.image = UIImage(named: "birthday_s")
        self.birthdayLabel.alpha = 1.0
        
        self.memoryImagV.image = UIImage(named: "memor_n")
        self.memoryLabel.alpha = 0.5
        
        scheduleV.layer.cornerRadius = 8
        scheduleV.layer.borderWidth = 0
        scheduleV.layer.borderColor = UIColor.hexSting(color: "#4B92FE", alpha: 0.5).cgColor
        scheduleV.backgroundColor = .hexSting(color: "#FAFAFA", alpha: 1)
        
        birthdayV.layer.cornerRadius = 8
        birthdayV.layer.borderWidth = 1
        birthdayV.layer.borderColor = UIColor.hexSting(color: "#4B92FE", alpha: 0.5).cgColor
        birthdayV.backgroundColor = .white
        
        memoryV.layer.cornerRadius = 8
        memoryV.layer.borderWidth = 0
        memoryV.layer.borderColor = UIColor.hexSting(color: "#4B92FE", alpha: 0.5).cgColor
        memoryV.backgroundColor = .hexSting(color: "#FAFAFA", alpha: 1)
        
    }
    
    
    @IBAction func memoryBtn(_ sender: UIButton) {
        
        self.type = "Memory"
        self.scheduleImagV.image = UIImage(named: "schedule_n")
        self.schedLabel.alpha = 0.5
        
        self.birthdayImagV.image = UIImage(named: "birthday_n")
        self.birthdayLabel.alpha = 0.5
        
        self.memoryImagV.image = UIImage(named: "memor_S")
        self.memoryLabel.alpha = 1.0
        
        scheduleV.layer.cornerRadius = 8
        scheduleV.layer.borderWidth = 0
        scheduleV.layer.borderColor = UIColor.hexSting(color: "#4B92FE", alpha: 0.5).cgColor
        scheduleV.backgroundColor = .hexSting(color: "#FAFAFA", alpha: 1)
        
        birthdayV.layer.cornerRadius = 8
        birthdayV.layer.borderWidth = 0
        birthdayV.layer.borderColor = UIColor.hexSting(color: "#4B92FE", alpha: 0.5).cgColor
        birthdayV.backgroundColor = .hexSting(color: "#FAFAFA", alpha: 1)
        
        memoryV.layer.cornerRadius = 8
        memoryV.layer.borderWidth = 1
        memoryV.layer.borderColor = UIColor.hexSting(color: "#4B92FE", alpha: 0.5).cgColor
        memoryV.backgroundColor = .white
        
        
    }
    
    
    
    
    
    @IBAction func btndelete(_ sender: UIButton) {
        self.cameraImagV.image = UIImage(named: "camera")
        self.deleteBtn.isHidden = true
    }
    
    
}

extension AV_AddVC:UIImagePickerControllerDelegate, UINavigationControllerDelegate{
    
    // 当选择图片完成时调用的方法
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
        picker.dismiss(animated: true, completion: nil)
        
        // 获取选定的图片
        if let image = info[UIImagePickerController.InfoKey.originalImage] as? UIImage {
            // 存储图片到 UserDefaults
            //            saveImageToUserDefaults(image, forKey: "selectedImage")
            self.cameraImagV.image = image
            // 也可以将图片保存到应用的沙盒中，以便稍后使用
            // saveImageToDocumentsDirectory(image)
            if self.cameraImagV.image == UIImage(named: "camera"){
                self.deleteBtn.isHidden = true
            }else{
                self.deleteBtn.isHidden = false
            }
        }
    }
    
    // 当用户取消选择图片时调用的方法
    func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
        picker.dismiss(animated: true, completion: nil)
        if self.cameraImagV.image == UIImage(named: "camera"){
            self.deleteBtn.isHidden = true
        }else{
            self.deleteBtn.isHidden = false
        }
    }
    
}

