package com.example.tampopo_client.viewmodels;

import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.ViewModel;
import com.example.tampopo_client.models.ChatMessage;
import com.example.tampopo_client.models.Chatroom;
import com.example.tampopo_client.resources.ChatroomResource;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.jackson.JacksonConverterFactory;

public class ChatViewModel extends RealTimeViewModel {

    private final Retrofit retrofit;
    private final ChatroomResource chatroomResource;

    // --- LiveData ---
    private final MutableLiveData<String> chatroomIdLiveData = new MutableLiveData<>();
    private final MutableLiveData<List<ChatMessage>> chatMessages = new MutableLiveData<>(new ArrayList<>());
    private final MutableLiveData<ChatMessage> latestMessage = new MutableLiveData<>();
    private final MutableLiveData<Boolean> chatroomClosed = new MutableLiveData<>();

    // 通話中（リアルタイム監視用）
    private final MutableLiveData<String> chatFriendToMeLiveData = new MutableLiveData<>();


    // ===== 以下は追加部分（Handlerループ） =====
    private final Handler handler = new Handler(Looper.getMainLooper());
    private boolean isChecking = false; // 二重起動防止フラグ


    // ===============================
    // 通知・リアルタイム関連
    // ===============================
    private final List<NotificationListener> notificationListeners = new ArrayList<>();
    private boolean notificationSent = false; // 一度だけ通知を送るためのフラグ

    private String userId;
    private String token;
    private String chatroomId;

    public ChatViewModel() {
        this.retrofit = new Retrofit.Builder()
                .baseUrl("http://nitta-lab-www.is.konan-u.ac.jp/tampopo/")
                .addConverterFactory(JacksonConverterFactory.create())
                .build();

        this.chatroomResource = retrofit.create(ChatroomResource.class);
    }

    public ChatViewModel(String userId, String token, String chatroomId) {
        this.userId = userId;
        this.token = token;
        this.chatroomId = chatroomId;


        this.retrofit = new Retrofit.Builder()
                .baseUrl("http://nitta-lab-www.is.konan-u.ac.jp/tampopo/")
                .addConverterFactory(JacksonConverterFactory.create())
                .build();

        this.chatroomResource = retrofit.create(ChatroomResource.class);
    }

    @Override
    public Runnable onUpdate() {
        return () -> {
            if (!notificationSent) {
                notificationSent = true;
                new Handler(Looper.getMainLooper()).postDelayed(() -> {
                    Log.d("ChatViewModel", "Received test notification (after 10s).");
                    notificationListeners.forEach(NotificationListener::onNotificationReceived);
                }, 10_000); // 10秒後に通知
            }
            foundChatroom(userId,token);
            loadLatestMessage(chatroomId, userId, token);
        };
    }


    // getter
    public MutableLiveData<String> getChatroomIdLiveData() {
        return chatroomIdLiveData;
    }

    public MutableLiveData<List<ChatMessage>> getChatMessages() {
        return chatMessages;
    }

    public MutableLiveData<ChatMessage> getLatestMessageLiveData() {
        return latestMessage;
    }

    public MutableLiveData<Boolean> getChatroomClosed() {
        return chatroomClosed;
    }

    public MutableLiveData<String> getChatFriendToMeLiveData() {
        return chatFriendToMeLiveData;
    }



    // ===============================
    // 1. チャットルームに入る（かける側）
    // ===============================
    public String enterChatroom(String user0Id, String user1Id, String token) {
        Call<Chatroom> call = chatroomResource.enterChatroom(user0Id, user1Id, token);
        try {
            Response<Chatroom> response = call.execute();
            if (response.isSuccessful() && response.body() != null) {
                return response.body().getChatRoomId();
            } else {
                return null;
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
//        call.enqueue(new Callback<Chatroom>() {
//            @Override
//            public void onResponse(Call<Chatroom> call, Response<Chatroom> response) {
//                if (response.isSuccessful() && response.body() != null) {
//                    chatroomIdLiveData.setValue(response.body().getChatroomId());
//                    Log.d("ChatVM", "enterChatroom success → chatroomId: " + response.body().getChatroomId());
//                }
//            }
//
//            @Override
//            public void onFailure(Call<Chatroom> call, Throwable t) {
//                Log.e("ChatVM", "enterChatroom error: " + t.getMessage());
//            }
//        });
    }

    // 1.5 自分がchatroomに入っているのか確認する
    public void foundChatroom(String userId, String token) {
        Call<Chatroom> call = chatroomResource.getMyChatroom(userId, token);
        call.enqueue(new Callback<Chatroom>() {
            @Override
            public void onResponse(Call<Chatroom> call, Response<Chatroom> response) {
                if (response.isSuccessful() && response.body() != null) {
                    Chatroom chatroom = response.body();

                    chatroomIdLiveData.setValue(chatroom.getChatRoomId());
                    chatFriendToMeLiveData.setValue(
                            userId.equals(chatroom.getUser0Id())
                                    ? chatroom.getUser1Id()
                                    : chatroom.getUser0Id()
                    );
                } else {
                    chatroomIdLiveData.setValue(null);
                    chatroomClosed.setValue(true);
                }
            }

            @Override
            public void onFailure(Call<Chatroom> call, Throwable t) {
                Log.e("ChatroomVM", "checkCurrentChatroom error: " + t.getMessage());
            }
        });
    }




    // ===============================
    // 2. メッセージ送信
    // ===============================
    public void sendMessage(String chatroomId, String senderId, String message, String token) {
        Call<ChatMessage> call = chatroomResource.sendMessage(token, chatroomId, senderId, message);
        call.enqueue(new Callback<ChatMessage>() {
            @Override
            public void onResponse(Call<ChatMessage> call, Response<ChatMessage> response) {
                if (response.isSuccessful() && response.body() != null) {
                    ChatMessage newMessage = response.body();
                        latestMessage.setValue(newMessage);
                    }
                }


            @Override
            public void onFailure(Call<ChatMessage> call, Throwable t) {
                Log.e("ChatVM", "sendMessage error: " + t.getMessage());
            }
        });
    }

    // ===============================
    // 3. 最新メッセージ取得
    // ===============================
    public void loadLatestMessage(String chatroomId, String userId, String token) {
        Call<List<ChatMessage>> call = chatroomResource.getMessages(token, chatroomId, userId);
        call.enqueue(new Callback<List<ChatMessage>>() {
            @Override
            public void onResponse(Call<List<ChatMessage>> call, Response<List<ChatMessage>> response) {
                if (response.isSuccessful() && response.body() != null && !response.body().isEmpty()) {
                    latestMessage.setValue(response.body().get(response.body().size() - 1));
                }
            }

            @Override
            public void onFailure(Call<List<ChatMessage>> call, Throwable t) {
                Log.e("ChatVM", "loadLatestMessage error: " + t.getMessage());
            }
        });
    }

    // ===============================
    // 4. チャットルーム削除
    // ===============================
    public void destroyChatroom(String chatroomId, String userId, String token) {
        Call<Void> call = chatroomResource.destroyChatroom(token, chatroomId, userId);
        call.enqueue(new Callback<Void>() {
            @Override
            public void onResponse(Call<Void> call, Response<Void> response) {
                chatroomClosed.setValue(true);
                if (!response.isSuccessful()) {
                    Log.e("ChatVM", "destroyChatroom failed: " + response.code());
                }
            }

            @Override
            public void onFailure(Call<Void> call, Throwable t) {
                chatroomClosed.setValue(true);
                Log.e("ChatVM", "destroyChatroom error: " + t.getMessage());
            }
        });
    }

    // ===== ここから Handlerループ部分をそのまま追記 =====

    /**
     * 10秒ごとにサーバー確認を行う
     */
    private void startServerCheck() {
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                Log.d("ChatViewModel", "Checking server / Received test notification.");
                notificationListeners.forEach(NotificationListener::onNotificationReceived);
                handler.postDelayed(this, 10_000);
            }
        }, 10_000);
    }

    public void addNotificationListener(NotificationListener listener) {
        notificationListeners.add(listener);
    }

    public void clearNotificationListener() {
        notificationListeners.clear();
    }

    /**
     * 定期確認を止めたい場合に使う
     */
    public void stopServerCheck() {
        handler.removeCallbacksAndMessages(null);
        isChecking = false;
    }
}
//