package com.example.bem;

import android.os.Bundle;
import android.os.CountDownTimer;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.firestore.FirebaseFirestore;

import java.util.HashMap;
import java.util.Map;
import java.util.Random;

public class GenerateCodeActivity extends AppCompatActivity {

    private FirebaseFirestore db;
    private FirebaseAuth mAuth;

    private TextView textCode;
    private TextView textTimer;
    private Button btnGenerate;
    private ProgressBar progressBar;

    private CountDownTimer countDownTimer;

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

        db = FirebaseFirestore.getInstance();
        mAuth = FirebaseAuth.getInstance();

        textCode = findViewById(R.id.text_code);
        textTimer = findViewById(R.id.text_timer);
        btnGenerate = findViewById(R.id.btn_generate_code);
        progressBar = findViewById(R.id.progress_bar);

        btnGenerate.setOnClickListener(v -> generateCode());

        generateCode();
    }

    private void generateCode() {
        setLoading(true);

        String userId = mAuth.getCurrentUser().getUid();
        if (userId == null) {
            Toast.makeText(this, "Erro: Utilizador não autenticado.", Toast.LENGTH_SHORT).show();
            setLoading(false);
            return;
        }

        String code = String.format("%06d", new Random().nextInt(1000000));

        Map<String, Object> codeData = new HashMap<>();
        codeData.put("userId", userId);
        codeData.put("createdAt", System.currentTimeMillis());

        db.collection("inviteCodes").document(code)
                .set(codeData)
                .addOnSuccessListener(aVoid -> {
                    textCode.setText(code);
                    startTimer();
                    setLoading(false);
                })
                .addOnFailureListener(e -> {
                    Toast.makeText(GenerateCodeActivity.this, "Falha ao gerar o código.", Toast.LENGTH_SHORT).show();
                    setLoading(false);
                });
    }

    private void startTimer() {
        if (countDownTimer != null) {
            countDownTimer.cancel();
        }

        countDownTimer = new CountDownTimer(30000, 1000) {
            @Override
            public void onTick(long millisUntilFinished) {
                textTimer.setText(String.format("Expira em %d segundos", millisUntilFinished / 1000));
            }

            @Override
            public void onFinish() {
                textTimer.setText("Código expirado");
                textCode.setText("------");
            }
        }.start();
    }

    private void setLoading(boolean isLoading) {
        if (isLoading) {
            progressBar.setVisibility(View.VISIBLE);
            btnGenerate.setEnabled(false);
        } else {
            progressBar.setVisibility(View.GONE);
            btnGenerate.setEnabled(true);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (countDownTimer != null) {
            countDownTimer.cancel();
        }
    }
}
