//
//  MyChatContentView.swift
//  Sailassist
//
//  Created by Mamoru Sugita on 2023/11/08.
//
import SwiftUI
import AVKit

struct MyChatContentView: View {
    @EnvironmentObject private var selectedTabModel: SelectedTabModel
    @State private var safariUrl: URL? = nil
    @State private var isSafariPresented = false
    var message : ChatMessage
    var contentWidth: CGFloat
    var onMediaLoaded: (() -> Void)? = nil

    var body: some View {
        HStack {
            Spacer()
            VStack(alignment: .trailing, spacing: 6) {
                Group {
                    HStack(alignment: .top, spacing: 6) {
                        if message.Latitude != nil && message.Longitude != nil {
                            Image("map_pin")
                                .resizable()
                                .frame(width: 20, height: 20)
                        }
                        if let msg = message.message {
                            if msg.contains(".jpg") || msg.contains(".png") {
                                ChatUrlImageView(imageUrl: msg, onLoad: onMediaLoaded)
                                    .onTapGesture {
                                        isSafariPresented = true
                                    }
                            } else {
                                Text(msg)
                                    .font(FontStyle.DefaultText.font)
                                    .foregroundColor(ColorSet.BodyChat.color)
                                    .padding(15)
                                    .background(ColorSet.ChatBaloon.color)
                                    .border(Color.red.gradient.opacity(0.8), width: (message.mode == ChatMode.warningProgress.rawValue ? 2 : 0))
                                    .clipShape(
                                        .rect(
                                            topLeadingRadius: 10,
                                            bottomLeadingRadius: 10,
                                            bottomTrailingRadius: 0,
                                            topTrailingRadius: 10
                                        ))
                                    .frame(maxWidth: contentWidth * 0.8, alignment: .trailing)
                                    .multilineTextAlignment(.leading)
                                    .onAppear {
                                        onMediaLoaded?()
                                    }
                            }
                        }
                    }
                }
                .onAppear {
                    if message.type >= 1 {
                        var urlString: String = HttpRequestType.RawImage.rawValue
                        urlString = urlString.replacingOccurrences(of: "XXXXX", with: String(message.shipId))
                        urlString = urlString.replacingOccurrences(of: "YYYYY", with: String(message.messageId))

                        if let url = URL(string: urlString) {
                            safariUrl = url
                        }
                    }
                }
                .onChange(of: selectedTabModel.activeTab) { newValue in
                    if newValue != Tab.chat {
                        isSafariPresented = false
                    }
                }

                HStack(spacing: 5){
                    //MARK: - 既読マーク
                    Text(DateTextLib.ISO86012FormatText(message.time, format: "yyyy/MM/dd HH:mm", errFormat: ""))
                        .padding(.trailing, 8)

                    let viewerCnt = viewerCnt()

                    Image("chat_company")
                        .resizable()
                        .scaledToFit()
                        .frame(width: 12, height: 12)
                        .padding(.trailing, 4)

                    Text(String(viewerCnt.1))

                    Image("chat_ship")
                        .resizable()
                        .scaledToFit()
                        .frame(width: 12, height: 12)
                        .padding(.trailing, 4)

                    Text(String(viewerCnt.0))
                }
                .font(FontStyle.DateText.font)
                .foregroundColor(ColorSet.ChatDate.color)
            }
            .padding(.trailing, 20)
        }
        .fullScreenCover(isPresented: $isSafariPresented) {
            if let url = safariUrl {
                SafariView(url: url) {
                    isSafariPresented = false
                }
            } else {
                Text("URLが無効です")
            }
        }
    }

    func viewerCnt() -> (Int, Int) {
        var shipViewer = -1
        var companyViewr = 0
        for viewer in message.viewer {
            if viewer.location == 1 {
                companyViewr += 1
            } else {
                shipViewer += 1
            }
        }
        if shipViewer == -1 { shipViewer = 0 }
        return (shipViewer, companyViewr)
    }
}
