package com.example.gallery;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.widget.*;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import com.example.gallery.api.ApiClient;
import com.example.gallery.api.ApiService;
import com.example.gallery.models.FileUtils;
import com.example.gallery.models.Publication;

import java.io.File;

import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class NewPostActivity extends AppCompatActivity {

    private EditText descriptionET;
    private RadioGroup mediaTypeRG;
    private Spinner categorySpinner;
    private Button selectMediaBtn, submitBtn, cancelBtn;
    private TextView selectedFileTV;
    private ImageView previewIV;

    private Uri selectedFileUri;
    private String mediaType = "image";
    private int selectedCategory = 1; // default

    private final ActivityResultLauncher<Intent> picker =
            registerForActivityResult(new ActivityResultContracts.StartActivityForResult(),
                    result -> {
                        if (result.getResultCode() == RESULT_OK && result.getData() != null) {
                            selectedFileUri = result.getData().getData();
                            selectedFileTV.setText(FileUtils.getFileName(this, selectedFileUri));

                            if (mediaType.equals("image")) {
                                previewIV.setImageURI(selectedFileUri);
                                previewIV.setVisibility(ImageView.VISIBLE);
                            } else {
                                previewIV.setVisibility(ImageView.GONE);
                            }
                        }
                    });

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

        descriptionET = findViewById(R.id.descriptionET);
        mediaTypeRG = findViewById(R.id.mediaTypeRG);
        selectMediaBtn = findViewById(R.id.selectMediaBtn);
        submitBtn = findViewById(R.id.submitBtn);
        cancelBtn = findViewById(R.id.cancelBtn);
        selectedFileTV = findViewById(R.id.selectedFileTV);
        previewIV = findViewById(R.id.previewIV);

        // Spinner for categories
        categorySpinner = findViewById(R.id.categorySpinner);
        ArrayAdapter<CharSequence> adapter = new ArrayAdapter<>(this,
                android.R.layout.simple_spinner_item,
                new String[]{"nature","city","landscape","animals","people"}); // categories from API
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        categorySpinner.setAdapter(adapter);
        categorySpinner.setSelection(0);
        categorySpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override public void onItemSelected(AdapterView<?> parent, android.view.View view, int position, long id) {
                selectedCategory = new int[]{1,2,3,4,5}[position];
            }
            @Override public void onNothingSelected(AdapterView<?> parent) {}
        });

        mediaTypeRG.setOnCheckedChangeListener((g, id) -> mediaType = (id == R.id.photoRB) ? "image" : "video");

        selectMediaBtn.setOnClickListener(v -> {
            Intent i = new Intent(Intent.ACTION_PICK);
            i.setType(mediaType.equals("image") ? "image/*" : "video/*");
            picker.launch(i);
        });

        submitBtn.setOnClickListener(v -> uploadPost());
        cancelBtn.setOnClickListener(v -> confirmCancel());
    }

    @Override
    public void onBackPressed() { confirmCancel(); }

    private void confirmCancel() {
        new AlertDialog.Builder(this)
                .setTitle("Cancel post")
                .setMessage("Are you sure?")
                .setPositiveButton("Yes", (d, w) -> super.onBackPressed())
                .setNegativeButton("No", null)
                .show();
    }

    private void uploadPost() {
        if (selectedFileUri == null || descriptionET.getText().toString().trim().isEmpty()) {
            Toast.makeText(this, "Select file and enter description", Toast.LENGTH_SHORT).show();
            return;
        }

        String rawToken = getSharedPreferences("MyAppPrefs", MODE_PRIVATE)
                .getString("authToken", null);

        if (rawToken == null) {
            Toast.makeText(this, "Login required", Toast.LENGTH_SHORT).show();
            return;
        }

        String authHeader = "Token " + rawToken;

        try {
            File file = FileUtils.getFileFromUri(this, selectedFileUri);
            MediaType mediaTypeFile = MediaType.parse(getContentResolver().getType(selectedFileUri));
            RequestBody fileBody = RequestBody.create(mediaTypeFile, file);

            MultipartBody.Part filePart = MultipartBody.Part.createFormData(
                    mediaType.equals("image") ? "image" : "video",
                    file.getName(),
                    fileBody
            );

            RequestBody desc = RequestBody.create(MediaType.parse("text/plain"),
                    descriptionET.getText().toString().trim());

            RequestBody ct = RequestBody.create(MediaType.parse("text/plain"), mediaType);
            RequestBody status = RequestBody.create(MediaType.parse("text/plain"), "public");
            RequestBody category = RequestBody.create(MediaType.parse("text/plain"), String.valueOf(selectedCategory));

            ApiService apiService = ApiClient.getClient().create(ApiService.class);

            Call<Publication> call = apiService.createPublication(
                    authHeader,
                    desc,
                    ct,
                    status,
                    category,
                    filePart
            );

            call.enqueue(new Callback<Publication>() {
                @Override
                public void onResponse(Call<Publication> call, Response<Publication> response) {
                    if (response.isSuccessful() && response.body() != null) {
                        Toast.makeText(NewPostActivity.this, "Post created 🎉", Toast.LENGTH_SHORT).show();
                        setResult(RESULT_OK); // signal MainActivity to refresh
                        finish();
                    } else {
                        Toast.makeText(NewPostActivity.this,
                                "Error " + response.code() + ": check fields", Toast.LENGTH_LONG).show();
                    }
                }

                @Override
                public void onFailure(Call<Publication> call, Throwable t) {
                    Toast.makeText(NewPostActivity.this, t.getMessage(), Toast.LENGTH_LONG).show();
                }
            });

        } catch (Exception e) {
            Toast.makeText(this, e.getMessage(), Toast.LENGTH_LONG).show();
        }
    }
}
