//
//  ScanItemView.swift
//  JustScanIt
//
//  Created by Pradyun Setti on 03/07/2024.
//

import SwiftUI

struct ScanItemView: View {
    @Environment(\.modelContext) var ctx
    @Namespace private var animation
    
    @State private var isZoomed = false
    
    let scan: Scan
    let images: [Image]
    let uiImages: [UIImage]
    
    private let translucentColour = Color(red: 0.6, green: 0.8, blue: 1, opacity: 0.4)
    
    private let bgBottomColour = Color(red: 33/255, green: 90/255, blue: 1, opacity: 1)
    private let bgTopColour = Color(red: 0/255, green: 130/255, blue: 1, opacity: 1)
    
    init(_ scan: Scan) {
        self.scan = scan
        self.images = scan.toSwiftUIImages()
        self.uiImages = scan.toUIImages()
    }
    
    var body: some View {
        LazyVStack {
            HStack {
                if !isZoomed {
                    self.images.first!
                        .resizable()
                        .scaledToFit()
                        .matchedGeometryEffect(id: "images", in: animation)
                        .frame(maxWidth: 70, maxHeight: 70)
                        .padding(4)
//                        .background(translucentColour)
//                        .clipShape(RoundedRectangle(cornerRadius: 12))
                        .onTapGesture {
                            withAnimation(.easeInOut(duration: 0.3)) {
                                isZoomed = true
                            }
                        }
                }
                
                VStack(alignment: .leading) {
                    Text("\(scan.imageCount) \(scan.imageCount == 1 ? "Page" : "Pages")")
                        .font(.title3)
                    Text("\(scan.timestamp.formatted())")
                        .font(.footnote)
                }
                .foregroundStyle(.white)
                Spacer()
                
                HStack {
                    Button { scan.copyImages() } label: {
                        Image(systemName: "doc.on.doc.fill").tint(.white)
                            .padding(8)
                            .background(translucentColour)
                            .clipShape(Circle())
                    }
                    
                    ShareLink(items: self.images, preview: { _ in SharePreview("Scan", image: self.images.first!)} )  {
                        Image(systemName: "square.and.arrow.up").tint(.white)
                            .padding(8)
                            .background(translucentColour)
                            .offset(y: -2)
                            .clipShape(Circle())
                    }
                    
                    Button { delete() } label: {
                        Image(systemName: "xmark").bold().tint(.red)
                            .padding(8)
                            .background(translucentColour)
                            .clipShape(Circle())
                    }
                }
                .shadow(radius: 6, y: 0)
                
                .contextMenu(menuItems: {
                    Button("Delete All Scans", role: .destructive) {
                        deleteAll()
                    }
                })
//                
            }
            
            if isZoomed {
                TabView {
                    ForEach(self.uiImages, id: \.self) { img in
                        Image(uiImage: img)
                            .resizable()
                            .scaledToFit()
                            .frame(maxHeight: 400)
                            .pinchToZoom()
                            .onTapGesture {
                                withAnimation(.easeInOut(duration: 0.3)) {
                                    isZoomed = false
                                }
                            }
                    }
                }
                .matchedGeometryEffect(id: "images", in: animation)
                .frame(height: 400)
                .tabViewStyle(.page(indexDisplayMode: .never))
            }
            
        }
        .padding()
//        .background(Color(red: 0.4, green: 0.6, blue: 0.9, opacity: 0.8))
        .background(bgTopColour)
//        .background(Gradient(colors: [bgTopColour, bgBottomColour]))
        .clipShape(RoundedRectangle(cornerRadius: 28))
        .padding(.horizontal, 12)
    }
    
    func delete() {
        withAnimation(.spring) {
            ctx.delete(scan)
            try? ctx.save()
        }
    }
    
    func deleteAll() {
        withAnimation(.easeOut) {
            try? ctx.delete(model: Scan.self)
            try? ctx.save()
        }
    }
}

#Preview {
    let scan = Scan(images: Array(repeating: UIImage(systemName: "book.fill")!, count: 5))
    
    return NavigationView {
        ScrollView {
            ForEach(Array(repeating: scan, count: 10)) { s in
                ScanItemView(s)
            }
        }
        .navigationTitle("Just Scan It!")
    }
}
