//
//  CardFormView.swift
//  AlloVoisinsSwiftUI
//
//  Created by Victor on 12/11/2024.
//

import PhotosUI
import SwiftUI

struct CardFormView: View {
    @State var title: String = ""
    @State var subtitle: String = ""
    @State var job: String = ""
    @State var showRating: Bool = true
    @State var phoneNumber: String = ""
    @State var address: String = ""
    @State var selectedPicture: PhotosPickerItem?
    @State private var image: Image?
    @State private var showImagePicker = false
    @State private var showPhotoPicker = false
    @State private var showActionSheet = false
    @State private var useCamera = false

    var body: some View {
        VStack {
            ScrollView {
                VStack {
                    VStack(alignment: .leading, spacing: 16) {
                        VStack(alignment: .leading) {
                            SQText("Informations", size: 24, font: .bold)
                            SQText("Les modifications apportées sur votre carte de visite ne seront pas reportées sur votre profil.")
                        }
                        VStack(alignment: .leading) {
                            SQText("Image", font: .demiBold)

                            ZStack(alignment: .bottomTrailing) {
                                Button(action: { showActionSheet = true }) {
                                    if let image = image {
                                        image
                                            .resizable()
                                            .scaledToFill()
                                            .frame(width: 160, height: 160)
                                            .clipShape(Circle())
                                    } else {
                                        SQIcon(.camera, customSize: 40)
                                            .frame(width: 160, height: 160)
                                            .background(Color.sqNeutral(10))
                                            .clipShape(Circle())
                                    }
                                }

                                if image != nil {
                                    SQIcon(.pen_to_square, size: .m)
                                        .padding(8)
                                        .background(Circle().fill(Color.sqNeutral(15)))
                                        .shadow(color: .sqNeutral(100).opacity(0.1), radius: 4, x: 0, y: 2)
                                        .offset(x: -8, y: -8)
                                }
                            }
                            .frame(maxWidth: .infinity)
                        }
                        SQTextField("Titre", placeholder: "Ex : Pro Solutions", errorText: "", text: $title)
                        SQTextField("Sous-titre", placeholder: "Ex : Martin Dupont", errorText: "", text: $subtitle, isOptional: true)
                        SQTextField("Métier", placeholder: "Ex : Dépannage électroménager", errorText: "", text: $job, isOptional: true)
                        VStack(alignment: .leading, spacing: 0) {
                            Toggle(isOn: $showRating) {
                                SQText("Afficher ma note AlloVoisins", font: .demiBold)
                            }
                            .tint(Color.sqNeutral(100))
                            HStack(spacing: 4) {
                                SQIcon(.star, type: .solid, color: .sqGold(50))
                                SQText("4,7/5 sur", size: 12, font: .demiBold)
                                SQImage("logo", height: 14)
                            }
                        }
                        .padding(.horizontal, 2)
                    }
                    .padding()

                    Rectangle()
                        .frame(height: 16)
                        .foregroundColor(Color.sqNeutral(10))

                    VStack(alignment: .leading, spacing: 16) {
                        SQTextField("Numéro de téléphone", placeholder: "Ex : 06 12 34 56 78", errorText: "", text: $phoneNumber)
                        SQTextField("Adresse complète", placeholder: "Ex : 1 rue de la gare, 67000 Strasbourg", errorText: "", text: $address)
                    }
                    .padding()
                }
            }
            SQFooter {
                SQButton("Aperçu", color: .sqNeutral(100), textColor: .sqNeutral(100), icon: SQIcon(.eye, color: .sqNeutral(100)), isFull: false) {}
                    .sqStyle()
                SQButton("Imprimer", color: .sqNeutral(100), textColor: .white, icon: SQIcon(.print, color: .white)) {}
                    .sqStyle()
            }
        }
        .confirmationDialog("Choisir une image", isPresented: $showActionSheet, actions: {
            Button("Appareil photo") {
                useCamera = true
                showImagePicker = true
            }

            Button("Galerie") {
                useCamera = false
                showPhotoPicker = true
            }

            Button("Annuler", role: .cancel) {}
        })
        .photosPicker(isPresented: $showPhotoPicker, selection: $selectedPicture)
        .sheet(isPresented: $showImagePicker) {
            if useCamera {
                ImagePicker(image: $image, sourceType: .camera)
            }
        }
        .task(id: selectedPicture) {
            if let data = try? await selectedPicture?.loadTransferable(type: Image.self) {
                image = data
            }
        }
        .sqNavigationBar(title: "Ma carte de visite")
    }
}

struct ImagePicker: UIViewControllerRepresentable {
    @Binding var image: Image?
    let sourceType: UIImagePickerController.SourceType

    func makeUIViewController(context: Context) -> UIImagePickerController {
        let picker = UIImagePickerController()
        picker.sourceType = sourceType
        picker.delegate = context.coordinator
        return picker
    }

    func updateUIViewController(_ uiViewController: UIImagePickerController, context: Context) {}

    func makeCoordinator() -> Coordinator {
        Coordinator(self)
    }

    class Coordinator: NSObject, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
        let parent: ImagePicker

        init(_ parent: ImagePicker) {
            self.parent = parent
        }

        func imagePickerController(_ picker: UIImagePickerController,
                                   didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey: Any])
        {
            if let uiImage = info[.originalImage] as? UIImage {
                parent.image = Image(uiImage: uiImage)
            }
            picker.dismiss(animated: true)
        }
    }
}

#Preview {
    CardFormView()
}
