package com.kaixed.kchat.view.activity;

import static com.kaixed.kchat.utils.Constants.MMKV_COMMON_DATA;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.ObjectAnimator;
import android.annotation.SuppressLint;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.IBinder;
import android.view.View;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.kaixed.kchat.R;
import com.kaixed.kchat.database.ObjectBox;
import com.kaixed.kchat.database.entity.ChatLists;
import com.kaixed.kchat.database.entity.ChatLists_;
import com.kaixed.kchat.database.entity.Messages;
import com.kaixed.kchat.databinding.ActivityMainBinding;
import com.kaixed.kchat.model.HomeItem;
import com.kaixed.kchat.service.WebSocketService;
import com.kaixed.kchat.view.adapter.ChatListAdapter;
import com.kaixed.kchat.view.adapter.MyGridAdapter;
import com.kaixed.kchat.view.i.OnChatListItemClickListener;
import com.tencent.mmkv.MMKV;

import java.util.ArrayList;
import java.util.List;

import io.objectbox.Box;

/**
 * @Author: kaixed
 * @Date: 2024/5/26 10:02
 * @Description: 应用的主活动
 */
public class MainActivity extends AppCompatActivity implements OnChatListItemClickListener {
    private ActivityMainBinding binding;
    private List<ChatLists> chatLists = new ArrayList<>();
    private ChatListAdapter chatListAdapter;
    private Box<ChatLists> chatListsBox;
    private Box<Messages> messagesBox;
    private String updateUsername;
    private final List<HomeItem> items = new ArrayList<>();
    private WebSocketService webSocketService;
    private boolean isFlipped = false;
    private boolean isBound = false;
    private final Context mContext = this;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        binding = ActivityMainBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());

        chatListsBox = ObjectBox.get().boxFor(ChatLists.class);
        messagesBox = ObjectBox.get().boxFor(Messages.class);

        initView();

        startService();

        setOnClick();


    }

    private void setOnClick() {
        binding.ivMessage.setOnClickListener(v -> {
            Intent intent = new Intent(this, MessageActivity.class);
            startActivity(intent);
        });
        binding.ivSearch.setOnClickListener(v -> {
            Intent intent = new Intent(mContext, SearchActivity.class);
            startActivity(intent);
        });

        binding.ifvAvatar.setOnClickListener(v -> {
            Intent intent = new Intent(mContext, ProfileActivity.class);
            startActivity(intent);
        });
    }


    private void flipImage(View v) {
        ObjectAnimator flipAnimation;
        if (isFlipped) {
            flipAnimation = ObjectAnimator.ofFloat(v, "rotationX", 180F, 0F);
        } else {
            flipAnimation = ObjectAnimator.ofFloat(v, "rotationX", 0F, 180F);
        }
        flipAnimation.setDuration(0);
        flipAnimation.start();
        isFlipped = !isFlipped;
    }

    @SuppressLint("NotifyDataSetChanged")
    public void notifyData() {
        chatListAdapter.notifyDataSetChanged();
    }

    private void startService() {
        Intent intent = new Intent(MainActivity.this, WebSocketService.class);
        startService(intent);
    }

    private void observeLiveData() {
        if (webSocketService == null) {
            return;
        }
        webSocketService.getLiveData().observe(this, messages -> {
            if ("normal".equals(messages.getType())) {
                processMessage(messages);
            }
        });
    }

    private void processMessage(Messages messages) {
        String talkerId = messages.getTakerId();
        String content = messages.getContent();
        Long timestamp = messages.getTimestamp();

        ChatLists chatList = createChatList(talkerId, content, timestamp);

        int index = findChatListIndex(talkerId);
        if (index == -1) {
            chatLists.add(chatList);
        } else {
            updateChatList(chatLists.get(index), content, timestamp);
        }

        runOnUiThread(this::notifyData);
        isInDb(chatList);
    }

    private ChatLists createChatList(String talkerId, String content, Long timestamp) {
        ChatLists chatList = new ChatLists();
        chatList.setAvatarUrl("1");
        chatList.setTalkerId(talkerId);
        chatList.setNickname(talkerId);
        chatList.setTimestamp(timestamp);
        chatList.setLastContent(content);
        chatList.setUnread(1);
        return chatList;
    }

    private int findChatListIndex(String talkerId) {
        for (int i = 0; i < chatLists.size(); i++) {
            if (chatLists.get(i).getTalkerId().equals(talkerId)) {
                return i;
            }
        }
        return -1;
    }

    private void updateChatList(ChatLists chatList, String content, Long timestamp) {
        chatList.setLastContent(content);
        chatList.setTimestamp(timestamp);
    }


    private void isInDb(ChatLists chatList) {
        // 查询数据库中是否已经存在该talkerId的记录
        ChatLists existingChatList = chatListsBox
                .query(ChatLists_.talkerId.equal(chatList.getTalkerId()))
                .build()
                .findFirst();

        if (existingChatList != null) {
            // 如果存在，更新内容和时间戳
            existingChatList.setLastContent(chatList.getLastContent());
            existingChatList.setTimestamp(chatList.getTimestamp());
            chatListsBox.put(existingChatList);
        } else {
            // 如果不存在，添加新的记录
            chatListsBox.put(chatList);
        }
    }

    private void updateChatLists() {
        MMKV kv = MMKV.mmkvWithID(MMKV_COMMON_DATA);
        long msgLocalId = kv.getLong("msgLocalId", -1L);
        if (msgLocalId != -1) {
            Messages messages = messagesBox.get(msgLocalId);
            processMessage(messages);
            kv.remove("msgLocalId");
        }
    }


    ServiceConnection connection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName className, IBinder service) {
            WebSocketService.LocalBinder binder = (WebSocketService.LocalBinder) service;
            webSocketService = binder.getService();
            isBound = true;
            observeLiveData();
        }

        @Override
        public void onServiceDisconnected(ComponentName arg0) {
            isBound = false;
        }
    };

    private void initView() {
        setupGridView();
        setupRecycleView();
        setupMoreOptionsToggle();
    }

    private void setupMoreOptionsToggle() {
        binding.ivMore.setOnClickListener(v -> {
            flipImage(v);
            int gridViewHeight = binding.gridView.getHeight();
            int startAt;
            int endAt;
            if (isFlipped) {
                binding.gridView.setVisibility(View.VISIBLE);
                startAt = 0;
                endAt = gridViewHeight;
            } else {
                startAt = gridViewHeight;
                endAt = 0;
            }
            createAnimator(startAt, endAt).start();
        });
    }

    private ObjectAnimator createAnimator(int start, int end) {
        ObjectAnimator animator = ObjectAnimator.ofInt(binding.linearlayout, "top", start, end);
        long duration = 500;
        animator.setDuration(duration);

        animator.addListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationStart(Animator animation) {
                super.onAnimationStart(animation);
                binding.ivMore.setEnabled(false);
            }

            @Override
            public void onAnimationEnd(Animator animation) {
                super.onAnimationEnd(animation);
                if (!isFlipped) {
                    binding.gridView.setVisibility(View.INVISIBLE);
                }
                binding.ivMore.setEnabled(true);
            }
        });
        return animator;
    }

    private void setupRecycleView() {
        if (chatListsBox.getAll() != null) {
            chatLists = chatListsBox.getAll();
        }
        chatListAdapter = new ChatListAdapter(chatLists, this);
        binding.recycleChatList.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
        binding.recycleChatList.setAdapter(chatListAdapter);
        chatListAdapter.setItemListener(this);
    }

    private void setupGridView() {
        initMenuData();
        MyGridAdapter myGridAdapter = new MyGridAdapter(this, items);
        binding.gridView.setAdapter(myGridAdapter);

        binding.gridView.setSelector(new ColorDrawable(Color.TRANSPARENT));

        binding.gridView.setOnItemClickListener((parent, view, position, id) -> {
            switch (position) {
                case 0:
                    break;
                case 2:
                    Intent intent = new Intent(MainActivity.this, AddFriendsActivity.class);
                    startActivity(intent);
                    break;
                case 6:
                    Intent intent1 = new Intent(MainActivity.this, FriendListActivity.class);
                    startActivity(intent1);
                    break;
                default:
                    finish();
                    break;
            }
        });

    }

    private void initMenuData() {
        items.add(new HomeItem("更换背景", true, R.drawable.ic_switch));
        items.add(new HomeItem("创建群聊", false, R.drawable.ic_troop));
        items.add(new HomeItem("新朋友", true, R.drawable.ic_friend));
        items.add(new HomeItem("夜间模式", true, R.drawable.ic_night));
        items.add(new HomeItem("好友动态", false, R.drawable.ic_qzone));
        items.add(new HomeItem("扫一扫", false, R.drawable.ic_scan));
        items.add(new HomeItem("通讯录", true, R.drawable.ic_clock_in));
        items.add(new HomeItem("关闭应用", false, R.drawable.ic_exit));
    }

    @Override
    public void onItemClick(String username) {
        this.updateUsername = username;
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        updateChatLists();
    }

    @Override
    protected void onStart() {
        super.onStart();
        Intent intent = new Intent(this, WebSocketService.class);
        bindService(intent, connection, Context.BIND_AUTO_CREATE);
    }

    @Override
    protected void onStop() {
        super.onStop();
        if (isBound) {
            unbindService(connection);
            isBound = false;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        Intent intent = new Intent(MainActivity.this, WebSocketService.class);
        stopService(intent);
    }
}