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

import UIKit
import FittedSheets
import SDWebImage

class ColorEditorVC: UIViewController {
    
    // MARK: - IBOutlets
    
    @IBOutlet weak var editorView: UIView!
    @IBOutlet weak var toolStackView: UIStackView!
    
    // MARK: - Properties
    
    var selectedColor = GradientColorModel(id: 23, colors: [UIColor(hex: "#fc8f35").cgColor, UIColor(hex: "#de2362").cgColor])
    private var _selectedStickerView: StickerView?
    var selectedStickerView: StickerView? {
        get {
            return _selectedStickerView
        } set {
            if _selectedStickerView != newValue {
                if let selectedStickerView = _selectedStickerView {
                    selectedStickerView.showEditingHandlers = false
                }
                _selectedStickerView = newValue
            }
            if let selectedStickerView = _selectedStickerView {
                selectedStickerView.showEditingHandlers = true
                selectedStickerView.superview?.bringSubviewToFront(selectedStickerView)
            }
        }
    }
    
    // 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.navigationController?.popViewController(animated: true)
    }
    
    // Save Button Action
    @IBAction func saveButtonAction(_ sender: UIButton) {
        self.view.endEditing(true)
        self.selectedStickerView?.showEditingHandlers = false
        self.toolStackView.isHidden = true
        if let image = self.editorView.render() {
            self.toolStackView.isHidden = false
            if let newVC = R.storyboard.story.addNewStoryVC() {
                newVC.selectedImage = image
                self.navigationController?.pushViewController(newVC, animated: true)
            }
        }
    }
    
    // Text Button Action
    @IBAction func textButtonAction(_ sender: UIButton) {
        self.view.endEditing(true)
        let options = SheetOptions(pullBarHeight: 0, useFullScreenMode: false, useInlineMode: true)
        if let newVC = R.storyboard.photoEditor.photoEditingTextToolVC() {
            newVC.delegate = self
            let sheetController = SheetViewController(controller: newVC, sizes: [.percent(0.7)], options: options)
            sheetController.cornerRadius = 24
            sheetController.dismissOnPull = false
            sheetController.dismissOnOverlayTap = false
            sheetController.allowPullingPastMaxHeight = false
            sheetController.allowPullingPastMinHeight = false
            sheetController.animateIn(to: self.view, in: self)
        }
    }
    
    // Sticker Button Action
    @IBAction func stickerButtonAction(_ sender: UIButton) {
        self.view.endEditing(true)
        let options = SheetOptions(pullBarHeight: 0, useFullScreenMode: false, useInlineMode: true)
        if let newVC = R.storyboard.photoEditor.photoEditingStickerToolVC() {
            newVC.delegate = self
            let sheetController = SheetViewController(controller: newVC, sizes: [.intrinsic], options: options)
            sheetController.cornerRadius = 24
            sheetController.dismissOnPull = false
            sheetController.dismissOnOverlayTap = false
            sheetController.allowPullingPastMaxHeight = false
            sheetController.allowPullingPastMinHeight = false
            sheetController.animateIn(to: self.view, in: self)
        }
    }
    
    // Color Button Action
    @IBAction func colorButtonAction(_ sender: UIButton) {
        self.view.endEditing(true)
        let options = SheetOptions(pullBarHeight: 0, useFullScreenMode: false, useInlineMode: true)
        if let newVC = R.storyboard.colorEditor.colorEditorColorToolVC() {
            newVC.selectedColor = self.selectedColor
            newVC.delegate = self
            let sheetController = SheetViewController(controller: newVC, sizes: [.intrinsic], options: options)
            sheetController.cornerRadius = 24
            sheetController.dismissOnPull = false
            sheetController.dismissOnOverlayTap = false
            sheetController.allowPullingPastMaxHeight = false
            sheetController.allowPullingPastMinHeight = false
            sheetController.animateIn(to: self.view, in: self)
        }
    }
    
    // MARK: - Helper Functions
    
    // Initial Config
    func initialConfig() {
        self.editorView.setUpGradientLayer(name: "Gradient Background", colors: self.selectedColor.colors)
        let tapGesture = UITapGestureRecognizer(target: self, action: #selector(self.handleTap(_:)))
        self.editorView.addGestureRecognizer(tapGesture)
    }
    
    @objc func handleTap(_ gesture: UITapGestureRecognizer) {
        self.selectedStickerView?.showEditingHandlers = false
    }
    
    func addImage(img: UIImageView) {
        let stickerView = StickerView.init(contentView: img)
        stickerView.center = CGPoint(x: self.editorView.bounds.midX, y: self.editorView.bounds.midY)
        stickerView.delegate = self
        stickerView.outlineBorderColor = UIColor(hex: "969696")
        stickerView.setImage(UIImage(named: "ic_remove")!, forHandler: StickerViewHandler.close)
        stickerView.setImage(UIImage(named: "rotate-right")!, forHandler: StickerViewHandler.rotate)
        stickerView.showEditingHandlers = true
        self.editorView.addSubview(stickerView)
        self.selectedStickerView = stickerView
    }
    
}

// MARK: - Extensions

//MARK: PhotoEditingTextToolVCDelegate
extension ColorEditorVC: PhotoEditingTextToolVCDelegate {
    
    func handlePhotoEditingText(sender: UILabel) {
        sender.sizeToFit()
        sender.setNeedsLayout()
        sender.layoutIfNeeded()
        if let image = sender.labelToImage() {
            let img = UIImageView(image: image)
            self.addImage(img: img)
        }
    }
    
}

// MARK: PhotoEditingStickerToolVCDelegate
extension ColorEditorVC: PhotoEditingStickerToolVCDelegate {
    
    func handleStickerSelection(data: PhotoStickerModel) {
        let url = URL(string: data.url)
        SDWebImageManager.shared.loadImage(with: url, progress: nil) { image, data, error, cache, success, url in
            let img = UIImageView(image: image)
            self.addImage(img: img)
        }
    }
    
    func handleStickerSelection(data: String) {
        let image = data.emojiToImage(size: 70)
        let img = UIImageView(image: image)
        self.addImage(img: img)
    }
    
    func handleStickerSelection(data: PhotoWidgetModel) {
        let img = UIImageView(image: data.image)
        self.addImage(img: img)
    }
    
}

// MARK: ColorEditorColorToolVCDelegate
extension ColorEditorVC: ColorEditorColorToolVCDelegate {
    
    func handleColorToolSaveButtonTap(color: GradientColorModel) {
        self.selectedColor = color
        self.editorView.setUpGradientLayer(name: "Gradient Background", colors: color.colors)
    }
    
    func handleColorToolSelectedColor(color: GradientColorModel) {
        self.editorView.setUpGradientLayer(name: "Gradient Background", colors: color.colors)
    }
    
    func handleColorToolCloseButtonTap() {
        self.editorView.setUpGradientLayer(name: "Gradient Background", colors: self.selectedColor.colors)
    }
    
}

// MARK: StickerViewDelegate
extension ColorEditorVC: StickerViewDelegate {
    
    func stickerViewDidBeginMoving(_ stickerView: StickerView) {
        self.selectedStickerView = stickerView
    }
    
    func stickerViewDidChangeMoving(_ stickerView: StickerView) {
        
    }
    
    func stickerViewDidEndMoving(_ stickerView: StickerView) {
        
    }
    
    func stickerViewDidBeginRotating(_ stickerView: StickerView) {
        
    }
    
    func stickerViewDidChangeRotating(_ stickerView: StickerView) {
        
    }
    
    func stickerViewDidEndRotating(_ stickerView: StickerView) {
        
    }
    
    func stickerViewDidClose(_ stickerView: StickerView) {
        
    }
    
    func stickerViewDidTap(_ stickerView: StickerView) {
        self.selectedStickerView = stickerView
    }
    
}
