package com.example.myapplication6;

import android.content.Intent;
import android.content.res.ColorStateList;
import android.os.Bundle;
import android.widget.EditText;
import android.widget.SeekBar;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import androidx.core.content.ContextCompat;
import com.google.android.material.button.MaterialButton;

public class ShelfEntryActivity extends BaseActivity {

    private long editingId = -1L;
    private String shelf;
    private SeekBar seekPuan;
    private TextView textScoreValue;

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

        MaterialButton btnSettings = findViewById(R.id.btnSettings);
        if (btnSettings != null) {
            btnSettings.setOnClickListener(v -> startActivity(new Intent(this, SettingsActivity.class)));
        }

        shelf = getIntent().getStringExtra(MainActivity.EXTRA_SHELF);
        if (shelf == null || shelf.isEmpty()) {
            shelf = bizimdb.SHELF_READING;
        }

        TextView title = findViewById(R.id.textFormTitle);
        TextView subtitle = findViewById(R.id.textFormSubtitle);
        TextView typeLabel = findViewById(R.id.textTypeLabel);
        EditText editBaslik = findViewById(R.id.editBaslik);
        EditText editYorum = findViewById(R.id.editYorum);
        Spinner spinnerTur = findViewById(R.id.spinnerTur);
        MaterialButton btnKaydet = findViewById(R.id.btnKaydet);
        seekPuan = findViewById(R.id.seekPuan);
        textScoreValue = findViewById(R.id.textScoreValue);

        int accent = accentForShelf(shelf);
        typeLabel.setText(getString(CollectionTypeHelper.categoryLabelForShelf(shelf)));
        CollectionTypeHelper.bindSpinnerForShelf(this, spinnerTur, shelf);
        btnKaydet.setBackgroundTintList(ColorStateList.valueOf(ContextCompat.getColor(this, accent)));

        if (seekPuan != null) {
            seekPuan.setOnSeekBarChangeListener(
                    new SeekBar.OnSeekBarChangeListener() {
                        @Override
                        public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                            updateScoreText();
                        }

                        @Override
                        public void onStartTrackingTouch(SeekBar seekBar) {}

                        @Override
                        public void onStopTrackingTouch(SeekBar seekBar) {}
                    });
            updateScoreText();
        }

        editingId = getIntent().getLongExtra(MainActivity.EXTRA_ENTRY_ID, -1L);
        if (editingId >= 0) {
            bizimdb db = new bizimdb(this);
            bizimdb.Item row = db.getItem(editingId);
            if (row == null || !shelf.equals(row.shelf)) {
                Toast.makeText(this, R.string.error_entry_not_found, Toast.LENGTH_SHORT).show();
                finish();
                return;
            }
            title.setText(R.string.title_edit_entry);
            subtitle.setText(getString(captionForShelf(shelf)));
            editBaslik.setText(row.baslik);
            editYorum.setText(row.yorum);
            int score = parseScore(row.puan);
            if (seekPuan != null) {
                seekPuan.setProgress(score - 1);
                updateScoreText();
            }
            spinnerTur.setSelection(
                    CollectionTypeHelper.indexForStoredTypeKey(this, shelf, row.tur));
            btnKaydet.setText(R.string.action_update_entry);
        } else {
            title.setText(titleForShelf(shelf));
            subtitle.setText(getString(captionForShelf(shelf)));
            btnKaydet.setText(R.string.action_add_to_collection);
        }

        final String shelfFinal = shelf;

        MaterialButton btnBack = findViewById(R.id.btnBack);
        MaterialButton btnNext = findViewById(R.id.btnNext);
        if (btnBack != null) {
            btnBack.setOnClickListener(
                    v -> {
                        Intent i = new Intent(ShelfEntryActivity.this, ShelfBrowseActivity.class);
                        i.putExtra(MainActivity.EXTRA_SHELF, shelfFinal);
                        startActivity(i);
                        finish();
                    });
        }
        if (btnNext != null) {
            btnNext.setOnClickListener(v -> btnKaydet.performClick());
        }

        btnKaydet.setOnClickListener(
                v -> {
                    String typeKey =
                            CollectionTypeHelper.typeKeyAtPosition(
                                    this,
                                    shelfFinal,
                                    spinnerTur.getSelectedItemPosition());
                    String baslik = editBaslik.getText().toString();
                    String puan = String.valueOf(getSelectedScore());
                    String yorum = editYorum.getText().toString();

                    if (editingId >= 0) {
                        bizimdb db = new bizimdb(this);
                        db.guncelle(editingId, baslik, typeKey, puan, yorum);
                        Toast.makeText(this, R.string.toast_updated, Toast.LENGTH_SHORT).show();
                        Intent i = new Intent(ShelfEntryActivity.this, ShelfBrowseActivity.class);
                        i.putExtra(MainActivity.EXTRA_SHELF, shelfFinal);
                        startActivity(i);
                        finish();
                        return;
                    }

                    Intent i = new Intent(ShelfEntryActivity.this, ShelfBrowseActivity.class);
                    i.putExtra(MainActivity.EXTRA_SHELF, shelfFinal);
                    i.putExtra("baslik", baslik);
                    i.putExtra("tur", typeKey);
                    i.putExtra("puan", puan);
                    i.putExtra("yorum", yorum);
                    startActivity(i);
                    finish();
                });
    }

    private int getSelectedScore() {
        if (seekPuan == null) return 1;
        int score = seekPuan.getProgress() + 1;
        return clampScore(score);
    }

    private void updateScoreText() {
        if (textScoreValue == null || seekPuan == null) return;
        textScoreValue.setText(String.valueOf(getSelectedScore()));
    }

    private static int parseScore(String raw) {
        try {
            int v = Integer.parseInt(raw);
            return clampScore(v);
        } catch (Exception e) {
            return 1;
        }
    }

    private static int clampScore(int v) {
        if (v < 1) return 1;
        if (v > 10) return 10;
        return v;
    }

    private static int accentForShelf(String shelf) {
        switch (shelf) {
            case bizimdb.SHELF_WISHLIST:
                return R.color.accent_wishlist;
            case bizimdb.SHELF_TRAVEL:
                return R.color.accent_travel;
            case bizimdb.SHELF_READING:
            default:
                return R.color.accent_reading;
        }
    }

    private static int titleForShelf(String shelf) {
        switch (shelf) {
            case bizimdb.SHELF_WISHLIST:
                return R.string.shelf_title_wishlist;
            case bizimdb.SHELF_TRAVEL:
                return R.string.shelf_title_travel;
            case bizimdb.SHELF_READING:
            default:
                return R.string.shelf_title_reading;
        }
    }

    private static int captionForShelf(String shelf) {
        switch (shelf) {
            case bizimdb.SHELF_WISHLIST:
                return R.string.form_caption_wishlist;
            case bizimdb.SHELF_TRAVEL:
                return R.string.form_caption_travel;
            case bizimdb.SHELF_READING:
            default:
                return R.string.form_caption_reading;
        }
    }
}
