package com.example.myapplication;

import android.annotation.SuppressLint;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log; // Добавлено для логирования
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.Spinner;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.example.myapplication.api.LoadCurrencyRatesTask;
import com.github.mikephil.charting.charts.LineChart;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.data.Entry; // Импорт Entry для точек данных на графике
import com.github.mikephil.charting.data.LineData;
import com.github.mikephil.charting.data.LineDataSet; // Импорт LineDataSet для набора данных
import com.github.mikephil.charting.formatter.ValueFormatter; // Импорт ValueFormatter для пользовательских подписей оси
import com.github.mikephil.charting.utils.ColorTemplate; // Импорт ColorTemplate для цветов
import com.google.android.material.button.MaterialButtonToggleGroup;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;

public class MainActivity extends AppCompatActivity {
    private Spinner spinnerFrom;
    private Spinner spinnerTo;
    private EditText inputFrom;
    private EditText inputTo;
    private ProgressBar loadingIndicator;
    private CurrencyRepository repository;
    private MaterialButtonToggleGroup timeRangeToggleGroup;

    private boolean isRatesLoaded = false;

    private LineChart lineChart; // Инициализация графика

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



        repository = new CurrencyRepository(this);
        spinnerFrom = findViewById(R.id.spinner_from);
        spinnerTo = findViewById(R.id.spinner_to);
        inputFrom = findViewById(R.id.input_from);
        inputTo = findViewById(R.id.input_to);
        loadingIndicator = findViewById(R.id.loading_indicator);
        lineChart = findViewById(R.id.line_chart); // Инициализация графика
        timeRangeToggleGroup = findViewById(R.id.time_range_toggle_group);

        // Показываем индикатор загрузки и загружаем курсы
        loadingIndicator.setVisibility(View.VISIBLE);
        repository.loadAllCurrencyRatesFromApi(new LoadCurrencyRatesTask.Callback() {
            @Override
            public void onRatesLoaded() {
                runOnUiThread(() -> {
                    new LoadCurrenciesTask().execute();
                });
            }

            @Override
            public void onError(Exception e) {
                runOnUiThread(() -> {
                    loadingIndicator.setVisibility(View.GONE);
                    showToast("Ошибка загрузки курсов валют: " + e.getMessage());
                });
            }
        });

        timeRangeToggleGroup.addOnButtonCheckedListener(new MaterialButtonToggleGroup.OnButtonCheckedListener() {
            @Override
            public void onButtonChecked(MaterialButtonToggleGroup group, int checkedId, boolean isChecked) {
                if (isChecked) {
                    Log.d("MainActivity", "Button checked: " + checkedId);
                    if (isRatesLoaded) {
                        performConversion();
                        loadChartData(); // Загружаем данные для графика при изменении выбора периода
                    } else {
                        showToast("Подождите, пока загрузятся курсы валют.");
                    }
                } else {
                    Log.d("MainActivity", "Button unchecked: " + checkedId);
                }
            }
        });

        inputFrom.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            @Override
            public void afterTextChanged(Editable s) {
                if (isRatesLoaded) {
                    performConversion();
                } else {
                    showToast("Подождите, пока загрузятся курсы валют.");
                }
            }
        });

        AdapterView.OnItemSelectedListener spinnerListener = new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                if (isRatesLoaded) {
                    performConversion();
                    loadChartData(); // Загружаем данные для графика при изменении выбора
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {}
        };

        spinnerFrom.setOnItemSelectedListener(spinnerListener);
        spinnerTo.setOnItemSelectedListener(spinnerListener);
    }

    private void loadChartData() {
        String fromCurrency = spinnerFrom.getSelectedItem().toString().toUpperCase();
        String toCurrency = spinnerTo.getSelectedItem().toString().toUpperCase();

        int timeRangeDays = 7;  // Значение по умолчанию
        int checkedButtonId = timeRangeToggleGroup.getCheckedButtonId();

        if (checkedButtonId == R.id.button_7_days) {
            timeRangeDays = 7;
        } else if (checkedButtonId == R.id.button_30_days) {
            timeRangeDays = 30;
        } else if (checkedButtonId == R.id.button_90_days) {
            timeRangeDays = 90;
        } else {
            timeRangeDays = 7; // По умолчанию 7 дней, если ничего не выбрано
        }

        new LoadChartDataTask(fromCurrency, toCurrency, timeRangeDays).execute();
    }

    private class LoadChartDataTask extends AsyncTask<Void, Void, LineData> {
        private final String fromCurrency;
        private final String toCurrency;
        private final int timeRangeDays;
        private List<Date> dates;

        public LoadChartDataTask(String fromCurrency, String toCurrency, int timeRangeDays) {
            this.fromCurrency = fromCurrency;
            this.toCurrency = toCurrency;
            this.timeRangeDays = timeRangeDays;
        }

        @Override
        protected LineData doInBackground(Void... voids) {
            Date endDate = new Date();  // Текущая дата
            Calendar cal = Calendar.getInstance();
            cal.setTime(endDate);
            cal.add(Calendar.DAY_OF_YEAR, -timeRangeDays);
            Date startDate = cal.getTime();

            List<CurrencyRate> historyFrom = repository.getCurrencyRateHistoryWithinDates("USD", fromCurrency, startDate, endDate);
            List<CurrencyRate> historyTo = repository.getCurrencyRateHistoryWithinDates("USD", toCurrency, startDate, endDate);

            if (fromCurrency.equals("USD")) {
                historyFrom = generateUsdHistory(startDate, endDate);
            }

            if (toCurrency.equals("USD")) {
                historyTo = generateUsdHistory(startDate, endDate);
            }

            if (historyFrom == null || historyTo == null ||
                    historyFrom.isEmpty() || historyTo.isEmpty()) {
                return null;
            }

            int size = Math.min(historyFrom.size(), historyTo.size());
            List<Entry> entries = new ArrayList<>();
            dates = new ArrayList<>();

            for (int i = 0; i < size; i++) {
                CurrencyRate rateFrom = historyFrom.get(i);
                CurrencyRate rateTo = historyTo.get(i);

                double rateFromUSD = rateFrom.rate;
                double rateToUSD = rateTo.rate;

                double crossRate = rateToUSD / rateFromUSD;

                entries.add(new Entry(i, (float) crossRate));
                dates.add(rateFrom.date);
            }

            LineDataSet dataSet = new LineDataSet(entries, "Курс " + fromCurrency + "/" + toCurrency);
            dataSet.setColor(ColorTemplate.getHoloBlue());
            dataSet.setLineWidth(2f);
            dataSet.setDrawCircles(false);
            dataSet.setMode(LineDataSet.Mode.CUBIC_BEZIER);
            dataSet.setDrawFilled(true);
            dataSet.setFillAlpha(50);
            dataSet.setFillColor(ColorTemplate.getHoloBlue());
            dataSet.setDrawValues(false);

            return new LineData(dataSet);
        }

        private List<CurrencyRate> generateUsdHistory(Date startDate, Date endDate) {
            List<Date> allDates = repository.getAllDatesWithinRange(startDate, endDate);
            List<CurrencyRate> usdHistory = new ArrayList<>();
            for (Date date : allDates) {
                usdHistory.add(new CurrencyRate("USD", "USD", 1.0, date));
            }
            return usdHistory;
        }

        @Override
        protected void onPostExecute(LineData lineData) {
            if (lineData != null && lineData.getEntryCount() > 0) {
                // Настраиваем ось X для отображения дат
                XAxis xAxis = lineChart.getXAxis();
                xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);
                xAxis.setLabelRotationAngle(-45f);
                xAxis.setGranularity(1f);
                xAxis.setDrawGridLines(false);
                xAxis.setValueFormatter(new ValueFormatter() {
                    private final SimpleDateFormat mFormat = new SimpleDateFormat("dd MMM", Locale.getDefault());

                    @Override
                    public String getFormattedValue(float value) {
                        int index = (int) value;
                        if (index >= 0 && index < dates.size()) {
                            Date date = dates.get(index);
                            return mFormat.format(date);
                        } else {
                            return "";
                        }
                    }
                });

                // Настраиваем ось Y
                lineChart.getAxisRight().setEnabled(false);

                // Обновляем данные графика
                lineChart.setData(lineData);

                // Разрешаем взаимодействие
                lineChart.setTouchEnabled(true);
                lineChart.setDragEnabled(true);
                lineChart.setScaleEnabled(true);

                // Устанавливаем кастомный MarkerView
                CustomMarkerView markerView = new CustomMarkerView(MainActivity.this, R.layout.custom_marker_view, dates);
                markerView.setChartView(lineChart);
                lineChart.setMarker(markerView);

                lineChart.invalidate();
            } else {
                lineChart.clear();
                lineChart.invalidate();
                showToast("Нет данных для отображения графика за выбранный период");
            }
        }
    }

    private class LoadCurrenciesTask extends AsyncTask<Void, Void, List<String>> {
        @Override
        protected void onPreExecute() {
            loadingIndicator.setVisibility(View.VISIBLE);
        }

        @Override
        protected List<String> doInBackground(Void... voids) {
            // Загрузка списка валют из репозитория
            return repository.getAllUniqueCurrencies();
        }

        @Override
        protected void onPostExecute(List<String> currencies) {
            loadingIndicator.setVisibility(View.GONE);
            if (currencies != null && !currencies.isEmpty()) {
                isRatesLoaded = true;
                ArrayAdapter<String> adapterFrom = new ArrayAdapter<>(MainActivity.this, android.R.layout.simple_spinner_item, currencies);
                adapterFrom.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
                spinnerFrom.setAdapter(adapterFrom);

                ArrayAdapter<String> adapterTo = new ArrayAdapter<>(MainActivity.this, android.R.layout.simple_spinner_item, currencies);
                adapterTo.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
                spinnerTo.setAdapter(adapterTo);

                // Устанавливаем стандартные значения
                spinnerFrom.setSelection(0);
                spinnerTo.setSelection(1);

                // Выполняем конвертацию и загружаем данные для графика
                performConversion();
                loadChartData();

                // Устанавливаем кнопку по умолчанию в ToggleGroup
                timeRangeToggleGroup.check(R.id.button_7_days);
            } else {
                showToast("Не удалось загрузить валюты");
            }
        }
    }

    private void performConversion() {
        String fromCurrency = spinnerFrom.getSelectedItem().toString().toUpperCase();
        String toCurrency = spinnerTo.getSelectedItem().toString().toUpperCase();
        String amountStr = inputFrom.getText().toString();

        if (amountStr.isEmpty()) {
            inputTo.setText("");
            return;
        }

        if (fromCurrency.equals(toCurrency)) {
            inputTo.setText(amountStr);
            return;
        }

        try {
            double amount = Double.parseDouble(amountStr);

            // Выполняем конвертацию
            new ConvertCurrencyTask(fromCurrency, toCurrency, amount, repository, result -> {
                if (result != null) {
                    inputTo.setText(String.format("%.2f", result));
                } else {
                    showToast("Ошибка при конвертации валюты: Курс не найден");
                    inputTo.setText("");
                }
            }).execute();
        } catch (NumberFormatException e) {
            inputTo.setText("");
        }
    }

    private void showToast(String message) {
        Toast.makeText(MainActivity.this, message, Toast.LENGTH_SHORT).show();
    }
}


<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/constraint_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="16dp"
    android:background="@color/background_color"
    tools:context=".MainActivity">

    <!-- Загрузочный индикатор (ProgressBar) -->
    <ProgressBar
        android:id="@+id/loading_indicator"
        style="?android:attr/progressBarStyleLarge"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:indeterminateTint="@color/colorPrimary"
        android:visibility="gone"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <!-- Спиннеры выбора валют -->
    <Spinner
        android:id="@+id/spinner_from"
        style="@style/SpinnerStyle"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginEnd="8dp"
        app:layout_constraintEnd_toStartOf="@+id/spinner_to"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <Spinner
        android:id="@+id/spinner_to"
        style="@style/SpinnerStyle"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginStart="8dp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toEndOf="@id/spinner_from"
        app:layout_constraintTop_toTopOf="@id/spinner_from" />

    <!-- Поле ввода суммы -->
    <com.google.android.material.textfield.TextInputLayout
        android:id="@+id/input_layout_from"
        style="@style/Widget.MaterialComponents.TextInputLayout.OutlinedBox.Dense"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:hint="Введите сумму"
        app:boxStrokeColor="@color/colorPrimary"
        android:layout_marginTop="16dp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@id/spinner_from">

        <com.google.android.material.textfield.TextInputEditText
            android:id="@+id/input_from"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:inputType="numberDecimal"
            android:padding="12dp" />

    </com.google.android.material.textfield.TextInputLayout>

    <!-- Поле вывода конвертированной суммы -->
    <com.google.android.material.textfield.TextInputLayout
        android:id="@+id/input_layout_to"
        style="@style/Widget.MaterialComponents.TextInputLayout.OutlinedBox.Dense"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:hint="Конвертированная сумма"
        app:boxStrokeColor="@color/colorPrimary"
        android:layout_marginTop="16dp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@id/input_layout_from">

        <com.google.android.material.textfield.TextInputEditText
            android:id="@+id/input_to"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:inputType="none"
            android:focusable="false"
            android:padding="12dp"
            android:background="@drawable/edittext_background_disabled" />

    </com.google.android.material.textfield.TextInputLayout>

    <!-- Layout for Time Range Selection -->
    <LinearLayout
        android:id="@+id/time_range_layout"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:gravity="center_vertical"
        android:layout_marginTop="16dp"
        app:layout_constraintTop_toBottomOf="@id/input_layout_to"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintEnd_toEndOf="parent">

        <TextView
            android:id="@+id/time_range_label"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Период:"
            android:textSize="16sp"
            android:layout_marginEnd="8dp"
            android:textColor="@color/black" />

        <!-- Заменяем Spinner на MaterialButtonToggleGroup -->
        <com.google.android.material.button.MaterialButtonToggleGroup
            android:id="@+id/time_range_toggle_group"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            app:singleSelection="true"> <!-- Добавьте этот атрибут -->

            <com.google.android.material.button.MaterialButton
                android:id="@+id/button_7_days"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="7 дней"
                android:checked="true"
                style="@style/Widget.MaterialComponents.Button.OutlinedButton" />

            <com.google.android.material.button.MaterialButton
                android:id="@+id/button_30_days"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="30 дней"
                style="@style/Widget.MaterialComponents.Button.OutlinedButton" />

            <com.google.android.material.button.MaterialButton
                android:id="@+id/button_90_days"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="90 дней"
                style="@style/Widget.MaterialComponents.Button.OutlinedButton" />

        </com.google.android.material.button.MaterialButtonToggleGroup>
    </LinearLayout>

    <!-- График тренда -->
    <com.github.mikephil.charting.charts.LineChart
        android:id="@+id/line_chart"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:background="@color/chart_background"
        android:elevation="4dp"
        android:layout_marginTop="24dp"
        android:layout_marginBottom="16dp"
        app:layout_constraintTop_toBottomOf="@id/time_range_layout"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintEnd_toEndOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout> добавь кнопку для свапа валют