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

import UIKit
import FittedSheets

struct PhotoFilterModel {
    var id: Int
    var photoFilter: PhotoFilter
    var filterSmallImage: UIImage
}

protocol PhotoEditingFilterToolVCDelegate {
    func handlePhotoEditingCloseTap()
    func handlePhotoEditingFilterSelection(data: PhotoFilterModel)
}

class PhotoEditingFilterToolVC: UIViewController {
    
    // MARK: - IBOutlets
    
    @IBOutlet weak var collectionView: UICollectionView!
    
    // MARK: - Properties
    
    var selectedImage: UIImage? = nil
    var filterList: [PhotoFilterModel] = []
    var delegate: PhotoEditingFilterToolVCDelegate?
    var selectedFilter: PhotoFilterModel?
    
    // 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.delegate?.handlePhotoEditingCloseTap()
        self.sheetViewController?.attemptDismiss(animated: true)
    }
    
    // Save Button Action
    @IBAction func saveButtonAction(_ sender: UIButton) {
        self.view.endEditing(true)
        self.sheetViewController?.attemptDismiss(animated: true)
    }
    
    // MARK: - Helper Functions
    
    // Initial Config
    func initialConfig() {
        self.setupCollectionView()
        self.setPhotoFilterData()
    }
    
    // Setup Collection View
    func setupCollectionView() {
        self.collectionView.delegate = self
        self.collectionView.dataSource = self
        self.collectionView.register(UINib(resource: R.nib.photoEditingToolFilterCell), forCellWithReuseIdentifier: R.reuseIdentifier.photoEditingToolFilterCell.identifier)
    }
    
    // Set Photo Filter Data
    func setPhotoFilterData() {
        let engine = PhotoFilterEngine()
        if let image = self.selectedImage {
            let smallImage = self.resizeImage(image: image)
            DispatchQueue.global(qos: .userInitiated).async {
                self.filterList = [
                    PhotoFilterModel(id: 1, photoFilter: .none, filterSmallImage: engine.apply(filter: .none, to: smallImage)),
                    PhotoFilterModel(id: 2, photoFilter: .autoFix, filterSmallImage: engine.apply(filter: .autoFix, to: smallImage)),
                    PhotoFilterModel(id: 3, photoFilter: .brightness, filterSmallImage: engine.apply(filter: .brightness, to: smallImage)),
                    PhotoFilterModel(id: 4, photoFilter: .contrast, filterSmallImage: engine.apply(filter: .contrast, to: smallImage)),
                    PhotoFilterModel(id: 5, photoFilter: .documentary, filterSmallImage: engine.apply(filter: .documentary, to: smallImage)),
                    PhotoFilterModel(id: 6, photoFilter: .dueTone, filterSmallImage: engine.apply(filter: .dueTone, to: smallImage)),
                    PhotoFilterModel(id: 7, photoFilter: .fillLight, filterSmallImage: engine.apply(filter: .fillLight, to: smallImage)),
                    PhotoFilterModel(id: 8, photoFilter: .fishEye, filterSmallImage: engine.apply(filter: .fishEye, to: smallImage)),
                    PhotoFilterModel(id: 9, photoFilter: .grain, filterSmallImage: engine.apply(filter: .grain, to: smallImage)),
                    PhotoFilterModel(id: 10, photoFilter: .grayScale, filterSmallImage: engine.apply(filter: .grayScale, to: smallImage)),
                    PhotoFilterModel(id: 11, photoFilter: .lomish, filterSmallImage: engine.apply(filter: .lomish, to: smallImage)),
                    PhotoFilterModel(id: 12, photoFilter: .negative, filterSmallImage: engine.apply(filter: .negative, to: smallImage)),
                    PhotoFilterModel(id: 13, photoFilter: .posterize, filterSmallImage: engine.apply(filter: .posterize, to: smallImage)),
                    PhotoFilterModel(id: 14, photoFilter: .saturate, filterSmallImage: engine.apply(filter: .saturate, to: smallImage)),
                    PhotoFilterModel(id: 15, photoFilter: .sepia, filterSmallImage: engine.apply(filter: .sepia, to: smallImage)),
                    PhotoFilterModel(id: 16, photoFilter: .sharpen, filterSmallImage: engine.apply(filter: .sharpen, to: smallImage)),
                    PhotoFilterModel(id: 17, photoFilter: .temperature, filterSmallImage: engine.apply(filter: .temperature, to: smallImage)),
                    PhotoFilterModel(id: 18, photoFilter: .tint, filterSmallImage: engine.apply(filter: .tint, to: smallImage)),
                    PhotoFilterModel(id: 19, photoFilter: .vignette, filterSmallImage: engine.apply(filter: .vignette, to: smallImage)),
                    PhotoFilterModel(id: 20, photoFilter: .crossProcess, filterSmallImage: engine.apply(filter: .crossProcess, to: smallImage)),
                    PhotoFilterModel(id: 21, photoFilter: .blackWhite, filterSmallImage: engine.apply(filter: .blackWhite, to: smallImage)),
                    PhotoFilterModel(id: 22, photoFilter: .flipHorizontal, filterSmallImage: engine.apply(filter: .flipHorizontal, to: smallImage)),
                    PhotoFilterModel(id: 23, photoFilter: .flipVertical, filterSmallImage: engine.apply(filter: .flipVertical, to: smallImage)),
                ]
                DispatchQueue.main.async {
                    self.collectionView.reloadData()
                }
            }
        }
    }
    
    func resizeImage(image: UIImage) -> UIImage {
        let ratio: CGFloat = 0.3
        let resizedSize = CGSize(width: Int(image.size.width * ratio), height: Int(image.size.height * ratio))
        UIGraphicsBeginImageContext(resizedSize)
        image.draw(in: CGRect(x: 0, y: 0, width: resizedSize.width, height: resizedSize.height))
        let resizedImage = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return resizedImage!
    }
    
}

// MARK: Collection View Setup
extension PhotoEditingFilterToolVC: UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout {
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        switch collectionView {
        case self.collectionView:
            return self.filterList.count
        default:
            return 0
        }
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        switch collectionView {
        case self.collectionView:
            let cell = self.collectionView.dequeueReusableCell(withReuseIdentifier: R.reuseIdentifier.photoEditingToolFilterCell.identifier, for: indexPath) as! PhotoEditingToolFilterCell
            let item = self.filterList[indexPath.item]
            cell.setData(data: item)
            return cell
        default:
            return UICollectionViewCell()
        }
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        switch collectionView {
        case self.collectionView:
            let item = self.filterList[indexPath.item]
            self.delegate?.handlePhotoEditingFilterSelection(data: item)
        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
    }
    
}
