package com.example.punyaria;

import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Typeface;
import android.net.Uri;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.ContextCompat;
import androidx.core.content.res.ResourcesCompat;

import com.google.firebase.database.ChildEventListener;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Locale;

public class ChatActivity extends AppCompatActivity {

    private EditText messageInput;
    private ImageButton sendButton;
    private ImageButton attachmentButton;
    private ListView chatListView;
    private DatabaseReference databaseRef;
    private String username;
    private String adminUsername = "uptd_ppajember21"; // Admin's username
    private ChatAdapter chatAdapter;
    private SharedPreferences sharedPreferences;

    private static final int PICK_IMAGE_REQUEST = 1;
    private Uri imageUrl; // Tambahkan variabel imageUrl

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_chat);
        getSupportActionBar().hide();

        // Mendapatkan referensi ImageView untuk header
        ImageView headerImageView = findViewById(R.id.headerImageView);
        headerImageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
                Toast.makeText(ChatActivity.this, "Chat tersimpan pada Data Konseling", Toast.LENGTH_SHORT).show();
            }
        });

        // Mendapatkan referensi UI lainnya
        messageInput = findViewById(R.id.message_input);
        sendButton = findViewById(R.id.send_button);
        attachmentButton = findViewById(R.id.attachment_button);
        chatListView = findViewById(R.id.chat_listview);

        // Mendapatkan username dari sharedPreferences
        sharedPreferences = getSharedPreferences("loginPrefs", MODE_PRIVATE);
        username = sharedPreferences.getString("username", null);

        // Mendapatkan KONSELING_ID dari intent
        String konselingID = getKonselingID();

        // Membuat DatabaseReference sesuai dengan KONSELING_ID
        if (konselingID != null) {
            databaseRef = FirebaseDatabase.getInstance().getReference("chats").child(konselingID);
        } else {
            // Handle the case when KONSELING_ID is not available
            // For example, display a message or go back to the previous activity
        }

        // Inisialisasi adapter untuk ListView chat
        ArrayList<ChatMessage> messageList = new ArrayList<>();
        chatAdapter = new ChatAdapter(this, messageList, username);
        chatListView.setAdapter(chatAdapter);

        // Listener untuk tombol kirim pesan
        sendButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                sendMessage();
            }
        });

        // Listener untuk tombol lampiran
        attachmentButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                openGallery();
            }
        });

        // Listener untuk tombol menu
        ImageView rightImageView = findViewById(R.id.rightImageView);
        rightImageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showEndSessionDialog();
            }
        });

        // ChildEventListener untuk mendengarkan perubahan pada database
        databaseRef.addChildEventListener(new ChildEventListener() {
            @Override
            public void onChildAdded(@NonNull DataSnapshot dataSnapshot, @Nullable String previousChildName) {
                ChatMessage chatMessage = dataSnapshot.getValue(ChatMessage.class);
                chatAdapter.add(chatMessage);
                chatAdapter.notifyDataSetChanged();
            }

            @Override
            public void onChildChanged(@NonNull DataSnapshot dataSnapshot, @Nullable String previousChildName) {}

            @Override
            public void onChildRemoved(@NonNull DataSnapshot dataSnapshot) {}

            @Override
            public void onChildMoved(@NonNull DataSnapshot dataSnapshot, @Nullable String previousChildName) {}

            @Override
            public void onCancelled(@NonNull DatabaseError databaseError) {}
        });
    }

    private void sendMessage() {
        String messageText = messageInput.getText().toString().trim();

        if (!messageText.isEmpty()) {
            String currentDate = getCurrentDateTime();
            String konselingID = getIntent().getStringExtra("KONSELING_ID");

            // Periksa apakah imageUrl sudah ada sebelum membuat ChatMessage
            if (imageUrl != null) {
                ChatMessage chatMessage = new ChatMessage(username, messageText, currentDate, konselingID, imageUrl.toString());
                databaseRef.push().setValue(chatMessage.toMap());
                imageUrl = null; // Setelah pengiriman pesan, reset imageUrl menjadi null
            } else {
                // Jika tidak ada imageUrl, buat ChatMessage tanpa imageUrl
                ChatMessage chatMessage = new ChatMessage(username, messageText, currentDate, konselingID, "");
                databaseRef.push().setValue(chatMessage.toMap());
            }

            messageInput.setText("");
        }
    }

    private void openGallery() {
        Intent intent = new Intent();
        intent.setType("image/*");
        intent.setAction(Intent.ACTION_GET_CONTENT);
        startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE_REQUEST);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) {
            Uri selectedImageUri = data.getData();
            uploadImageToDatabase(selectedImageUri);
        }
    }

    private void uploadImageToDatabase(Uri imageUri) {
        imageUrl = imageUri; // Tetapkan nilai imageUrl dengan Uri gambar yang dipilih
        String currentDate = getCurrentDateTime();
        String konselingID = getIntent().getStringExtra("KONSELING_ID");
        ChatMessage chatMessage = new ChatMessage(username, "", currentDate, konselingID, imageUrl.toString());

        databaseRef.push().setValue(chatMessage.toMap());
    }

    private void showEndSessionDialog() {
        Typeface poppins = ResourcesCompat.getFont(this, R.font.poppins_regular);
        int grey = ContextCompat.getColor(this, R.color.grey);

        TextView title = new TextView(this);
        title.setText("Konfirmasi");
        title.setPadding(20, 30, 20, 0);
        title.setGravity(Gravity.CENTER);
        title.setTextSize(16);
        title.setTypeface(poppins, Typeface.BOLD);
        title.setTextColor(grey);

        TextView message = new TextView(this);
        message.setText("Anda ingin mengakhiri sesi konseling ini?");
        message.setPadding(20, 20, 20, 30);
        message.setGravity(Gravity.CENTER);
        message.setTextSize(14);
        message.setTypeface(poppins);
        message.setTextColor(grey);

        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setCustomTitle(title);
        builder.setView(message);

        builder.setPositiveButton("Ya", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                // Perbarui status di Firebase
                String konselingID = getKonselingID();
                if (konselingID != null) {
                    DatabaseReference konselingRef = FirebaseDatabase.getInstance().getReference("konseling").child(konselingID);
                    konselingRef.child("status").setValue("ended");
                }
                finish();
            }
        });
        builder.setNegativeButton("Tidak", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        builder.create().show();
    }

    private String getCurrentDateTime() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault());
        return sdf.format(new Date());
    }

    private String getKonselingID() {
        return sharedPreferences.getString("KONSELING_ID", null);
    }
}
