//
//  LivePicWidget.swift


import WidgetKit
import SwiftUI
import Intents
import Combine
import Kingfisher
import FirebaseCore

struct Provider: IntentTimelineProvider {
    
    func placeholder(in context: Context) -> SimpleEntry {
        SimpleEntry(date: Date(), configuration: ConfigurationIntent(), senderName: "Place Holder", image: UIImage(named: "widget_background")!, isFromSnapshot: false, previewType: .placeholder, imageURL: "")
    }

    func getSnapshot(for configuration: ConfigurationIntent, in context: Context, completion: @escaping (SimpleEntry) -> ()) {
        let entry = SimpleEntry(date: Date(), configuration: configuration, senderName: "Placeholder", image: UIImage(named: "widget_background")!, isFromSnapshot: true, previewType: .snapshot, imageURL: "")
        completion(entry)
    }

    func getTimeline(for configuration: ConfigurationIntent, in context: Context, completion: @escaping (Timeline<SimpleEntry>) -> ()) {
        var entries: [SimpleEntry] = []
        FirebaseApp.configure()
        
        if UserDefaultManager.shared.loginUserToken == ""{
            let entry = SimpleEntry(date: Date(), configuration: configuration, senderName: "", image: UIImage(named: "widget_background")!, isFromSnapshot: false, previewType: .widgetview, imageURL: "")
            entries.append(entry)
            
            let timeline = Timeline(entries: entries, policy: .after(Calendar.current.date(byAdding: .minute, value: 5, to: Date())!))
            completion(timeline)
        }
        else{
            NetworkManager.shared.callGetAPI(apiName: APIName.latest_image) { response, message  in
                do {
                    if let jsonData = try? JSONSerialization.data(withJSONObject: response as Any) {
                        
                        let decoder = JSONDecoder()
                        let dataModel = try decoder.decode(LatestImageAPIModel.self, from: jsonData)
                        
                        let entry = SimpleEntry(date: Date(), configuration: configuration, senderName: dataModel.image.first_name ?? "", image: dataModel.image.image_url == "" ? UIImage(named: "widget_background")! : UIImage(), isFromSnapshot: false, previewType: .widgetview, imageURL: dataModel.image.image_url ?? "")
                        entries.append(entry)
                        
                        let timeline = Timeline(entries: entries, policy: .after(Calendar.current.date(byAdding: .minute, value: 15, to: Date())!))
                        completion(timeline)
                        
                    }
                } catch {
                    debugPrint("Get Latest Image Parse Error: ",error)
                    
                    let entry = SimpleEntry(date: Date(), configuration: configuration, senderName: "", image: UIImage(named: "widget_background")!, isFromSnapshot: false, previewType: .widgetview, imageURL: "")
                    entries.append(entry)
                    
                    let timeline = Timeline(entries: entries, policy: .after(Calendar.current.date(byAdding: .minute, value: 15, to: Date())!))
                    completion(timeline)
                }
            } failure: { (error) in
                debugPrint("Error message: \(error)")
                
                let entry = SimpleEntry(date: Date(), configuration: configuration, senderName: "", image: UIImage(named: "widget_background")!, isFromSnapshot: false, previewType: .widgetview, imageURL: "")
                entries.append(entry)
                
                let timeline = Timeline(entries: entries, policy: .after(Calendar.current.date(byAdding: .minute, value: 15, to: Date())!))
                completion(timeline)
            }
        }
    }
}

struct WidgetEntryView : View {
    var entry: Provider.Entry
    @Environment(\.widgetFamily) private var family
    @Environment(\.redactionReasons) private var reasons
    
    var body: some View {
        if PreviewType.snapshot == entry.previewType || PreviewType.placeholder == entry.previewType{
            self.snapshotView()
        }
        else{
            if entry.image != UIImage(){
                self.snapshotView()
            }
            else{
                ZStack{//?.resized(to: CGSize.init(width: 300, height: 300))
                    
                    if let imgData = try? Data(contentsOf: URL(string: entry.imageURL)!) , let uiimage = UIImage(data: imgData)?.resizeImage(){
//                        let imageData = uiimage.jpegData(compressionQuality: 0.0)! as Data
//                        let uiiimage = UIImage(data: imageData)
                        Image(uiImage: uiimage)
                            .resizable()
                            .aspectRatio(contentMode: .fill)
                            .fillParent()
                    }
                    else{
                        Image("widget_background")
                            .resizable()
                            .aspectRatio(contentMode: .fill)
                        
                    }
                    
                    VStack {
                        Spacer()
                        HStack(){
                            ZStack{
                                Image("friend_icon")
                                    .resizable()
                                    .frame(width: family == .systemSmall ? 30 : 40, height: family == .systemSmall ? 30 : 40, alignment: .center)
                                Text(String(entry.senderName.first ?? Character("a")))
                                    .font(Font.custom("SF Pro Display Semibold", size: family == .systemSmall ? 13 : 15))
                                    .foregroundColor(.black)
                            }
                            Text(entry.senderName)
                                .lineLimit(1)
                                .foregroundColor(.white)
                            Spacer()
                        }
                        .padding(.leading,10)
                        .padding(.bottom,10)
                    }
                }
            }
        }
    }
    
    @ViewBuilder func snapshotView() -> some View{
        if UserDefaultManager.shared.friendList.contains("") || UserDefaultManager.shared.friendList.count == 0{
            ZStack{
                Image("widget_background")
                    .resizable()
                    .aspectRatio(contentMode: .fill)
                VStack{
                    Image("preview_ icon")
                        .resizable()
                        .frame(width: family == .systemSmall ? 110 : 236, height: family == .systemSmall ? 110 : 236)
                    Text("Tap to setup")
                        .foregroundColor(.white)
                        .font(Font.custom("SF Pro Display Semibold", size: family == .systemSmall ? 14 : 26))
                }
            }
        }
        else{
            ZStack{
                Image("widget_background")
                    .resizable()
                    .aspectRatio(contentMode: .fill)
                VStack{
                    HStack(spacing : family == .systemSmall ? 20 : 30){
                        ZStack{
                            Image("friend_icon")
                                .resizable()
                                .frame(width: family == .systemSmall ? 40 : 60, height: family == .systemSmall ? 40 : 60, alignment: .center)
                            Text(String((UserDefaultManager.shared.friendList.count >= 2 ? UserDefaultManager.shared.friendList[1].first ?? Character("Y") : "Y")))
                                .font(Font.custom("SF Pro Display Semibold", size: family == .systemSmall ? 15 : 25))
                        }
                        
                        ZStack{
                            Image("friend_icon")
                                .resizable()
                                .frame(width: family == .systemSmall ? 40 : 60, height: family == .systemSmall ? 40 : 60, alignment: .center)
                            Text(String(( UserDefaultManager.shared.friendList.count >= 3 ? UserDefaultManager.shared.friendList[2].first ?? Character("Y") : "Y")))
                                .font(Font.custom("SF Pro Display Semibold", size: family == .systemSmall ? 15 : 25))
                        }
                    }
                }
                ZStack{
                    Image("friend_icon")
                        .resizable()
                        .frame(width: family == .systemSmall ? 50 : 70, height: family == .systemSmall ? 50 : 70, alignment: .center)
                    Text(String((UserDefaultManager.shared.friendList[0].first ?? Character("Y"))))
                        .font(Font.custom("SF Pro Display Semibold", size: family == .systemSmall ? 20 : 30))
                }
            }
        }
    }
}

//struct BgModifier

extension View{
    func fillParent(alignment: Alignment = .center) -> some View {
        self
            .frame(
                minWidth: 0,
                maxWidth: .infinity,
                minHeight: 0,
                maxHeight: .infinity,
                alignment: alignment
            )
    }
}

@main
struct LivePicWidget: Widget {
    let kind: String = "LivePicWidget"

    var body: some WidgetConfiguration {
        IntentConfiguration(kind: kind, intent: ConfigurationIntent.self, provider: Provider()) { entry in
            WidgetEntryView(entry: entry).onAppear {
                FirebaseApp.configure()
            }.widgetBackground(Color.clear)
        }
        .contentMarginsDisabledIfAvailable()
        .configurationDisplayName(APP_NAME)
        .description(WIDGET_DESC)
        .supportedFamilies([.systemSmall,.systemLarge])
    }
}

struct LivePicWidget_Previews: PreviewProvider {
    static var previews: some View {
        WidgetEntryView(entry: SimpleEntry(date: Date(), configuration: ConfigurationIntent(), senderName: "Entry", image: UIImage(named: "widget_background")!, isFromSnapshot: false, previewType: .placeholder, imageURL: ""))
            .previewContext(WidgetPreviewContext(family: .systemSmall))
    }
}

//TO remove the extra padding in iOS 17 widgets
extension WidgetConfiguration{
    func contentMarginsDisabledIfAvailable() -> some WidgetConfiguration{
        if #available(iOS 17.0, *){
            return self.contentMarginsDisabled()
        }
        else{
            return self
        }
    }
}
extension View{
    //For widget background (From iOS 17 widget background needs containerBackground API for background view)
        func widgetBackground(_ backgroundView: some View) -> some View {
            if #available(iOS 17.0, *) {
                return containerBackground(for: .widget) {
                    backgroundView
                }
            } else {
                return background(backgroundView)
            }
        }
}
