package com.example.cuida.ui.sns24;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import com.google.ai.client.generativeai.GenerativeModel;
import com.google.ai.client.generativeai.java.GenerativeModelFutures;
import com.google.ai.client.generativeai.type.Content;
import com.google.ai.client.generativeai.type.GenerateContentResponse;
import com.google.common.util.concurrent.FutureCallback;
import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.ListenableFuture;

import java.util.concurrent.Executor;
import java.util.concurrent.Executors;

import com.example.cuida.databinding.FragmentSns24Binding;

public class Sns24Fragment extends Fragment {

    private FragmentSns24Binding binding;
    private GenerativeModelFutures model;
    private static final String API_KEY = "AIzaSyBmLgn-SHaTDvAeDWsw2iTZRR9gahhOu7k";

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container,
            @Nullable Bundle savedInstanceState) {
        binding = FragmentSns24Binding.inflate(inflater, container, false);
        return binding.getRoot();
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        // 1. Inicializar o Modelo Gemini
        // NOTA: Substitua "SUA_API_KEY" pela sua chave do Google AI Studio
        GenerativeModel gm = new GenerativeModel("gemini-2.5-flash", API_KEY);
        model = GenerativeModelFutures.from(gm);

        // 2. Botão Ligar SNS 24
        binding.buttonCallSns.setOnClickListener(v -> {
            Intent intent = new Intent(Intent.ACTION_DIAL);
            intent.setData(Uri.parse("tel:808242424"));
            startActivity(intent);
        });

        // 3. Botão Triagem IA
        binding.buttonAiTriage.setOnClickListener(v -> {
            String symptoms = binding.inputSymptoms.getText().toString().trim();
            if (!symptoms.isEmpty()) {
                analyzeSymptomsWithGemini(symptoms);
            } else {
                Toast.makeText(getContext(), "Por favor, descreva os seus sintomas.", Toast.LENGTH_SHORT).show();
            }
        });
    }

    private void analyzeSymptomsWithGemini(String symptoms) {
        // Feedback visual de carregamento
        binding.buttonAiTriage.setEnabled(false);
        binding.textAiResult.setVisibility(View.VISIBLE);
        binding.textAiResult.setText("A analisar sintomas com IA...");
        binding.buttonFindHospital.setVisibility(View.GONE);

        // Criar o prompt
        Content content = new Content.Builder()
                .addText("Atua como um assistente de triagem de saúde. O utilizador diz: \"" + symptoms + "\". " +
                        "Se a situação exigir avaliação médica imediata ou urgência, começa a resposta com 'URGENTE: HOSPITAL'. "
                        +
                        "Caso contrário, dá apenas o conselho habitual. " +
                        "Dá uma resposta curta (máximo 4 linhas). " +
                        "Aviso: Isto não substitui aconselhamento médico.")
                .build();

        // Executar chamada assíncrona (usando Guava Futures para Java)
        ListenableFuture<GenerateContentResponse> response = model.generateContent(content);

        // Executor para rodar a resposta na UI Thread
        // Creating a new single thread executor for the background work if needed,
        // but the callback needs to run on main thread or handle UI updates on main
        // thread.
        // We use ContextCompat.getMainExecutor to be safe on API < 28 (minSdk is 24)

        Futures.addCallback(response, new FutureCallback<GenerateContentResponse>() {
            @Override
            public void onSuccess(GenerateContentResponse result) {
                if (getActivity() != null) {
                    String text = result.getText();
                    binding.textAiResult.setText(text);
                    binding.buttonAiTriage.setEnabled(true);

                    if (text != null && text.contains("URGENTE: HOSPITAL")) {
                        binding.buttonFindHospital.setVisibility(View.VISIBLE);
                        binding.buttonFindHospital.setOnClickListener(v -> {
                            Uri gmmIntentUri = Uri.parse("geo:0,0?q=hospital");
                            Intent mapIntent = new Intent(Intent.ACTION_VIEW, gmmIntentUri);
                            mapIntent.setPackage("com.google.android.apps.maps");
                            startActivity(mapIntent);
                        });
                    }
                }
            }

            @Override
            public void onFailure(Throwable t) {
                if (getActivity() != null) {
                    binding.textAiResult.setText("Erro ao contactar a IA: " + t.getMessage());
                    binding.buttonAiTriage.setEnabled(true);
                }
            }
        }, androidx.core.content.ContextCompat.getMainExecutor(requireContext()));
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        binding = null;
    }
}
