package com.example.pap_teste;

import android.os.Bundle;
import android.text.TextUtils;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

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

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 java.util.HashMap;
import java.util.Map;

import android.net.Uri;
import android.content.Intent;
import android.widget.ImageView;
import com.bumptech.glide.Glide;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.StorageReference;
import java.util.UUID;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import android.widget.CheckBox;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.view.LayoutInflater;
import android.view.View;
import android.app.TimePickerDialog;
import java.util.ArrayList;
import java.util.List;
import com.example.pap_teste.models.ScheduleDay;

public class DefinicoesAdminActivity extends AppCompatActivity {

    private EditText inputRadius, inputAddress;
    private android.widget.Spinner spinnerCategory;
    private ImageView imgLogo;
    private DatabaseReference databaseReference;
    private String documentId;
    private String photoUrl;
    private ActivityResultLauncher<Intent> imagePickerLauncher;
    private String[] categories = {"Carnes", "Massas", "Sushi", "Pizzas", "Sobremesas", "Italiana", "Moderna"};
    private String[] dayNames = {"Domingo", "Segunda-feira", "Terça-feira", "Quarta-feira", "Quinta-feira", "Sexta-feira", "Sábado"};
    private String[] dayKeys = {"sunday", "monday", "tuesday", "wednesday", "thursday", "friday", "saturday"};
    private List<View> scheduleViews = new ArrayList<>();

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

        String email = getIntent().getStringExtra(MainActivity.EXTRA_EMAIL);
        if (email != null) {
            documentId = email.replace(".", "_").replace("@", "_at_");
        }

        databaseReference = FirebaseDatabase.getInstance().getReference().child("Restaurantes");

        inputRadius = findViewById(R.id.inputRadius);
        inputAddress = findViewById(R.id.inputAddress);
        spinnerCategory = findViewById(R.id.spinnerCategory);
        imgLogo = findViewById(R.id.imgRestaurantLogo);

        android.widget.ArrayAdapter<String> adapter = new android.widget.ArrayAdapter<>(this,
                android.R.layout.simple_spinner_item, categories);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinnerCategory.setAdapter(adapter);

        Button btnSave = findViewById(R.id.btnSaveSettings);
        Button btnBack = findViewById(R.id.btnVoltar);
        Button btnChangeLogo = findViewById(R.id.btnChangeLogo);

        if (btnBack != null) {
            btnBack.setOnClickListener(v -> finish());
        }

        imagePickerLauncher = registerForActivityResult(
                new ActivityResultContracts.StartActivityForResult(),
                result -> {
                    if (result.getResultCode() == RESULT_OK && result.getData() != null) {
                        Uri imageUri = result.getData().getData();
                        if (imageUri != null) {
                            uploadImageToFirebase(imageUri);
                        }
                    }
                });

        btnChangeLogo.setOnClickListener(v -> {
            String[] options = {"Galeria", "URL da Imagem"};
            new androidx.appcompat.app.AlertDialog.Builder(this)
                    .setTitle("Escolher Logótipo")
                    .setItems(options, (dialog, which) -> {
                        if (which == 0) {
                            Intent intent = new Intent(Intent.ACTION_PICK);
                            intent.setType("image/*");
                            imagePickerLauncher.launch(intent);
                        } else {
                            showUrlInputDialog();
                        }
                    }).show();
        });

        LinearLayout containerSchedule = findViewById(R.id.containerSchedule);
        LayoutInflater inflater = LayoutInflater.from(this);
        for (int i = 0; i < dayNames.length; i++) {
            View view = inflater.inflate(R.layout.item_schedule_day, containerSchedule, false);
            TextView tvDayName = view.findViewById(R.id.tvDayName);
            TextView tvOpenTime = view.findViewById(R.id.tvOpenTime);
            TextView tvCloseTime = view.findViewById(R.id.tvCloseTime);
            CheckBox cbClosed = view.findViewById(R.id.cbClosed);

            tvDayName.setText(dayNames[i]);
            
            tvOpenTime.setOnClickListener(v -> showTimePicker(tvOpenTime));
            tvCloseTime.setOnClickListener(v -> showTimePicker(tvCloseTime));
            
            cbClosed.setOnCheckedChangeListener((buttonView, isChecked) -> {
                tvOpenTime.setEnabled(!isChecked);
                tvCloseTime.setEnabled(!isChecked);
            });

            containerSchedule.addView(view);
            scheduleViews.add(view);
        }

        loadCurrentSettings();

        btnSave.setOnClickListener(v -> saveSettings());
    }

    private void showUrlInputDialog() {
        androidx.appcompat.app.AlertDialog.Builder builder = new androidx.appcompat.app.AlertDialog.Builder(this);
        builder.setTitle("Inserir URL da Imagem");

        final EditText input = new EditText(this);
        input.setInputType(android.text.InputType.TYPE_TEXT_VARIATION_URI);
        builder.setView(input);

        builder.setPositiveButton("Confirmar", (dialog, which) -> {
            String url = input.getText().toString().trim();
            if (!TextUtils.isEmpty(url)) {
                this.photoUrl = url;
                Glide.with(this).load(photoUrl).circleCrop().into(imgLogo);
                Toast.makeText(this, "Logótipo definido!", Toast.LENGTH_SHORT).show();
            }
        });
        builder.setNegativeButton("Cancelar", (dialog, which) -> dialog.cancel());
        builder.show();
    }

    private void showTimePicker(TextView targetTextView) {
        java.util.Calendar cal = java.util.Calendar.getInstance();
        new TimePickerDialog(this, (view, hourOfDay, minute) -> {
            targetTextView.setText(String.format(java.util.Locale.getDefault(), "%02d:%02d", hourOfDay, minute));
        }, cal.get(java.util.Calendar.HOUR_OF_DAY), cal.get(java.util.Calendar.MINUTE), true).show();
    }

    private void uploadImageToFirebase(Uri imageUri) {
        if (documentId == null) return;

        StorageReference storageRef = FirebaseStorage.getInstance().getReference()
                .child("restaurant_logos/" + UUID.randomUUID().toString());

        storageRef.putFile(imageUri).addOnSuccessListener(taskSnapshot -> {
            storageRef.getDownloadUrl().addOnSuccessListener(uri -> {
                photoUrl = uri.toString();
                Glide.with(this).load(photoUrl).circleCrop().into(imgLogo);
            });
        }).addOnFailureListener(e -> {
            Toast.makeText(this, "Falha no upload: " + e.getMessage(), Toast.LENGTH_LONG).show();
        });
    }

    private void loadCurrentSettings() {
        if (documentId == null)
            return;

        databaseReference.child(documentId).addListenerForSingleValueEvent(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot snapshot) {
                if (snapshot.exists()) {
                    if (snapshot.hasChild("securityDistance")) {
                        Object val = snapshot.child("securityDistance").getValue();
                        inputRadius.setText(val != null ? val.toString() : "");
                    }
                    if (snapshot.hasChild("address")) {
                        String addr = snapshot.child("address").getValue(String.class);
                        inputAddress.setText(addr != null ? addr : "");
                    }
                    if (snapshot.hasChild("category")) {
                        String cat = snapshot.child("category").getValue(String.class);
                        if (cat != null) {
                            for (int i = 0; i < categories.length; i++) {
                                if (categories[i].equalsIgnoreCase(cat)) {
                                    spinnerCategory.setSelection(i);
                                    break;
                                }
                            }
                        }
                    }
                    if (snapshot.hasChild("logoUrl")) {
                        photoUrl = snapshot.child("logoUrl").getValue(String.class);
                        if (photoUrl != null && !photoUrl.isEmpty()) {
                            Glide.with(DefinicoesAdminActivity.this).load(photoUrl).circleCrop().into(imgLogo);
                        }
                    }
                    if (snapshot.hasChild("schedule")) {
                        for (int i = 0; i < dayKeys.length; i++) {
                            DataSnapshot daySnapshot = snapshot.child("schedule").child(dayKeys[i]);
                            if (daySnapshot.exists()) {
                                ScheduleDay sd = daySnapshot.getValue(ScheduleDay.class);
                                if (sd != null) {
                                    View view = scheduleViews.get(i);
                                    CheckBox cbClosed = view.findViewById(R.id.cbClosed);
                                    TextView tvOpenTime = view.findViewById(R.id.tvOpenTime);
                                    TextView tvCloseTime = view.findViewById(R.id.tvCloseTime);
                                    
                                    cbClosed.setChecked(sd.isClosed());
                                    if (sd.getOpenTime() != null) tvOpenTime.setText(sd.getOpenTime());
                                    if (sd.getCloseTime() != null) tvCloseTime.setText(sd.getCloseTime());
                                    
                                    tvOpenTime.setEnabled(!sd.isClosed());
                                    tvCloseTime.setEnabled(!sd.isClosed());
                                }
                            }
                        }
                    }
                }
            }

            @Override
            public void onCancelled(@NonNull DatabaseError error) {
                Toast.makeText(DefinicoesAdminActivity.this, "Erro ao carregar definições.", Toast.LENGTH_SHORT).show();
            }
        });
    }

    private void saveSettings() {
        if (documentId == null)
            return;

        String radiusStr = inputRadius.getText().toString().trim();
        String addressStr = inputAddress.getText().toString().trim();
        String selectedCategory = spinnerCategory.getSelectedItem().toString();

        if (TextUtils.isEmpty(radiusStr) || TextUtils.isEmpty(addressStr)) {
            Toast.makeText(this, "Preencha todos os campos.", Toast.LENGTH_SHORT).show();
            return;
        }

        try {
            int radius = Integer.parseInt(radiusStr);

            Map<String, Object> updates = new HashMap<>();
            updates.put("securityDistance", radius);
            updates.put("address", addressStr);
            updates.put("category", selectedCategory);
            if (photoUrl != null) {
                 updates.put("logoUrl", photoUrl);
            }

            Map<String, ScheduleDay> scheduleMap = new HashMap<>();
            for (int i = 0; i < dayKeys.length; i++) {
                View view = scheduleViews.get(i);
                CheckBox cbClosed = view.findViewById(R.id.cbClosed);
                TextView tvOpenTime = view.findViewById(R.id.tvOpenTime);
                TextView tvCloseTime = view.findViewById(R.id.tvCloseTime);
                
                scheduleMap.put(dayKeys[i], new ScheduleDay(cbClosed.isChecked(), tvOpenTime.getText().toString(), tvCloseTime.getText().toString()));
            }
            updates.put("schedule", scheduleMap);

            databaseReference.child(documentId).updateChildren(updates)
                    .addOnSuccessListener(aVoid -> {
                        Toast.makeText(this, "Definições guardadas com sucesso!", Toast.LENGTH_SHORT).show();
                        finish();
                    })
                    .addOnFailureListener(
                            e -> Toast.makeText(this, "Falha ao guardar definições.", Toast.LENGTH_SHORT).show());

        } catch (NumberFormatException e) {
            Toast.makeText(this, "Raio inválido.", Toast.LENGTH_SHORT).show();
        }
    }
}
