package com.example.pap_teste;

import com.example.pap_teste.models.Mesa;
import com.example.pap_teste.models.Staff;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
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 com.google.firebase.database.ValueEventListener;
import androidx.annotation.NonNull;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;

import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

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

public class GestaoStaffActivity extends AppCompatActivity {

    private final List<Staff> staffList = new ArrayList<>();
    private ArrayAdapter<String> staffAdapter;
    private ListView listStaffMesas;

    private Spinner spinnerNomeStaff;
    private Spinner spinnerMesaStaff;
    private TextView txtMensagemStaff;

    private DatabaseReference staffRef;
    private DatabaseReference mesasRef;

    private List<String> staffNames = new ArrayList<>();
    private List<Mesa> mesasDisponiveis = new ArrayList<>();
    private ArrayAdapter<String> staffNameAdapter;
    private ArrayAdapter<String> mesaSpinnerAdapter;

    private FloatingActionButton floatingActionButton;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_gestao_staff);
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.gestaoStaffRoot), (v, insets) -> {
            Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
            return insets;
        });

        staffRef = FirebaseDatabase.getInstance().getReference("Staff");
        mesasRef = FirebaseDatabase.getInstance().getReference("Mesas");

        Button back = findViewById(R.id.btnVoltar);
        if (back != null) {
            back.setOnClickListener(v -> finish());
        }

        bindViews();
        setupMesaSpinner();
        setupList();
        setupFormActions();
    }

    private void bindViews() {
        listStaffMesas = findViewById(R.id.listStaffMesas);
        spinnerNomeStaff = findViewById(R.id.spinnerNomeStaff);
        spinnerMesaStaff = findViewById(R.id.spinnerMesaStaff);
        txtMensagemStaff = findViewById(R.id.txtMensagemStaff);
        floatingActionButton = findViewById(R.id.floatingActionButton);
    }

    /**
     * Preenche o spinner com uma lista simples de mesas (1–20).
     * Mais tarde isto pode ser ligado às mesas reais configuradas em "Gerir Mesas".
     */
    private void setupMesaSpinner() {
        mesaSpinnerAdapter = new ArrayAdapter<>(
                this,
                android.R.layout.simple_spinner_dropdown_item);

        staffNameAdapter = new ArrayAdapter<>(
                this,
                android.R.layout.simple_spinner_dropdown_item,
                staffNames);
        spinnerNomeStaff.setAdapter(staffNameAdapter);

        loadStaffMembers();
        loadMesas();

        spinnerMesaStaff.setAdapter(mesaSpinnerAdapter);
    }

    private void loadMesas() {
        mesasRef.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot snapshot) {
                mesasDisponiveis.clear();
                mesaSpinnerAdapter.clear();
                for (DataSnapshot postSnapshot : snapshot.getChildren()) {
                    Mesa mesa = postSnapshot.getValue(Mesa.class);
                    if (mesa != null) {
                        mesasDisponiveis.add(mesa);
                        mesaSpinnerAdapter.add("Mesa " + mesa.getNumero());
                    }
                }
                mesaSpinnerAdapter.notifyDataSetChanged();
            }

            @Override
            public void onCancelled(@NonNull DatabaseError error) {
                Toast.makeText(GestaoStaffActivity.this, "Erro ao carregar mesas.", Toast.LENGTH_SHORT).show();
            }
        });
    }

    private void setupList() {
        staffAdapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_activated_1);
        listStaffMesas.setAdapter(staffAdapter);

        listStaffMesas.setOnItemClickListener((parent, view, position, id) -> {
            Staff item = staffList.get(position);
            // Select staff in spinner
            int staffIndex = staffNames.indexOf(item.getName());
            if (staffIndex >= 0) {
                spinnerNomeStaff.setSelection(staffIndex);
            }
            // Select mesa in spinner
            // Simple string matching for now since Mesa is stored as String in Staff
            String assignedMesa = item.getMesa();
            if (assignedMesa != null) {
                for (int i = 0; i < mesaSpinnerAdapter.getCount(); i++) {
                    if (mesaSpinnerAdapter.getItem(i).equals(assignedMesa)) {
                        spinnerMesaStaff.setSelection(i);
                        break;
                    }
                }
            }

            txtMensagemStaff.setText(String.format("A editar: %s", item.getName()));
        });
    }

    private void setupFormActions() {
        Button btnAtribuir = findViewById(R.id.btnAtribuirStaff);
        if (btnAtribuir != null) {
            btnAtribuir.setOnClickListener(v -> guardarAtribuicao());
        }

        Button btnEliminar = findViewById(R.id.btnEliminarStaff);
        if (btnEliminar != null) {
            btnEliminar.setOnClickListener(v -> eliminarStaff());
        }

        if (floatingActionButton != null) {
            floatingActionButton.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(GestaoStaffActivity.this, AddStaffActivity.class);
                    startActivity(intent);
                }
            });
        }

        Button btnGerirMesas = findViewById(R.id.btnGerirMesasStaff);
        if (btnGerirMesas != null) {
            btnGerirMesas.setOnClickListener(v -> {
                Intent intent = new Intent(GestaoStaffActivity.this, GerirMesasActivity.class);
                startActivity(intent);
            });
        }
    }

    private void guardarAtribuicao() {
        String nome = "";
        if (spinnerNomeStaff.getSelectedItem() != null) {
            nome = spinnerNomeStaff.getSelectedItem().toString();
        }

        if (nome.isEmpty()) {
            Toast.makeText(this, "Selecione um funcionário.", Toast.LENGTH_SHORT).show();
            return;
        }

        if (spinnerMesaStaff == null || spinnerMesaStaff.getSelectedItem() == null) {
            Toast.makeText(this, "Selecione uma mesa.", Toast.LENGTH_SHORT).show();
            return;
        }

        String mesaSelecionada = spinnerMesaStaff.getSelectedItem().toString();

        Staff staffToUpdate = findByNome(nome);
        if (staffToUpdate != null) {
            staffToUpdate.setMesa(mesaSelecionada);

            final String finalNome = nome;
            final String finalMesa = mesaSelecionada;

            staffRef.child(staffToUpdate.getId()).setValue(staffToUpdate)
                    .addOnSuccessListener(aVoid -> {
                        txtMensagemStaff.setText(String.format("%s atribuído à %s.", finalNome, finalMesa));
                    })
                    .addOnFailureListener(e -> {
                        Toast.makeText(this, "Erro ao atualizar: " + e.getMessage(), Toast.LENGTH_SHORT).show();
                    });
        } else {
            Toast.makeText(this, "Erro: Staff não encontrado.", Toast.LENGTH_SHORT).show();
        }
    }

    private void eliminarStaff() {
        String nome = "";
        if (spinnerNomeStaff.getSelectedItem() != null) {
            nome = spinnerNomeStaff.getSelectedItem().toString();
        }

        if (nome.isEmpty()) {
            Toast.makeText(this, "Selecione um funcionário primeiro.", Toast.LENGTH_SHORT).show();
            return;
        }

        Staff staffToDelete = findByNome(nome);
        if (staffToDelete != null) {
            new androidx.appcompat.app.AlertDialog.Builder(this)
                .setTitle("Eliminar Staff")
                .setMessage("Tem a certeza que deseja eliminar o funcionário " + staffToDelete.getName() + "?")
                .setPositiveButton("Eliminar", (dialog, which) -> {
                    staffRef.child(staffToDelete.getId()).removeValue()
                        .addOnSuccessListener(aVoid -> {
                            txtMensagemStaff.setText(staffToDelete.getName() + " foi eliminado.");
                        })
                        .addOnFailureListener(e -> {
                            Toast.makeText(this, "Erro ao eliminar: " + e.getMessage(), Toast.LENGTH_SHORT).show();
                        });
                })
                .setNegativeButton("Cancelar", null)
                .show();
        } else {
            Toast.makeText(this, "Staff não encontrado.", Toast.LENGTH_SHORT).show();
        }
    }

    private Staff findByNome(String nome) {
        for (Staff item : staffList) {
            if (item.getName().equalsIgnoreCase(nome)) {
                return item;
            }
        }
        return null;
    }

    private void loadStaffMembers() {
        staffRef.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot snapshot) {
                staffList.clear();
                staffNames.clear();
                staffAdapter.clear();

                for (DataSnapshot postSnapshot : snapshot.getChildren()) {
                    Staff staff = postSnapshot.getValue(Staff.class);
                    if (staff != null && staff.getName() != null) {
                        staffList.add(staff);
                        staffNames.add(staff.getName());

                        String mesaInfo = staff.getMesa() != null ? staff.getMesa() : "Sem Mesa";
                        String resumo = String.format("%s • %s • %s", staff.getName(), staff.getZona(), mesaInfo);
                        staffAdapter.add(resumo);
                    }
                }

                staffNameAdapter.notifyDataSetChanged();
                staffAdapter.notifyDataSetChanged();
            }

            @Override
            public void onCancelled(@NonNull DatabaseError error) {
                Toast.makeText(GestaoStaffActivity.this, "Erro ao carregar staff.", Toast.LENGTH_SHORT).show();
            }
        });
    }
}