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

import UIKit
import CoreLocation
import Async
import WowonderMessengerSDK

struct PhotoWidgetModel {
    let id: Int
    let image: UIImage
    let type: StickerType
    let content: String
}

protocol PhotoEditorWidgetVCDelegate {
    func handleStickerSelection(data: PhotoWidgetModel)
}

class PhotoEditorWidgetVC: UIViewController {
    
    // MARK: - IBOutlets
    
    @IBOutlet weak var collectionView: UICollectionView!
    
    // MARK: - Properties
    
    private let locationManager = CLLocationManager()
    var parentContorller: PhotoEditingStickerToolVC!
    var widgetList: [PhotoWidgetModel] = []
    var delegate: PhotoEditorWidgetVCDelegate?
    
    // MARK: - View Life Cycles
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        // Do any additional setup after loading the view.
        
        self.initialConfig()
    }
    
    // MARK: - Helper Functions
    
    // Initial Config
    func initialConfig() {
        self.setupCollectionView()
        self.setupLocationManager()
        self.setWidgetData()
    }
    
    static func widgetVC() -> PhotoEditorWidgetVC {
        let newVC = R.storyboard.photoEditor.photoEditorWidgetVC()
        return newVC!
    }
    
    // Setup Location Manager
    func setupLocationManager() {
        self.locationManager.delegate = self
        self.locationManager.requestWhenInUseAuthorization()
        self.locationManager.requestAlwaysAuthorization()
        self.locationManager.desiredAccuracy = kCLLocationAccuracyBest
        self.locationManager.startUpdatingLocation()
    }
    
    // Setup Collection View
    func setupCollectionView() {
        self.collectionView.delegate = self
        self.collectionView.dataSource = self
        self.collectionView.register(UINib(resource: R.nib.photoEditingToolWidgetCell), forCellWithReuseIdentifier: R.reuseIdentifier.photoEditingToolWidgetCell.identifier)
        let flowLayout = CollectionViewCenteredFlowLayout()
        flowLayout.estimatedItemSize = UICollectionViewFlowLayout.automaticSize
        self.collectionView.collectionViewLayout = flowLayout
    }
    
    // Set Widget Data
    func setWidgetData() {
        self.getTime()
        self.getCurrentDay()
        self.getBattery()
        self.getMoonPhase()
        self.getHashtags()
        self.getCustomQuotes()
        self.collectionView.reloadData()
    }
    
    private func getCountryName(from location: CLLocation, completion: @escaping (String) -> Void) {
        let geocoder = CLGeocoder()
        geocoder.reverseGeocodeLocation(location) { placemarks, error in
            if let country = placemarks?.first?.country {
                completion(country)
            } else {
                completion("")
            }
        }
    }
    
    func getTime() {
        let dateFormatter = DateFormatter()
        dateFormatter.timeStyle = .short
        let currentTime = dateFormatter.string(from: Date())
        let tvDateTime = "🕒 \(currentTime)"
        if let itemView = Bundle.main.loadNibNamed("PhotoWidgetTextView", owner: nil, options: nil)?.first as? PhotoWidgetTextView {
            itemView.widgetLabel.text = tvDateTime
            if let bitmap = BitmapUtils.loadImageFromView(itemView) {
                let exists = widgetList.contains(where: { $0.content == "Time" })
                if !exists {
                    let model = PhotoWidgetModel(
                        id: widgetList.count + 1,
                        image: bitmap,
                        type: .widget,
                        content: "Time"
                    )
                    widgetList.append(model)
                }
            }
        }
    }
    
    func getCurrentDay() {
        let date = Date()
        let calendar = Calendar.current
        let weekday = calendar.component(.weekday, from: date)
        let days = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]
        let currentDay = days[weekday - 1]
        if let itemView = Bundle.main.loadNibNamed("PhotoWidgetTextView", owner: nil, options: nil)?.first as? PhotoWidgetTextView {
            itemView.widgetLabel.text = currentDay
            if let bitmap = BitmapUtils.loadImageFromView(itemView) {
                let exists = widgetList.contains(where: { $0.content == "Day" })
                if !exists {
                    let model = PhotoWidgetModel(
                        id: widgetList.count + 1,
                        image: bitmap,
                        type: .widget,
                        content: "Day"
                    )
                    widgetList.append(model)
                }
            }
        }
    }
    
    func getHashtags() {
        if let itemView = Bundle.main.loadNibNamed("PhotoWidgetTextView", owner: nil, options: nil)?.first as? PhotoWidgetTextView {
            itemView.widgetLabel.text = "# HASHTAG"
            if let bitmap = BitmapUtils.loadImageFromView(itemView) {
                let exists = widgetList.contains(where: { $0.content == "Hashtags" })
                if !exists {
                    let model = PhotoWidgetModel(
                        id: widgetList.count + 1,
                        image: bitmap,
                        type: .widget,
                        content: "Hashtags"
                    )
                    widgetList.append(model)
                }
            }
        }
    }

    
    func getBattery() {
        UIDevice.current.isBatteryMonitoringEnabled = true
        let level = Int(UIDevice.current.batteryLevel * 100)
        let batteryText = "🔋 Battery: \(level)%"
        if let itemView = Bundle.main.loadNibNamed("PhotoWidgetTextView", owner: nil, options: nil)?.first as? PhotoWidgetTextView {
            itemView.widgetLabel.text = batteryText
            if let bitmap = BitmapUtils.loadImageFromView(itemView) {
                let exists = widgetList.contains(where: { $0.content == "Battery" })
                if !exists {
                    let model = PhotoWidgetModel(
                        id: widgetList.count + 1,
                        image: bitmap,
                        type: .widget,
                        content: "Battery"
                    )
                    widgetList.append(model)
                }
            }
        }
    }
    
    func getCustomQuotes() {
        let quotes = [
            "Believe in yourself 💪",
            "You got this! ✨",
            "Happy New Year 🎉",
            "Merry Christmas 🎄",
            "Wanderlust ✈️",
            "Beach Vibes 🌊"
        ]
        for (index, quote) in quotes.enumerated() {
            if let itemView = Bundle.main.loadNibNamed("PhotoWidgetTextView", owner: nil, options: nil)?.first as? PhotoWidgetTextView {
                itemView.widgetLabel.text = quote
                if let bitmap = BitmapUtils.loadImageFromView(itemView) {
                    let contentKey = "CustomQuotes\(index)"
                    let exists = widgetList.contains(where: { $0.content == contentKey })
                    if !exists {
                        let model = PhotoWidgetModel(
                            id: widgetList.count + 1,
                            image: bitmap,
                            type: .widget,
                            content: contentKey
                        )
                        widgetList.append(model)
                    }
                }
            }
        }
    }
    
    func getMoonPhase() {
        let moonPhase = MoonPhaseCalculator.getMoonPhase()
        if let itemView = Bundle.main.loadNibNamed("PhotoWidgetTextView", owner: nil, options: nil)?.first as? PhotoWidgetTextView {
            itemView.widgetLabel.text = moonPhase
            if let bitmap = BitmapUtils.loadImageFromView(itemView) {
                let exists = widgetList.contains(where: { $0.content == "MoonPhase" })
                if !exists {
                    let sticker = PhotoWidgetModel(
                        id: widgetList.count + 1,
                        image: bitmap,
                        type: .widget,
                        content: "MoonPhase"
                    )
                    widgetList.append(sticker)
                }
            }
        }
    }
    
}

// MARK: - Extensions

// MARK: Api Call
extension PhotoEditorWidgetVC {
    
    private func weatherForecast(latitude: Double, longitude: Double) {
        if Connectivity.isConnectedToNetwork() {
            Async.background {
                WeatherManager.sharedInstance.weatherForecast(latitude: latitude, longitude: longitude, completionBlock: { (success, authError, error) in
                    Async.main {
                        if success != nil {
                            if let temp_c = success?.current?.temp_c {
                                let temperature = String(temp_c)
                                let weatherText = "🌡 " + temperature + "°C"
                                if let itemView = Bundle.main.loadNibNamed("PhotoWidgetTextView", owner: nil, options: nil)?.first as? PhotoWidgetTextView {
                                    itemView.widgetLabel.text = weatherText
                                    if let bitmap = BitmapUtils.loadImageFromView(itemView) {
                                        let exists = self.widgetList.contains(where: { $0.content == "Weather" })
                                        if !exists {
                                            let model = PhotoWidgetModel(
                                                id: self.widgetList.count + 1,
                                                image: bitmap,
                                                type: .widget,
                                                content: "Weather"
                                            )
                                            self.widgetList.append(model)
                                            self.collectionView.reloadData()
                                        }
                                    }
                                }
                            }
                        } else if authError != nil {
                            print(authError?.message ?? "")
                        } else if error != nil {
                            print(error?.localizedDescription ?? "")
                        }
                    }
                })
            }
        } else {
            print(InterNetError)
        }
    }
    
}

// MARK: Collection View Setup
extension PhotoEditorWidgetVC: UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout {
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        switch collectionView {
        case self.collectionView:
            return self.widgetList.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.photoEditingToolWidgetCell.identifier, for: indexPath) as! PhotoEditingToolWidgetCell
            let item = self.widgetList[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.widgetList[indexPath.item]
            self.delegate?.handleStickerSelection(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
    }
    
}

// MARK: CLLocationManagerDelegate
extension PhotoEditorWidgetVC: CLLocationManagerDelegate {
    
    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        guard let location = locations.first else { return }
        self.locationManager.stopUpdatingLocation()
        self.getCountryName(from: location) { countryName in
            guard !countryName.isEmpty else { return }
            let locationText = "📍 \(countryName.uppercased())"
            if let itemView = Bundle.main.loadNibNamed("PhotoWidgetTextView", owner: nil, options: nil)?.first as? PhotoWidgetTextView {
                itemView.widgetLabel.text = locationText
                if let bit = BitmapUtils.loadImageFromView(itemView) {
                    let exists = self.widgetList.contains(where: { $0.content == "Location" })
                    if !exists {
                        let model = PhotoWidgetModel(
                            id: self.widgetList.count + 1,
                            image: bit,
                            type: .widget,
                            content: "Location"
                        )
                        self.widgetList.append(model)
                        self.collectionView.reloadData()
                    }
                }
            }
            self.weatherForecast(latitude: location.coordinate.latitude, longitude: location.coordinate.longitude)
        }
    }
    
    func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
        print("Location error: \(error.localizedDescription)")
    }
    
}

class MoonPhaseCalculator {
    
    static func getMoonPhase() -> String {
        let calendar = Calendar(identifier: .gregorian)
        let now = Date()
        let components = calendar.dateComponents([.year, .month, .day], from: now)
        
        var year = components.year ?? 2000
        var month = components.month ?? 1
        let day = components.day ?? 1
        
        if month < 3 {
            year -= 1
            month += 12
        }
        
        let a = Double(year) / 100.0
        let b = a / 4.0
        let c = 2 - a + b
        let e = floor(365.25 * Double(year + 4716))
        let f = floor(30.6001 * Double(month + 1))
        
        let julianDay = c + Double(day) + e + f - 1524.5
        let daysSinceNewMoon = julianDay - 2451550.1
        let moonCycle = daysSinceNewMoon / 29.53058867
        let moonPhase = moonCycle - floor(moonCycle)
        
        print("Julian Day: \(julianDay)")
        print("Days Since New Moon: \(daysSinceNewMoon)")
        print("Moon Cycle: \(moonCycle)")
        print("Moon Phase (0-1): \(moonPhase)")
        
        switch moonPhase {
        case ..<0.03:
            return "🌑 New Moon"
        case ..<0.22:
            return "🌒 Waxing Crescent"
        case ..<0.28:
            return "🌓 First Quarter"
        case ..<0.47:
            return "🌔 Waxing Gibbous"
        case ..<0.53:
            return "🌕 Full Moon"
        case ..<0.72:
            return "🌖 Waning Gibbous"
        case ..<0.78:
            return "🌗 Last Quarter"
        default:
            return "🌘 Waning Crescent"
        }
    }
}



class BitmapUtils {
    
    static func loadImageFromView(_ view: UIView) -> UIImage? {
        let targetSize = view.systemLayoutSizeFitting(UIView.layoutFittingCompressedSize)
        view.frame = CGRect(origin: .zero, size: targetSize)
        view.layoutIfNeeded()
        let renderer = UIGraphicsImageRenderer(size: targetSize)
        let image = renderer.image { context in
            view.drawHierarchy(in: view.bounds, afterScreenUpdates: true)
        }
        return image
    }
    
}
