//
//  PhotoEditingImageToolVC.swift
//  WoWonder
//
//  Created by iMac on 03/06/25.
//  Copyright © 2025 ScriptSun. All rights reserved.
//

import UIKit
import FittedSheets
import Async
import Toast_Swift

protocol PhotoEditingImageToolVCDelegate {
    func handleAIImageGenerate(image_url: String)
}

class PhotoEditingImageToolVC: BaseVC {
    
    // MARK: - IBOutlets
    
    @IBOutlet weak var viewTextView: UIView!
    @IBOutlet weak var textView: UITextView!
    
    // MARK: - Properties
    
    var delegate: PhotoEditingImageToolVCDelegate?
    
    // MARK: - View Life Cycles
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        // Do any additional setup after loading the view.
        
        self.initialConfig()
    }
    
    // MARK: - Selectors
    
    // Close Button Action
    @IBAction func closeButtonAction(_ sender: UIButton) {
        self.view.endEditing(true)
        self.sheetViewController?.attemptDismiss(animated: true)
    }
    
    // Generate Button Action
    @IBAction func generateButtonAction(_ sender: UIButton) {
        self.view.endEditing(true)
        guard let text = self.textView.text, !text.isEmpty, !text.trimmingCharacters(in: .whitespaces).isEmpty else {
            self.view.makeToast("Type the prompt to generate an image")
            return
        }
        if !GenerateImageAi.shared.checkGenerateImageAi() {
            return
        }
        if !Connectivity.isConnectedToNetwork() {
            return
        }
        self.showProgressDialog(text: NSLocalizedString("Loading...", comment: "Loading..."))
        Async.background {
            GenerateImageAi.shared.generateImage(text: text) { success  in
                Async.main {
                    self.dismissProgressDialog {
                        if success != nil {
                            print("output_url >>>>>", success?.output_url ?? "")
                            self.delegate?.handleAIImageGenerate(image_url: success?.output_url ?? "")
                            self.sheetViewController?.attemptDismiss(animated: true)
                        } else {
                            self.view.makeToast("Something went wrong")
                        }
                    }
                }
            }
        }
    }
    
    // MARK: - Helper Functions
    
    // Initial Config
    func initialConfig() {
        self.setupTextView()    
    }
    
    // Setup TextView
    func setupTextView() {
        self.textView.textContainerInset = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
        self.textView.addPlaceholder("Type something", with: UIColor(hex: "808080"))
        self.textView.delegate = self
    }
    
}

// MARK: - Extensions

// MARK: UITextViewDelegate
extension PhotoEditingImageToolVC: UITextViewDelegate {
    
    func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
        let currentText = textView.text ?? ""
        guard let stringRange = Range(range, in: currentText) else { return false }
        let updatedText = currentText.replacingCharacters(in: stringRange, with: text)
        return updatedText.count <= 5000
    }
    
    func textViewDidBeginEditing(_ textView: UITextView) {
        switch textView {
        case self.textView:
            self.viewTextView.borderColorV = .accent
        default:
            break
        }
    }
    
    func textViewDidEndEditing(_ textView: UITextView) {
        switch textView {
        case self.textView:
            self.viewTextView.borderColorV = .color_divider
        default:
            break
        }
    }
    
}
