//
//  EditSharingView.swift
//  Padel Tournament
//
//  Created by Razmig Sarkissian on 03/02/2024.
//

import SwiftUI
import TipKit
import CoreTransferable

struct EditSharingView: View {
    var match: Match
    @State private var displayRank: Bool = false
    @State private var displayTeamTitle: Bool = false
    @State private var showCamera: Bool = false
    @State private var newImage: UIImage?
    @State private var copied: Bool = false

    var shareMessage: String {
        shareMessage(displayRank: displayRank, displayTeamName: displayTeamTitle)
    }
    
    func shareMessage(displayRank: Bool, displayTeamName: Bool) -> String {
        var messageData: [String] = []
        
        var locAndTime: String = ""
        if let courtName = match.courtName() {
            locAndTime.append("\(courtName)")
        }
        
        if let startDate = match.startDate {
            locAndTime = locAndTime + " à " + startDate.formattedAsHourMinute()
        }
        
        if locAndTime.isEmpty == false {
            messageData.append(locAndTime)
        }
        
        if let tournament = match.currentTournament() {
            messageData.append(tournament.tournamentTitle())
        }
        
        let message = [match.isLoserBracket ? "Classement" : nil, match.roundTitle(), match.isLoserBracket ? nil : ((match.index > 0 || match.isGroupStage()) ? match.matchTitle(.short) : nil)].compactMap({ $0 }).joined(separator: " ")

        messageData.append(message)
        
        guard let labelOne = match.team(.one)?.teamLabelRanked(displayRank: displayRank, displayTeamName: displayTeamName), let labelTwo = match.team(.two)?.teamLabelRanked(displayRank: displayRank, displayTeamName: displayTeamName) else {
            return messageData.joined(separator: "\n")
        }
        
        let players = "\(labelOne)\ncontre\n\(labelTwo)"
        messageData.append(players)
        
        return messageData.joined(separator: "\n")
    }
    


    var body: some View {
        List {
            if let newImage {
                Section {
                    let tip = SharePictureTip()
                    TipView(tip)
                        .tipStyle(tint: .green)
                }
                
                Section {
                    ZStack {
                        Color.black
                            .ignoresSafeArea()
                        Image(uiImage: newImage)
                            .resizable()
                            .scaledToFit()
                            .frame(height: 200, alignment: .center)
                            .frame(maxWidth: .infinity, alignment: .center)
                    }
                    .listRowInsets(EdgeInsets())
                } footer: {
                    HStack {
                        Spacer()
                        Button("effacer", role: .destructive) {
                            self.newImage = nil
                        }
                    }
                }
            } else {
                Section {
                    RowButtonView("Prendre une photo", systemImage: "camera") {
                        showCamera = true
                    }
                }                                
            }
            
            Section {
                Toggle(isOn: $displayRank) {
                    Text("Afficher leurs rangs dans ce tournoi")
                }
                
                Toggle(isOn: $displayTeamTitle) {
                    Text("Afficher plutôt le nom de l'équipe")
                }
            } header: {
                Text("Options")
            }

            Section {
                Text(shareMessage)
            } header: {
                Text("Message type généré")
            } footer: {
                HStack {
                    Spacer()
                    CopyPasteButtonView(pasteValue: shareMessage)
                }
            }
        }
        .toolbar {
            ToolbarItem(placement: .topBarTrailing) {
                if let newImage {
                    let photo = Photo(image: Image(uiImage:newImage), caption: shareMessage)
                    ShareLink(
                        item: photo,
                        preview: SharePreview(
                            photo.caption,
                            image: photo.image)) {
                                Text("Partager")
                            }
                            .onAppear {
                                UIPasteboard.general.string = shareMessage
                                copied = true
                            }
                } else {
                    ShareLink("Partager", item: shareMessage)
                }
            }
        }
        .navigationTitle("Préparation")
        .navigationBarTitleDisplayMode(.inline)
        .toolbarBackground(.visible, for: .navigationBar)
        .fullScreenCover(isPresented: $showCamera) {
            ImagePickerView(image: $newImage)
                .background(Color.black.edgesIgnoringSafeArea(.all))
        }
        .onChange(of: displayRank) {
            copied = false
        }
        .onChange(of: displayTeamTitle) {
            copied = false
        }
    }
}

struct Photo: Transferable {
    static var transferRepresentation: some TransferRepresentation {
        ProxyRepresentation(exporting: \.image)
        ProxyRepresentation(exporting: \.caption)
    }

    public var image: Image
    public var caption: String
}
