import SwiftUI
import UIKit


struct ImagePicker: UIViewControllerRepresentable {
    @Binding var selectedImage: UIImage?
    @Environment(\.presentationMode) var presentationMode
    
    class Coordinator: NSObject, UINavigationControllerDelegate, UIImagePickerControllerDelegate {
        let parent: ImagePicker
        
        init(parent: ImagePicker) {
            self.parent = parent
        }
        
        func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
            if let image = info[.originalImage] as? UIImage {
                parent.selectedImage = image
            }
            
            parent.presentationMode.wrappedValue.dismiss()
        }
        
        func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
            parent.presentationMode.wrappedValue.dismiss()
        }
    }
    
    func makeCoordinator() -> Coordinator {
        Coordinator(parent: self)
    }
    
    func makeUIViewController(context: Context) -> UIImagePickerController {
        let picker = UIImagePickerController()
        picker.delegate = context.coordinator
        picker.sourceType = .photoLibrary
        return picker
    }
    
    func updateUIViewController(_ uiViewController: UIImagePickerController, context: Context) {}
}


struct ViewEButtonStyle: ButtonStyle {
    var isPressedStyle: Bool = false
    
    func makeBody(configuration: Self.Configuration) -> some View {
        configuration.label
            .padding(20)
            .background(
                Group {
                    if configuration.isPressed || isPressedStyle {
                        Capsule()
                            .fill(Color(.systemGray5))
                            .overlay(
                                Capsule()
                                    .stroke(Color.white, lineWidth: 4)
                                    .shadow(color: Color.white.opacity(0.7), radius: 10, x: -5, y: -5)
                                    .shadow(color: Color.black.opacity(0.2), radius: 10, x: 5, y: 5)
                            )
                    } else {
                        Capsule()
                            .fill(Color(.systemGray6))
                            .shadow(color: Color.black.opacity(0.2), radius: 10, x: 5, y: 5)
                            .shadow(color: Color.white.opacity(0.7), radius: 10, x: -5, y: -5)
                    }
                }
            )
            .scaleEffect(configuration.isPressed ? 0.95 : 1)
            .animation(.spring(), value: configuration.isPressed)
    }
}

// ViewE's Button
struct ViewEButton: View {
    var title: String
    var action: () -> Void
    var isPressedStyle: Bool = false
    
    var body: some View {
        Button(action: action) {
            Text(title)
                .foregroundColor(.gray)
        }
        .buttonStyle(ViewEButtonStyle(isPressedStyle: isPressedStyle))
    }
}

// ViewE View
struct ViewE: View {
    @State private var images: [UIImage?] = [nil, nil, nil, nil, nil]
    @State private var showingImagePicker = false
    @State private var selectedImageIndex = 0
    @State private var userTexts: [String] = Array(repeating: "", count: 5)
    
    let imagePlaceholders = [
        "Indsæt et foto fra din kamerarulle",
        "Indsæt et foto fra din kamerarulle",
        "Indsæt et foto fra din kamerarulle",
        "Indsæt et foto fra din kamerarulle",
        "Indsæt et foto fra din kamerarulle"
    ]
    
    let textEditorPlaceholders = [
        "Skriv tekst her",
        "Skriv tekst her",
        "Skriv tekst her",
        "Skriv tekst her",
        "Skriv tekst her"
    ]
    
    var body: some View {
        GeometryReader { geometry in
            let padding = geometry.size.width / 9
            ScrollView {
                VStack(spacing: 20) {
                    Text("Portfolio til din App")
                        .font(.largeTitle)
                        .padding(.top, 20)
                     .foregroundColor(.black)
                    
                    Text("Vis din rejse fra idéudvikling, idébeskrivelse, mindmap og prototype til din app. Upload dine skærmbilleder fra processen på denne side ved at klikke på boksene og vælge dine fotos fra kamerarullen.")
                        .font(.subheadline)
                        .padding(.bottom, 20)
                        .foregroundColor(.black)
                    
                    VStack(spacing: 20) {
                        ForEach(0..<images.count, id: \.self) { index in
                            VStack {
                                Button(action: {
                                    selectedImageIndex = index
                                    showingImagePicker = true
                                }) {
                                    if let image = images[index] {
                                        Image(uiImage: image)
                                            .resizable()
                                            .scaledToFit()
                                            .frame(width: geometry.size.width - padding * 2, height: (geometry.size.width - padding * 2) * 3 / 4)
                                            .border(Color.gray)
                                            .padding(.horizontal, padding)
                                            .cornerRadius(10) 
                                    } else {
                                        Text(imagePlaceholders[index])
                                            .frame(width: geometry.size.width - padding * 2, height: (geometry.size.width - padding * 2) * 3 / 4)
                                            .background(Color.gray)
                                            .foregroundColor(.black)
                                            .border(Color.gray)
                                            .padding(.horizontal, padding)
                                            .cornerRadius(10) 
                                    }
                                }
                                ZStack(alignment: .topLeading) {
                                    TextEditor(text: $userTexts[index])
                                        .foregroundColor(Color.primary) 
                                        .background(Color.clear) 
                                        .frame(height: 100) 
                                        .overlay(
                                            RoundedRectangle(cornerRadius: 8)
                                                .stroke(Color.gray, lineWidth: 1)
                                        )
                                        .cornerRadius(10) 
                                        .padding(.horizontal, padding)
                                        .onTapGesture {
                                            if userTexts[index] == textEditorPlaceholders[index] {
                                                userTexts[index] = ""
                                            }
                                        }
                                    
                                    if userTexts[index].isEmpty {
                                        Text(textEditorPlaceholders[index])
                                            .foregroundColor(.gray)
                                            .padding(.horizontal, padding + 5) 
                                            .padding(.top, 8) 
                                    }
                                }
                                .padding(.top, 10)
                            }
                        }
                        if images.count < 20 {
                            ViewEButton(title: images.count >= 10 ? "Leger du bare nu?" : "Tilføj flere") {
                                images.append(nil)
                                userTexts.append("")
                            }
                            .frame(width: geometry.size.width - 40, height: 50)
                            .padding(.bottom, 20) 
                        }
                    }
                }
                .padding([.leading, .trailing], 20)
            }
            .frame(width: geometry.size.width, height: geometry.size.height)
            .background(
                LinearGradient(
                    gradient: Gradient(colors: [
                        Color(red: 217 / 255, green: 201 / 255, blue: 254 / 255),
                        Color(red: 86 / 255, green: 193 / 255, blue: 255 / 255)
                    ]),
                    startPoint: .leading,
                    endPoint: .trailing
                )
                .edgesIgnoringSafeArea(.all) 
            )
        }
        .sheet(isPresented: $showingImagePicker) {
            ImagePicker(selectedImage: Binding(
                get: { images[selectedImageIndex] },
                set: { images[selectedImageIndex] = $0 }
            ))
        }
    }
}

struct ViewE_Previews: PreviewProvider {
    static var previews: some View {
        ViewE()
    }
}

