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

import UIKit
import FittedSheets

struct BrushColorModel {
    let id: Int
    let color: String
}

struct MagicBrushModel {
    let id: Int
    let icon: String
    let type: BrushShapeType
}

enum BrushShapeType {
    case draw
    case line
    case ellipse
    case rect
}

protocol PhotoEditingBrushToolVCDelegate {
    func handleSelectedBrushColor(color: BrushColorModel)
    func handleSelectedBrushShape(shape: MagicBrushModel)
    func handleChangedBrushSize(size: CGFloat)
    func handleChangedBrushOpacity(opacity: CGFloat)
    func handleEraserButtonTap(sender: UIButton)
}

class PhotoEditingBrushToolVC: UIViewController {
    
    // MARK: - IBOutlets
    
    @IBOutlet weak var headerLabel: UILabel!
    @IBOutlet weak var sizeSlider: UISlider!
    @IBOutlet weak var opacitySlider: UISlider!
    @IBOutlet weak var colorCollectionView: UICollectionView!
    @IBOutlet weak var shapeCollectionView: UICollectionView!
    @IBOutlet weak var eraserButton: UIButton!
    
    // MARK: - Properties
    
    var selectedBrushSize: CGFloat = 7
    var selectedBrushOpacity: CGFloat = 1
    private var colorList: [BrushColorModel] = []
    var selectedColor = BrushColorModel(id: 2, color: "#000000")
    private var magicBrushList: [MagicBrushModel] = []
    var selectedShape = MagicBrushModel(id: 0, icon: "ic_brush", type: .draw)
    var delegate: PhotoEditingBrushToolVCDelegate?
    var isEraser = false
    
    // 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)
    }
    
    // Eraser Button Action
    @IBAction func eraserButtonAction(_ sender: UIButton) {
        self.view.endEditing(true)
        self.delegate?.handleEraserButtonTap(sender: sender)
        self.isEraser = !self.isEraser
        self.setupEraser()
    }
    
    // Size Slider Action
    @IBAction func sizeSliderAction(_ sender: UISlider) {
        self.delegate?.handleChangedBrushSize(size: CGFloat(sender.value))
    }
    
    // Opacity Slider Action
    @IBAction func opacitySliderAction(_ sender: UISlider) {
        self.delegate?.handleChangedBrushOpacity(opacity: CGFloat(sender.value))
        self.isEraser = false
        self.setupEraser()
    }
    
    // MARK: - Helper Functions
    
    // Initial Config
    func initialConfig() {
        self.setupUI()
        self.setupEraser()
        self.setupCollectionView()
        self.setBrushColorData()
        self.setMagicBrushData()
    }
    
    // Setup Eraser
    func setupEraser() {
        if self.isEraser {
            self.headerLabel.text = "Eraser"
        } else {
            self.headerLabel.text = "Brush"
        }
    }
    
    // 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.shapeCollectionView.delegate = self
        self.shapeCollectionView.dataSource = self
        self.shapeCollectionView.register(UINib(resource: R.nib.photoEditingBrushToolShapeCell), forCellWithReuseIdentifier: R.reuseIdentifier.photoEditingBrushToolShapeCell.identifier)
    }
    
    // Setup UI
    func setupUI() {
        self.sizeSlider.setThumbImage(UIImage(named: "custom_thumb"), for: .normal)
        self.sizeSlider.setThumbImage(UIImage(named: "custom_thumb"), for: .highlighted)
        self.sizeSlider.setValue(Float(self.selectedBrushSize), animated: true)
        self.opacitySlider.setThumbImage(UIImage(named: "custom_thumb"), for: .normal)
        self.opacitySlider.setThumbImage(UIImage(named: "custom_thumb"), for: .highlighted)
        self.opacitySlider.setValue(Float(self.selectedBrushOpacity), animated: true)
    }
    
    // Set Brush Color Data
    func setBrushColorData() {
        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 Magic Brush Data
    func setMagicBrushData() {
        self.magicBrushList = [
            MagicBrushModel(id: 0, icon: "ic_brush", type: .draw),
            MagicBrushModel(id: 2, icon: "ic_line", type: .line),
            MagicBrushModel(id: 3, icon: "ic_circle_oval", type: .ellipse),
            MagicBrushModel(id: 4, icon: "ic_rectangle", type: .rect)
        ]
        self.shapeCollectionView.reloadData()
    }
    
}

// MARK: - Extension

// MARK: Collection View Setup
extension PhotoEditingBrushToolVC: UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout {
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        switch collectionView {
        case self.colorCollectionView:
            return self.colorList.count
        case self.shapeCollectionView:
            return self.magicBrushList.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.shapeCollectionView:
            let cell = self.shapeCollectionView.dequeueReusableCell(withReuseIdentifier: R.reuseIdentifier.photoEditingBrushToolShapeCell.identifier, for: indexPath) as! PhotoEditingBrushToolShapeCell
            let item = self.magicBrushList[indexPath.item]
            cell.setData(data: item)
            if self.selectedShape.id == item.id {
                cell.imageView.tintColor = .accent
            } else {
                cell.imageView.tintColor = UIColor(hex: "212121")
            }
            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.delegate?.handleSelectedBrushColor(color: self.selectedColor)
            self.isEraser = false
            self.setupEraser()
        case self.shapeCollectionView:
            let item = self.magicBrushList[indexPath.item]
            self.selectedShape = item
            self.shapeCollectionView.reloadData()
            self.delegate?.handleSelectedBrushShape(shape: self.selectedShape)
        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
    }
    
}
