//
//  PhotoEditingTextToolVC.swift
//  WoWonder
//
//  Created by iMac on 22/05/25.
//  Copyright © 2025 ScriptSun. All rights reserved.
//

import UIKit
import FittedSheets

struct TextShadow {
    var radius: CGFloat
    var size: CGSize
    var color: String
}

struct TextShadowModel {
    var id: Int
    var text: String
    var shadow: TextShadow
}

struct TextFontModel {
    var id: Int
    var text: String
    var font: String
}

protocol PhotoEditingTextToolVCDelegate {
    func handlePhotoEditingText(sender: UILabel)
}

class PhotoEditingTextToolVC: UIViewController {
    
    // MARK: - IBOutlets
    
    @IBOutlet weak var scrollView: UIScrollView!
    @IBOutlet weak var outputLabel: UILabel!
    @IBOutlet weak var viewTextView: UIView!
    @IBOutlet weak var textView: UITextView!
    @IBOutlet weak var colorCollectionView: UICollectionView!
    @IBOutlet weak var shadowCollectionView: UICollectionView!
    @IBOutlet weak var fontCollectionView: UICollectionView!
    
    // MARK: - Properties
    
    private var colorList: [BrushColorModel] = []
    var selectedColor = BrushColorModel(id: 2, color: "#000000")
    private var shadowList: [TextShadowModel] = []
    var selectedShadow = TextShadowModel(id: 0, text: "Text Shadow", shadow: TextShadow(radius:0, size: CGSize(width: 0, height: 0), color: "00FFFF"))
    private var fontList: [TextFontModel] = []
    var selectedFont: TextFontModel?
    var delegate: PhotoEditingTextToolVCDelegate?
    
    // 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)
    }
    
    // Save Button Action
    @IBAction func saveButtonAction(_ sender: UIButton) {
        self.view.endEditing(true)
        self.sheetViewController?.attemptDismiss(animated: true)
        self.delegate?.handlePhotoEditingText(sender: self.outputLabel)
    }
    
    // Left Align Button Action
    @IBAction func leftAlignButtonAction(_ sender: UIButton) {
        self.outputLabel.textAlignment = .left
    }
    
    // Center Align Button Action
    @IBAction func centerAlignButtonAction(_ sender: UIButton) {
        self.outputLabel.textAlignment = .center
    }
    
    // Right Align Button Action
    @IBAction func rightAlignButtonAction(_ sender: UIButton) {
        self.outputLabel.textAlignment = .right
    }
    
    // Bold Button Action
    @IBAction func boldButtonAction(_ sender: UIButton) {
        self.applyTextStyle([.strokeWidth: -3]) // Adjust size as needed
    }

    // Italic Button Action
    @IBAction func italicButtonAction(_ sender: UIButton) {
        self.applyTextStyle([.obliqueness: 0.2]) // Adjust size as needed
    }

    // Underline Button Action
    @IBAction func underLineButtonAction(_ sender: UIButton) {
        self.applyTextStyle([.underlineStyle: NSUnderlineStyle.single.rawValue])
    }

    // Strikethrough Button Action
    @IBAction func strikethroughButtonAction(_ sender: UIButton) {
        self.applyTextStyle([.strikethroughStyle: NSUnderlineStyle.single.rawValue])
    }

    // Helper function to apply text styles
    private func applyTextStyle(_ attributes: [NSAttributedString.Key: Any]) {
        let text = self.outputLabel.text ?? ""
        let attributedText: NSMutableAttributedString
        
        // Check if the outputLabel already has attributed text
        if let existingAttributedText = self.outputLabel.attributedText {
            attributedText = NSMutableAttributedString(attributedString: existingAttributedText)
        } else {
            attributedText = NSMutableAttributedString(string: text)
        }
        
        // Apply the new attributes
        attributedText.addAttributes(attributes, range: NSRange(location: 0, length: attributedText.length))
        
        self.outputLabel.attributedText = attributedText
    }

    
    // MARK: - Helper Functions
    
    // Initial Config
    func initialConfig() {
        self.sheetViewController!.handleScrollView(self.scrollView)
        self.setupTextView()
        self.setupCollectionView()
        self.setTextColorData()
        self.setTextShadowData()
        self.setTextFontData()
    }
    
    // Setup TextView
    func setupTextView() {
        self.textView.textContainerInset = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
        self.textView.addPlaceholder("Type something", with: UIColor(hex: "888888"))
        self.textView.delegate = self
    }
    
    // Setup Collection View
    func setupCollectionView() {
        self.colorCollectionView.delegate = self
        self.colorCollectionView.dataSource = self
        self.colorCollectionView.register(UINib(resource: R.nib.photoEditingToolColorPickerCell), forCellWithReuseIdentifier: R.reuseIdentifier.photoEditingToolColorPickerCell.identifier)
        
        self.shadowCollectionView.delegate = self
        self.shadowCollectionView.dataSource = self
        self.shadowCollectionView.register(UINib(resource: R.nib.photoEditingToolTextShadowCell), forCellWithReuseIdentifier: R.reuseIdentifier.photoEditingToolTextShadowCell.identifier)
        
        self.fontCollectionView.delegate = self
        self.fontCollectionView.dataSource = self
        self.fontCollectionView.register(UINib(resource: R.nib.photoEditingToolTextFontCell), forCellWithReuseIdentifier: R.reuseIdentifier.photoEditingToolTextFontCell.identifier)
    }
    
    // Set Text Color Data
    func setTextColorData() {
        self.colorList = [
            BrushColorModel(id: 1, color: "#FFFFFF"),
            BrushColorModel(id: 2, color: "#000000"),
            BrushColorModel(id: 3, color: "#f44336"),
            BrushColorModel(id: 4, color: "#E91E63"),
            BrushColorModel(id: 5, color: "#EC407A"),
            BrushColorModel(id: 6, color: "#9C27B0"),
            BrushColorModel(id: 7, color: "#3F51B5"),
            BrushColorModel(id: 8, color: "#2196F3"),
            BrushColorModel(id: 9, color: "#03A9F4"),
            BrushColorModel(id: 10, color: "#00BFA5"),
            BrushColorModel(id: 11, color: "#00BCD4"),
            BrushColorModel(id: 12, color: "#009688"),
            BrushColorModel(id: 13, color: "#4CAF50"),
            BrushColorModel(id: 14, color: "#8BC34A"),
            BrushColorModel(id: 15, color: "#CDDC39"),
            BrushColorModel(id: 16, color: "#FFEB3B"),
            BrushColorModel(id: 17, color: "#FFC107"),
            BrushColorModel(id: 18, color: "#FF9800"),
            BrushColorModel(id: 19, color: "#FF5722"),
            BrushColorModel(id: 20, color: "#795548"),
            BrushColorModel(id: 21, color: "#9E9E9E"),
            BrushColorModel(id: 22, color: "#607D8B")
        ]
        self.colorCollectionView.reloadData()
    }
    
    // Set Text Shadow Data
    func setTextShadowData() {
        self.shadowList = [
            TextShadowModel(id: 0, text: "Text Shadow", shadow: TextShadow(radius: 0, size: CGSize(width: 0, height: 0), color: "00FFFF")),
            TextShadowModel(id: 1, text: "Text Shadow", shadow: TextShadow(radius: 8, size: CGSize(width: 4, height: 4), color: "FF1493")),
            TextShadowModel(id: 2, text: "Text Shadow", shadow: TextShadow(radius: 8, size: CGSize(width: 4, height: 4), color: "FF00FF")),
            TextShadowModel(id: 3, text: "Text Shadow", shadow: TextShadow(radius: 8, size: CGSize(width: 4, height: 4), color: "24FFFF")),
            TextShadowModel(id: 4, text: "Text Shadow", shadow: TextShadow(radius: 8, size: CGSize(width: 4, height: 4), color: "FFFF00")),
            TextShadowModel(id: 5, text: "Text Shadow", shadow: TextShadow(radius: 8, size: CGSize(width: 4, height: 4), color: "FFFFFF")),
            TextShadowModel(id: 6, text: "Text Shadow", shadow: TextShadow(radius: 8, size: CGSize(width: 4, height: 4), color: "888888")),
            TextShadowModel(id: 7, text: "Text Shadow", shadow: TextShadow(radius: 8, size: CGSize(width: -4, height: -4), color: "FF1493")),
            TextShadowModel(id: 8, text: "Text Shadow", shadow: TextShadow(radius: 8, size: CGSize(width: -4, height: -4), color: "FF00FF")),
            TextShadowModel(id: 9, text: "Text Shadow", shadow: TextShadow(radius: 8, size: CGSize(width: -4, height: -4), color: "24FFFF")),
            TextShadowModel(id: 10, text: "Text Shadow", shadow: TextShadow(radius: 8, size: CGSize(width: -4, height: -4), color: "FFFF00")),
            TextShadowModel(id: 11, text: "Text Shadow", shadow: TextShadow(radius: 8, size: CGSize(width: -4, height: -4), color: "FFFFFF")),
            TextShadowModel(id: 12, text: "Text Shadow", shadow: TextShadow(radius: 8, size: CGSize(width: -4, height: -4), color: "696969")),
            TextShadowModel(id: 13, text: "Text Shadow", shadow: TextShadow(radius: 8, size: CGSize(width: -4, height: 4), color: "FF1493")),
            TextShadowModel(id: 14, text: "Text Shadow", shadow: TextShadow(radius: 8, size: CGSize(width: -4, height: 4), color: "FF00FF")),
            TextShadowModel(id: 15, text: "Text Shadow", shadow: TextShadow(radius: 8, size: CGSize(width: -4, height: 4), color: "24FFFF")),
            TextShadowModel(id: 16, text: "Text Shadow", shadow: TextShadow(radius: 8, size: CGSize(width: -4, height: 4), color: "FFFF00")),
            TextShadowModel(id: 17, text: "Text Shadow", shadow: TextShadow(radius: 8, size: CGSize(width: -4, height: 4), color: "FFFFFF")),
            TextShadowModel(id: 18, text: "Text Shadow", shadow: TextShadow(radius: 8, size: CGSize(width: -4, height: 4), color: "696969")),
            TextShadowModel(id: 19, text: "Text Shadow", shadow: TextShadow(radius: 8, size: CGSize(width: 4, height: -4), color: "FF1493")),
            TextShadowModel(id: 20, text: "Text Shadow", shadow: TextShadow(radius: 8, size: CGSize(width: 4, height: -4), color: "FF00FF")),
            TextShadowModel(id: 21, text: "Text Shadow", shadow: TextShadow(radius: 8, size: CGSize(width: 4, height: -4), color: "24FFFF")),
            TextShadowModel(id: 22, text: "Text Shadow", shadow: TextShadow(radius: 8, size: CGSize(width: 4, height: -4), color: "FFFF00")),
            TextShadowModel(id: 23, text: "Text Shadow", shadow: TextShadow(radius: 8, size: CGSize(width: 4, height: -4), color: "FFFFFF")),
            TextShadowModel(id: 24, text: "Text Shadow", shadow: TextShadow(radius: 8, size: CGSize(width: 4, height: -4), color: "696969"))
        ]
        self.shadowCollectionView.reloadData()
    }
    
    // Set Text Font Data
    func setTextFontData() {
        self.fontList = [
            TextFontModel(id: 0, text: "DynaPuff", font: "DynaPuff-Regular"),
            TextFontModel(id: 1, text: "Eater", font: "Eater-Regular"),
            TextFontModel(id: 2, text: "Henny Penny", font: "HennyPenny-Regular"),
            TextFontModel(id: 3, text: "Iceberg", font: "Iceberg-Regular"),
            TextFontModel(id: 4, text: "Monsieur La Doulaise", font: "MonsieurLaDoulaise-Regular"),
            TextFontModel(id: 5, text: "PlaywriteVN", font: "PlaywriteVN-Regular"),
            TextFontModel(id: 6, text: "Poppins", font: "Poppins Medium"),
            TextFontModel(id: 7, text: "Rubik Dirt", font: "RubikDirt-Regular"),
            TextFontModel(id: 8, text: "Urbanist", font: "Urbanist-Regular"),
            TextFontModel(id: 9, text: "Almarai", font: "Almarai-Regular"),
            TextFontModel(id: 10, text: "Cairo", font: "Cairo-Regular"),
            TextFontModel(id: 11, text: "Fustat", font: "Fustat-Regular"),
            TextFontModel(id: 12, text: "Noto Sans", font: "NotoSansArabic-Regular"),
            TextFontModel(id: 13, text: "Rakkas", font: "Rakkas-Regular"),
            TextFontModel(id: 14, text: "Bryndan Write", font: "Bryndan-Write"),
            TextFontModel(id: 15, text: "Hacen", font: "HacenSudan"),
            TextFontModel(id: 16, text: "Harmattan", font: "Harmattan-Regular"),
            TextFontModel(id: 17, text: "Norican", font: "Norican-Regular"),
            TextFontModel(id: 18, text: "Oswald Heavy", font: "Oswald-Heavy"),
        ]
        self.fontCollectionView.reloadData()
    }
    
}

// MARK: - Extensions

// MARK: UITextViewDelegate
extension PhotoEditingTextToolVC: UITextViewDelegate {
    
    func textViewDidChange(_ textView: UITextView) {
        self.outputLabel.text = self.textView.text
    }
    
    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
        }
    }
    
}

// MARK: Collection View Setup
extension PhotoEditingTextToolVC: UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout {
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        switch collectionView {
        case self.colorCollectionView:
            return self.colorList.count
        case self.shadowCollectionView:
            return self.shadowList.count
        case self.fontCollectionView:
            return self.fontList.count
        default:
            return 0
        }
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        switch collectionView {
        case self.colorCollectionView:
            let cell = self.colorCollectionView.dequeueReusableCell(withReuseIdentifier: R.reuseIdentifier.photoEditingToolColorPickerCell.identifier, for: indexPath) as! PhotoEditingToolColorPickerCell
            let item = self.colorList[indexPath.item]
            cell.setData(data: item)
            if selectedColor.id == item.id {
                cell.colorView.layer.borderColor = UIColor.accent.cgColor
            } else {
                if indexPath.item == 0 {
                    cell.colorView.layer.borderColor = UIColor.black.cgColor
                } else {
                    cell.colorView.layer.borderColor = UIColor.clear.cgColor
                }
            }
            return cell
        case self.shadowCollectionView:
            let cell = self.shadowCollectionView.dequeueReusableCell(withReuseIdentifier: R.reuseIdentifier.photoEditingToolTextShadowCell.identifier, for: indexPath) as! PhotoEditingToolTextShadowCell
            let item = self.shadowList[indexPath.item]
            cell.setData(data: item)
            if self.selectedShadow.id == item.id {
                cell.shadowView.backgroundColor = .accent
                cell.shadowLabel.textColor = .white
            } else {
                cell.shadowView.backgroundColor = UIColor(hex: "808080")
                cell.shadowLabel.textColor = .black
            }
            return cell
        case self.fontCollectionView:
            let cell = self.fontCollectionView.dequeueReusableCell(withReuseIdentifier: R.reuseIdentifier.photoEditingToolTextFontCell.identifier, for: indexPath) as! PhotoEditingToolTextFontCell
            let item = self.fontList[indexPath.item]
            cell.setData(data: item)
            if self.selectedFont?.id == item.id {
                cell.fontView.backgroundColor = .accent
                cell.fontLabel.textColor = .white
            } else {
                cell.fontView.backgroundColor = UIColor(hex: "808080")
                cell.fontLabel.textColor = .black
            }
            return cell
        default:
            return UICollectionViewCell()
        }
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        switch collectionView {
        case self.colorCollectionView:
            let item = self.colorList[indexPath.item]
            self.selectedColor = item
            self.colorCollectionView.reloadData()
            self.outputLabel.textColor = UIColor(hex: selectedColor.color)
        case self.shadowCollectionView:
            let item = self.shadowList[indexPath.item]
            self.selectedShadow = item
            self.shadowCollectionView.reloadData()
            self.outputLabel.layer.shadowOffset = self.selectedShadow.shadow.size
            self.outputLabel.layer.shadowColor = UIColor(hex: self.selectedShadow.shadow.color).cgColor
            self.outputLabel.layer.shadowOpacity = 1
            self.outputLabel.layer.shadowRadius = self.selectedShadow.shadow.radius
        case self.fontCollectionView:
            let item = self.fontList[indexPath.item]
            self.selectedFont = item
            self.fontCollectionView.reloadData()
            self.outputLabel.font = UIFont(name: self.selectedFont?.font ?? "", size: 16)
        default:
            break
        }
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
        return UIEdgeInsets.zero
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
        return 0
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
        return 0
    }
    
}
