//
//  ChatView.swift
//  forShip
//
//  Created by Mamoru Sugita on 2023/10/16.
//

import SwiftUI

struct ChatView: View {
    @EnvironmentObject private var selectedTabModel: SelectedTabModel
    @ObservedObject var message = SharingData.message
    @State var isShowMember: Bool = false
    @State var isNotification = Preferences.ChatNotification
    @State var isFocus: Bool = true

    var body: some View {
        ZStack {
            if message.mode {
                LinearGradient(gradient: Gradient(colors: [.chatEmargencyColor1,  .chatEmargencyColor2]), startPoint: .top, endPoint: .bottom)
                    .ignoresSafeArea()
            }
            VStack(spacing: 0) {
                ChatTitleView(isShowMember: $isShowMember, isNotification: $isNotification)

                ZStack {
                    ScrollViewReader { proxy in
                        ScrollView(.vertical) {
                            VStack {
                                Spacer()
                                    .frame(height: 20)

                                ForEach(message.messages, id: \.messageId) { msg in
                                    if msg.message != nil {
                                        if msg.from == Preferences.UserName {
                                            //自分のメッセージ
                                            MyChatContentView(message: msg)
                                                .padding(.bottom, 24)
                                        }else{
                                            //他人のメッセージ
                                            OtherChatContentView(message: msg)
                                                .padding(.bottom, 24)
                                        }
                                    } else {
                                        AlertChatMessage(message: msg)
                                            .padding(.bottom, 24)
                                    }
                                }
                            }
                            .onAppear {
                                guard !message.messages.isEmpty,
                                      let id = message.messages.last?.messageId else { return }
                                proxy.scrollTo(id, anchor: .bottom)
                                DispatchQueue.main.async {
                                    message.viewCnt = 0
                                }
                            }
                            .onChange(of: message.messages.count) { newValue in
                                withAnimation {
                                    if let id = message.messages.last?.messageId {
                                        proxy.scrollTo(id, anchor: .bottom)

                                        //Warningモードは既読は返さない
                                        if message.messages.last?.message != nil {
                                            if message.messages.last?.from != Preferences.UserName {
                                                DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
                                                    let getMessage = GetMessage()
                                                    getMessage.readNotification()
                                                }
                                            }
                                        }

                                        message.viewCnt = 0
                                    }
                                }
                            }
                            .onReceive(message.$messages) { (value) in
                                withAnimation {
                                    guard !value.isEmpty else {return}
                                    if let id = message.messages.last?.messageId {
                                        proxy.scrollTo(id, anchor: .bottom)
                                        message.viewCnt = 0
                                    }
                                }
                            }
                        }
                    }
                    HStack {
                        Spacer()
                        VStack{
                            Button{
                                selectedTabModel.isShowChangeEmrMode.toggle()
                                isFocus = false
                            }label: {
                                Image(systemName: "exclamationmark.triangle.fill")
                                    .foregroundColor(.white)
                                    .frame(width: 48, height: 48)
                                    .background(ColorSet.Notice.color)
                                    .cornerRadius(50)
                            }.padding(9)
                            Spacer()
                        }
                    }
                    if isShowMember{
                        ChatMemberView()
                    }
                }
                .onTapGesture {
                    isFocus = false
                }
                ChatInputView(isFocus: $isFocus)
            }
        }
        .background(ColorSet.BackgroundPrimary.color)
    }
}

struct AlertChatMessage: View {
    @Environment(\ .colorScheme) var colorScheme
    var message : ChatMessage

    var body: some View {
        if message.mode == ChatMode.warningProgress.rawValue {
            HStack() {
                Rectangle()
                    .fill(ColorSet.ChatDate.color)
                    .frame(width: 20, height: 1)
                Text("Warning mode start  " + DateTextLib.ISO86012FormatText(message.time, format: "yyyy/MM/dd HH:mm", errFormat: ""))
                    .font(FontStyle.DateText.font)
                    .foregroundColor(ColorSet.ChatDate.color)
                Rectangle()
                    .fill(ColorSet.ChatDate.color)
                    .frame(width: 20, height: 1)
            }
        } else {
            HStack() {
                Rectangle()
                    .fill(ColorSet.ChatDate.color)
                    .frame(width: 20, height: 1)
                Text("Warning mode end  " + DateTextLib.ISO86012FormatText(message.time, format: "yyyy/MM/dd HH:mm", errFormat: ""))
                    .font(FontStyle.DateText.font)
                    .foregroundColor(ColorSet.ChatDate.color)
                Rectangle()
                    .fill(ColorSet.ChatDate.color)
                    .frame(width: 20, height: 1)
            }
        }
    }
}

#Preview {
    ChatView()
}

