package com.hs.sosnow;

import android.Manifest;
import android.animation.ValueAnimator;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.view.MotionEvent;
import android.view.View;
import android.view.animation.DecelerateInterpolator;
import android.view.animation.LinearInterpolator;
import android.view.animation.OvershootInterpolator;
import android.widget.ImageButton;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.PopupMenu;
import androidx.cardview.widget.CardView;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import com.google.android.material.progressindicator.CircularProgressIndicator;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {

    private static final int PERMISSION_REQ_CODE = 201;

    private TextView tvStatus, tvSosLabel;
    private CardView cardSosWrapper;
    private RelativeLayout btnSos;
    private View btnCancelTimer;
    private CircularProgressIndicator circularTimerProgress;

    private SharedPreferences prefs;
    private final Gson gson = new Gson();

    private CountDownTimer triggerTimer;
    private ValueAnimator progressAnimator;
    private boolean isTimerRunning = false;
    private SosHelper sosHelper;

    @SuppressLint("ClickableViewAccessibility")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        prefs = getSharedPreferences("SosNowPrefs", Context.MODE_PRIVATE);
        sosHelper = new SosHelper(this);

        tvStatus = findViewById(R.id.tvStatus);
        tvSosLabel = findViewById(R.id.tvSosLabel);
        cardSosWrapper = findViewById(R.id.cardSosWrapper);
        btnSos = findViewById(R.id.btnSos);
        btnCancelTimer = findViewById(R.id.btnCancelTimer);
        circularTimerProgress = findViewById(R.id.circularTimerProgress);

        ImageButton btnMenuDots = findViewById(R.id.btnMenuDots);
        ImageButton btnSettings = findViewById(R.id.btnSettings);

        btnMenuDots.setOnClickListener(this::showAboutMenu);
        btnSettings.setOnClickListener(v -> startActivity(new Intent(this, SettingsActivity.class)));
        btnCancelTimer.setOnClickListener(v -> abortCountdown(true));

        // 3D Press Motion for SOS Button
        btnSos.setOnTouchListener((v, event) -> {
            switch (event.getAction()) {
                case MotionEvent.ACTION_DOWN:
                    cardSosWrapper.animate()
                            .scaleX(0.90f)
                            .scaleY(0.90f)
                            .translationZ(-12f)
                            .setDuration(100)
                            .setInterpolator(new DecelerateInterpolator())
                            .start();
                    return true;

                case MotionEvent.ACTION_UP:
                    cardSosWrapper.animate()
                            .scaleX(1.0f)
                            .scaleY(1.0f)
                            .translationZ(0f)
                            .setDuration(260)
                            .setInterpolator(new OvershootInterpolator(3.0f))
                            .start();
                    startSosSequence();
                    return true;

                case MotionEvent.ACTION_CANCEL:
                    cardSosWrapper.animate()
                            .scaleX(1.0f)
                            .scaleY(1.0f)
                            .translationZ(0f)
                            .setDuration(150)
                            .start();
                    return true;
            }
            return false;
        });

        checkAndRequestPermissions();
        safeStartPowerTriggerService();
    }

    private void showAboutMenu(View anchor) {
        PopupMenu popup = new PopupMenu(this, anchor);
        popup.getMenu().add(0, 1, 0, "About");
        popup.setOnMenuItemClickListener(item -> {
            if (item.getItemId() == 1) {
                startActivity(new Intent(this, AboutActivity.class));
                return true;
            }
            return false;
        });
        popup.show();
    }

    private void safeStartPowerTriggerService() {
        try {
            Intent serviceIntent = new Intent(this, PowerButtonService.class);
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                startForegroundService(serviceIntent);
            } else {
                startService(serviceIntent);
            }
        } catch (Exception ignored) {}
    }

    private void startSosSequence() {
        if (isTimerRunning) return;

        List<String> callList = getList("CALL_CONTACTS");
        if (callList.isEmpty()) {
            Toast.makeText(this, "Please configure emergency contacts in Settings first!", Toast.LENGTH_LONG).show();
            startActivity(new Intent(this, SettingsActivity.class));
            return;
        }

        int delaySec = prefs.getInt("TRIGGER_DELAY", 2);
        if (delaySec == 0) {
            executeEmergencyProtocol();
            return;
        }

        isTimerRunning = true;
        btnCancelTimer.setVisibility(View.VISIBLE);
        circularTimerProgress.setVisibility(View.VISIBLE);
        circularTimerProgress.setMax(100);
        circularTimerProgress.setProgress(0);

        progressAnimator = ValueAnimator.ofInt(0, 100);
        progressAnimator.setDuration(delaySec * 1000L);
        progressAnimator.setInterpolator(new LinearInterpolator());
        progressAnimator.addUpdateListener(anim -> circularTimerProgress.setProgress((int) anim.getAnimatedValue()));
        progressAnimator.start();

        triggerTimer = new CountDownTimer(delaySec * 1000L, 100) {
            @Override
            public void onTick(long millisUntilFinished) {
                int sec = (int) Math.ceil(millisUntilFinished / 1000.0);
                tvSosLabel.setText(String.valueOf(sec));
                tvStatus.setText("Triggering SOS in " + sec + "s...");
            }

            @Override
            public void onFinish() {
                abortCountdown(false);
                executeEmergencyProtocol();
            }
        }.start();
    }

    private void abortCountdown(boolean isManualCancel) {
        if (triggerTimer != null) triggerTimer.cancel();
        if (progressAnimator != null) progressAnimator.cancel();
        isTimerRunning = false;
        tvSosLabel.setText("SOS");
        btnCancelTimer.setVisibility(View.GONE);
        circularTimerProgress.setVisibility(View.INVISIBLE);
        tvStatus.setText("Protection Active • Ready for Dispatch");

        if (isManualCancel) {
            Toast.makeText(this, "SOS Alert Aborted", Toast.LENGTH_SHORT).show();
        }
    }

    private void executeEmergencyProtocol() {
        tvStatus.setText("Emergency Protocol In Flight...");
        sosHelper.executeEmergency();
    }

    private List<String> getList(String key) {
        String json = prefs.getString(key, null);
        if (json != null) {
            Type type = new TypeToken<ArrayList<String>>() {}.getType();
            return gson.fromJson(json, type);
        }
        return new ArrayList<>();
    }

    private void checkAndRequestPermissions() {
        ArrayList<String> perms = new ArrayList<>();
        perms.add(Manifest.permission.SEND_SMS);
        perms.add(Manifest.permission.CALL_PHONE);
        perms.add(Manifest.permission.READ_PHONE_STATE);
        perms.add(Manifest.permission.ACCESS_FINE_LOCATION);
        perms.add(Manifest.permission.ACCESS_COARSE_LOCATION);
        perms.add(Manifest.permission.RECORD_AUDIO);
        perms.add(Manifest.permission.CAMERA);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            perms.add(Manifest.permission.POST_NOTIFICATIONS);
        }

        List<String> missing = new ArrayList<>();
        for (String perm : perms) {
            if (ContextCompat.checkSelfPermission(this, perm) != PackageManager.PERMISSION_GRANTED) {
                missing.add(perm);
            }
        }

        if (!missing.isEmpty()) {
            ActivityCompat.requestPermissions(this, missing.toArray(new String[0]), PERMISSION_REQ_CODE);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == PERMISSION_REQ_CODE) {
            boolean allGranted = true;
            for (int res : grantResults) {
                if (res != PackageManager.PERMISSION_GRANTED) {
                    allGranted = false;
                    break;
                }
            }
            if (!allGranted) {
                Toast.makeText(this, "Emergency automated features require all permissions!", Toast.LENGTH_SHORT).show();
            }
        }
    }
}