package com.example.pap_findu.adapters;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.example.pap_findu.R;
import com.example.pap_findu.models.AlertMessage;
import com.google.firebase.auth.FirebaseAuth; // ADICIONADO
import com.google.firebase.auth.FirebaseUser; // ADICIONADO
import com.google.firebase.firestore.FirebaseFirestore;

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

public class AlertsAdapter extends RecyclerView.Adapter<AlertsAdapter.AlertViewHolder> {

    private List<AlertMessage> alertsList = new ArrayList<>();
    private Context context;
    private SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy HH:mm", Locale.getDefault());

    public AlertsAdapter(Context context) {
        this.context = context;
    }

    public void setAlertsList(List<AlertMessage> alertsList) {
        this.alertsList = alertsList;
        notifyDataSetChanged();
    }

    @NonNull
    @Override
    public AlertViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(context).inflate(R.layout.item_alert, parent, false);
        return new AlertViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull AlertViewHolder holder, int position) {
        AlertMessage alert = alertsList.get(position);

        holder.tvAlertTitle.setText(alert.getTitle() != null ? alert.getTitle() : "");
        holder.tvAlertMessage.setText(alert.getMessage() != null ? alert.getMessage() : "");

        if (alert.getTimestamp() != null) {
            holder.tvAlertDate.setText(sdf.format(alert.getTimestamp()));
        } else {
            holder.tvAlertDate.setText("");
        }

        // VERIFICAÇÃO DE QUEM ESTÁ LOGADO
        FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
        boolean isParent = (user != null && !user.isAnonymous());

        if ("RESOLVED".equalsIgnoreCase(alert.getStatus())) {
            holder.flAlertIconBg.setBackgroundResource(R.drawable.bg_alert_icon_info);
            holder.ivAlertIcon.setImageResource(android.R.drawable.ic_dialog_info);
            holder.ivAlertIcon.setColorFilter(Color.parseColor("#1F6AEF"));

            holder.tvAlertStatus.setBackgroundResource(R.drawable.bg_chip_success);
            holder.tvAlertStatus.setText("Resolvido");
            holder.tvAlertStatus.setTextColor(Color.parseColor("#0F7A45"));

            holder.llAlertActions.setVisibility(View.GONE);
        } else {
            holder.flAlertIconBg.setBackgroundResource(R.drawable.bg_alert_icon_warning);
            holder.ivAlertIcon.setImageResource(R.drawable.ic_alert_warning);
            holder.ivAlertIcon.setColorFilter(null);

            holder.tvAlertStatus.setBackgroundResource(R.drawable.bg_chip_warning);
            holder.tvAlertStatus.setText("Urgente");
            holder.tvAlertStatus.setTextColor(Color.parseColor("#B45309"));

            // LOGICA DE SEGURANÇA: Só mostra os botões de ação se for o PAI
            if (isParent) {
                holder.llAlertActions.setVisibility(View.VISIBLE);
            } else {
                holder.llAlertActions.setVisibility(View.GONE);
            }
        }

        holder.btnContactar.setOnClickListener(v -> {
            Intent intent = new Intent(Intent.ACTION_DIAL);
            v.getContext().startActivity(intent);
        });

        holder.btnResolver.setOnClickListener(v -> {
            // DUPLA SEGURANÇA: Verifica novamente no clique
            if (isParent && alert.getId() != null) {
                FirebaseFirestore.getInstance().collection("Alerts").document(alert.getId())
                        .update("status", "RESOLVED")
                        .addOnSuccessListener(aVoid -> Toast.makeText(context, "Alerta resolvido!", Toast.LENGTH_SHORT).show());
            } else if (!isParent) {
                Toast.makeText(context, "Apenas os pais podem resolver alertas.", Toast.LENGTH_SHORT).show();
            }
        });
    }

    @Override
    public int getItemCount() {
        return alertsList.size();
    }

    static class AlertViewHolder extends RecyclerView.ViewHolder {
        FrameLayout flAlertIconBg;
        ImageView ivAlertIcon;
        TextView tvAlertTitle, tvAlertMessage, tvAlertStatus, tvAlertDate;
        LinearLayout llAlertActions;
        TextView btnContactar, btnResolver;

        public AlertViewHolder(@NonNull View itemView) {
            super(itemView);
            flAlertIconBg = itemView.findViewById(R.id.flAlertIconBg);
            ivAlertIcon = itemView.findViewById(R.id.ivAlertIcon);
            tvAlertTitle = itemView.findViewById(R.id.tvAlertTitle);
            tvAlertMessage = itemView.findViewById(R.id.tvAlertMessage);
            tvAlertStatus = itemView.findViewById(R.id.tvAlertStatus);
            tvAlertDate = itemView.findViewById(R.id.tvAlertDate);
            llAlertActions = itemView.findViewById(R.id.llAlertActions);
            btnContactar = itemView.findViewById(R.id.btnContactar);
            btnResolver = itemView.findViewById(R.id.btnResolver);
        }
    }
}