package com.example.sms_call_sync;

import android.Manifest;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import java.util.ArrayList; // ADDED: Import for ArrayList

public class MainActivity extends AppCompatActivity {

    private static final int PERMISSION_REQUEST_CODE = 100;

    private EditText etServerUrl;
    private EditText etPhoneName;
    private Button btnSyncSms;
    private Button btnSyncCalls;
    private Button btnAutoSync;
    private Button btnSettings;

    private SyncManager syncManager;

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

        initViews();
        syncManager = new SyncManager(this); // Initialize SyncManager

        loadSavedPreferences();
        setupListeners();
        initializeAutoSyncButton();

        // Request permissions when the activity is created
        checkAndRequestPermissions();
    }

    private void initViews() {
        etServerUrl = findViewById(R.id.et_server_url);
        etPhoneName = findViewById(R.id.et_phone_name);
        btnSyncSms = findViewById(R.id.btn_sync_sms);
        btnSyncCalls = findViewById(R.id.btn_sync_calls);
        btnAutoSync = findViewById(R.id.btn_auto_sync);
        btnSettings = findViewById(R.id.btn_settings);
    }

    private void loadSavedPreferences() {
        SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
        String savedServerUrl = sharedPreferences.getString("server_url", "");
        String savedPhoneName = sharedPreferences.getString("phone_name", "");

        etServerUrl.setText(savedServerUrl);
        etPhoneName.setText(savedPhoneName);
    }

    private void savePreferences() {
        SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.putString("server_url", etServerUrl.getText().toString());
        editor.putString("phone_name", etPhoneName.getText().toString());
        editor.apply();
    }

    private void initializeAutoSyncButton() {
        SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
        boolean isAutoSyncEnabled = sharedPreferences.getBoolean("auto_sync_enabled", false);
        
        if (isAutoSyncEnabled) {
            btnAutoSync.setText("Auto Sync ON");
            btnAutoSync.setBackgroundColor(getResources().getColor(android.R.color.holo_green_dark));
            // Start the service if auto sync was enabled
            startAutoSyncService();
        } else {
            btnAutoSync.setText("Auto Sync OFF");
            btnAutoSync.setBackgroundColor(getResources().getColor(android.R.color.holo_blue_dark));
        }
    }

    private void setupListeners() {
        btnSyncSms.setOnClickListener(v -> syncSms());
        btnSyncCalls.setOnClickListener(v -> syncCallHistory());
        btnAutoSync.setOnClickListener(v -> toggleAutoSync());
        btnSettings.setOnClickListener(v -> openSettings());
    }

    private void syncSms() {
        savePreferences(); // Save current inputs before syncing
        String serverUrl = etServerUrl.getText().toString();
        String phoneName = etPhoneName.getText().toString();

        if (serverUrl.isEmpty() || phoneName.isEmpty()) {
            Toast.makeText(this, "Please enter Server URL and Phone Name", Toast.LENGTH_SHORT).show();
            return;
        }

        // Check for READ_SMS permission before syncing
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_SMS) != PackageManager.PERMISSION_GRANTED) {
            Toast.makeText(this, "READ_SMS permission is required to sync SMS.", Toast.LENGTH_LONG).show();
            checkAndRequestPermissions(); // Request again if not granted
            return;
        }

        Toast.makeText(this, "Syncing SMS...", Toast.LENGTH_SHORT).show();
        syncManager.syncSms(serverUrl, phoneName);
    }

    private void syncCallHistory() {
        savePreferences(); // Save current inputs before syncing
        String serverUrl = etServerUrl.getText().toString();
        String phoneName = etPhoneName.getText().toString();

        if (serverUrl.isEmpty() || phoneName.isEmpty()) {
            Toast.makeText(this, "Please enter Server URL and Phone Name", Toast.LENGTH_SHORT).show();
            return;
        }

        // Check for READ_CALL_LOG permission before syncing
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_CALL_LOG) != PackageManager.PERMISSION_GRANTED) {
            Toast.makeText(this, "READ_CALL_LOG permission is required to sync Call History.", Toast.LENGTH_LONG).show();
            checkAndRequestPermissions(); // Request again if not granted
            return;
        }

        Toast.makeText(this, "Syncing Call History...", Toast.LENGTH_SHORT).show();
        syncManager.syncCallHistory(serverUrl, phoneName);
    }

    private void toggleAutoSync() {
        SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
        boolean isAutoSyncEnabled = sharedPreferences.getBoolean("auto_sync_enabled", false);
        
        // Toggle the state
        isAutoSyncEnabled = !isAutoSyncEnabled;
        
        // Save the new state
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.putBoolean("auto_sync_enabled", isAutoSyncEnabled);
        editor.apply();
        
        // Get server URL and phone name for backend update
        String serverUrl = etServerUrl.getText().toString();
        String phoneName = etPhoneName.getText().toString();
        
        if (isAutoSyncEnabled) {
            // Enable auto sync
            btnAutoSync.setText("Auto Sync ON");
            btnAutoSync.setBackgroundColor(getResources().getColor(android.R.color.holo_green_dark));
            
            // Update backend status
            if (!serverUrl.isEmpty() && !phoneName.isEmpty()) {
                syncManager.updateAutoSyncStatus(serverUrl, phoneName, true, 30);
            }
            
            // Start the background service
            startAutoSyncService();
            Toast.makeText(this, "Auto Sync Enabled - Background service started", Toast.LENGTH_LONG).show();
        } else {
            // Disable auto sync
            btnAutoSync.setText("Auto Sync OFF");
            btnAutoSync.setBackgroundColor(getResources().getColor(android.R.color.holo_blue_dark));
            
            // Update backend status
            if (!serverUrl.isEmpty() && !phoneName.isEmpty()) {
                syncManager.updateAutoSyncStatus(serverUrl, phoneName, false, 30);
            }
            
            // Stop the background service
            stopAutoSyncService();
            Toast.makeText(this, "Auto Sync Disabled - Background service stopped", Toast.LENGTH_SHORT).show();
        }
    }
    
    private void startAutoSyncService() {
        Intent serviceIntent = new Intent(this, AutoSyncService.class);
        startForegroundService(serviceIntent);
    }
    
    private void stopAutoSyncService() {
        Intent serviceIntent = new Intent(this, AutoSyncService.class);
        stopService(serviceIntent);
    }

    private void openSettings() {
        Intent intent = new Intent(MainActivity.this, SettingsActivity.class);
        startActivity(intent);
    }

    // --- Permission Handling ---
    private void checkAndRequestPermissions() {
        String[] permissions = {
                Manifest.permission.READ_SMS,
                Manifest.permission.RECEIVE_SMS,
                Manifest.permission.READ_CALL_LOG,
                Manifest.permission.INTERNET,
                Manifest.permission.ACCESS_FINE_LOCATION, // Include if you intend to use location
                Manifest.permission.ACCESS_COARSE_LOCATION // Include if you intend to use location
        };

        // Filter out permissions that are already granted
        // Note: INTERNET permission is a "normal" permission and does not require runtime request
        // It's checked here for completeness but will always be granted if declared in manifest.
        // ACCESS_FINE_LOCATION and ACCESS_COARSE_LOCATION are "dangerous" and need runtime request.
        // READ_SMS, RECEIVE_SMS, READ_CALL_LOG are "dangerous" and need runtime request.
        ArrayList<String> permissionsToRequest = new ArrayList<>();
        for (String permission : permissions) {
            if (ContextCompat.checkSelfPermission(this, permission) != PackageManager.PERMISSION_GRANTED) {
                permissionsToRequest.add(permission);
            }
        }

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

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == PERMISSION_REQUEST_CODE) {
            boolean allPermissionsGranted = true;
            for (int result : grantResults) {
                if (result != PackageManager.PERMISSION_GRANTED) {
                    allPermissionsGranted = false;
                    break;
                }
            }

            if (allPermissionsGranted) {
                Toast.makeText(this, "All required permissions granted!", Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(this, "Some permissions were denied. App functionality may be limited.", Toast.LENGTH_LONG).show();
            }
        }
    }
}
