package com.example.weighttracker;

import android.content.pm.PackageManager;
import android.os.Bundle;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.google.android.material.textfield.TextInputEditText;

import java.util.List;

// This activity controls the main weight tracking screen.
public class WeightLogActivity extends AppCompatActivity {

    private DatabaseHelper db;
    private WeightAdapter adapter;
    private TextView progressSummaryText;

    // Null means add mode. A real ID means edit mode.
    private Integer selectedId = null;

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

        // Main database connection for this screen.
        db = new DatabaseHelper(this);

        // Weight entry UI.
        RecyclerView recyclerView = findViewById(R.id.weightRecyclerView);
        TextInputEditText dateInput = findViewById(R.id.dateInput);
        TextInputEditText weightInput = findViewById(R.id.weightInput);
        Button addButton = findViewById(R.id.addEntryButton);

        // Goal weight UI.
        TextInputEditText goalInput = findViewById(R.id.goalInput);
        Button setGoalButton = findViewById(R.id.setGoalButton);

        // Progress summary UI for the algorithms and data structures enhancement.
        progressSummaryText = findViewById(R.id.progressSummaryText);

        // RecyclerView setup.
        recyclerView.setLayoutManager(new LinearLayoutManager(this));

        // Default form state.
        selectedId = null;
        addButton.setText("Add Entry");

        // SMS permission is handled by a helper so this activity stays cleaner.
        SmsHelper.checkSmsPermission(this);

        // I broke these setup sections into smaller methods so this activity is easier to follow.
        setupGoalButton(goalInput, setGoalButton);
        setupWeightAdapter(recyclerView, dateInput, weightInput, addButton);
        setupAddButton(dateInput, weightInput, addButton);

        // Loads the current list and calculates the starting summary.
        refreshList();
    }

    // Handles the goal weight save button.
    private void setupGoalButton(TextInputEditText goalInput, Button setGoalButton) {
        setGoalButton.setOnClickListener(v -> {
            String goalText = InputHelper.getText(goalInput);

            if (goalText.isEmpty()) {
                Toast.makeText(this, "Enter a goal weight", Toast.LENGTH_SHORT).show();
                return;
            }

            Double goal = InputHelper.parseDouble(goalText);

            if (goal == null) {
                Toast.makeText(this, "Goal must be a number", Toast.LENGTH_SHORT).show();
                return;
            }

            db.setGoalWeight(goal);
            goalInput.setText("");

            // Recalculate the progress summary after the user sets a goal.
            refreshList();

            Toast.makeText(this, "Goal saved", Toast.LENGTH_SHORT).show();
        });
    }

    // Sets up the RecyclerView and handles row edit/delete behavior.
    private void setupWeightAdapter(
            RecyclerView recyclerView,
            TextInputEditText dateInput,
            TextInputEditText weightInput,
            Button addButton
    ) {
        adapter = new WeightAdapter(
                db.getAllWeights(),

                id -> {
                    db.deleteWeight(id);
                    refreshList();

                    // If I delete the row currently being edited, I reset the screen.
                    if (selectedId != null && selectedId == id) {
                        resetForm(dateInput, weightInput, addButton);
                    }
                },

                entry -> {
                    // Tapping a row switches the form into edit mode.
                    selectedId = entry.getId();
                    dateInput.setText(entry.getDate());
                    weightInput.setText(String.valueOf(entry.getWeight()));
                    addButton.setText("Update Entry");
                }
        );

        recyclerView.setAdapter(adapter);
    }

    // Handles the add/update button for weight entries.
    private void setupAddButton(
            TextInputEditText dateInput,
            TextInputEditText weightInput,
            Button addButton
    ) {
        addButton.setOnClickListener(v -> {
            String date = InputHelper.getText(dateInput);
            String weightText = InputHelper.getText(weightInput);

            if (date.isEmpty() || weightText.isEmpty()) {
                Toast.makeText(this, "Enter date and weight", Toast.LENGTH_SHORT).show();
                return;
            }

            Double weight = InputHelper.parseDouble(weightText);

            if (weight == null) {
                Toast.makeText(this, "Weight must be a number", Toast.LENGTH_SHORT).show();
                return;
            }

            boolean saved = saveWeightEntry(date, weight);

            if (saved) {
                // Goal logic is separate now, which keeps this activity from getting too crowded.
                GoalHelper.checkGoal(this, db, weight);

                resetForm(dateInput, weightInput, addButton);
                refreshList();
            } else {
                Toast.makeText(this, "Could not save entry", Toast.LENGTH_SHORT).show();
            }
        });
    }

    // Saves a new row or updates the selected row.
    private boolean saveWeightEntry(String date, double weight) {
        if (selectedId == null) {
            return db.addWeight(date, weight);
        }

        return db.updateWeight(selectedId, date, weight);
    }

    // Clears the form and switches back to add mode.
    private void resetForm(
            TextInputEditText dateInput,
            TextInputEditText weightInput,
            Button addButton
    ) {
        dateInput.setText("");
        weightInput.setText("");
        selectedId = null;
        addButton.setText("Add Entry");
    }

    // Refreshes the list after database changes and recalculates the progress summary.
    private void refreshList() {
        List<WeightEntry> entries = db.getAllWeights();

        adapter.updateData(entries);
        updateProgressSummary(entries);
    }

    // Runs the algorithmic summary calculation and displays the result.
    private void updateProgressSummary(List<WeightEntry> entries) {
        Double goal = db.getGoalWeight();
        WeightStats stats = WeightStats.calculate(entries, goal);

        progressSummaryText.setText(stats.getDisplayText());
    }

    // Handles the result of the SMS permission popup.
    @Override
    public void onRequestPermissionsResult(
            int requestCode,
            @NonNull String[] permissions,
            @NonNull int[] grantResults
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

        if (requestCode == SmsHelper.SMS_PERMISSION_CODE) {
            boolean granted = grantResults.length > 0 &&
                    grantResults[0] == PackageManager.PERMISSION_GRANTED;

            if (!granted) {
                Toast.makeText(this, "SMS permission denied", Toast.LENGTH_SHORT).show();
            }
        }
    }
}