package com.example.petstoremobile.fragments.listfragments.listprofilefragments;

import android.net.Uri;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProvider;
import androidx.navigation.fragment.NavHostFragment;

import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import com.example.petstoremobile.R;
import com.example.petstoremobile.api.PetApi;
import com.example.petstoremobile.api.auth.TokenManager;
import com.example.petstoremobile.databinding.FragmentPetProfileBinding;
import com.example.petstoremobile.dtos.PetDTO;
import com.example.petstoremobile.utils.FileUtils;
import com.example.petstoremobile.utils.GlideUtils;
import com.example.petstoremobile.utils.ImagePickerHelper;
import com.example.petstoremobile.utils.Resource;
import com.example.petstoremobile.viewmodels.PetProfileViewModel;

import java.io.File;
import java.util.Locale;

import javax.inject.Inject;
import javax.inject.Named;

import dagger.hilt.android.AndroidEntryPoint;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;

@AndroidEntryPoint
public class PetProfileFragment extends Fragment {

    private FragmentPetProfileBinding binding;
    private long petId;
    private boolean hasImage = false;

    @Inject @Named("baseUrl") String baseUrl;
    @Inject TokenManager tokenManager;

    private PetProfileViewModel viewModel;
    private ImagePickerHelper imagePickerHelper;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        viewModel = new ViewModelProvider(this).get(PetProfileViewModel.class);

        imagePickerHelper = new ImagePickerHelper(this, "pet_photo.jpg", new ImagePickerHelper.ImagePickerListener() {
            @Override
            public void onImagePicked(Uri uri) {
                uploadPetImage(uri);
            }

            @Override
            public void onImageRemoved() {
                deletePetImage();
            }
        });
    }

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        binding = FragmentPetProfileBinding.inflate(inflater, container, false);

        if (getArguments() != null) {
            petId = getArguments().getLong("petId");
            loadPetData();
            loadPetImage((int) petId);
        }

        binding.btnBack.setOnClickListener(v -> {
            NavHostFragment.findNavController(this).popBackStack();
        });

        binding.btnEditPet.setOnClickListener(v -> {
            Bundle args = new Bundle();
            args.putLong("petId", petId);
            NavHostFragment.findNavController(this).navigate(R.id.nav_pet_detail, args);
        });

        binding.btnChangePhoto.setOnClickListener(v -> {
            imagePickerHelper.showImagePickerDialog("Change Pet Photo", hasImage);
        });

        return binding.getRoot();
    }

    private void setLoading(boolean loading) {
        if (binding != null && binding.progressBar != null) {
            binding.progressBar.setVisibility(loading ? View.VISIBLE : View.GONE);
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        binding = null;
    }

    private void loadPetData() {
        viewModel.getPetById(petId).observe(getViewLifecycleOwner(), resource -> {
            if (resource == null) return;
            setLoading(resource.status == Resource.Status.LOADING);
            if (resource.status == Resource.Status.SUCCESS && resource.data != null) {
                PetDTO pet = resource.data;
                binding.tvPetName.setText(pet.getPetName());
                binding.tvPetSpecies.setText(pet.getPetSpecies());
                binding.tvPetBreed.setText(pet.getPetBreed());
                binding.tvPetAge.setText(String.format(Locale.getDefault(), "%d yr(s)", pet.getPetAge()));
                
                if (pet.getPetPrice() != null) {
                    binding.tvPetPrice.setText(String.format(Locale.getDefault(), "$%.2f", pet.getPetPrice()));
                } else {
                    binding.tvPetPrice.setText("$0.00");
                }

                String status = pet.getPetStatus();

                if ("Adopted".equalsIgnoreCase(status) || "Owned".equalsIgnoreCase(status) || "Pending".equalsIgnoreCase(status)) {
                    binding.layoutPetOwner.setVisibility(View.VISIBLE);
                    if (pet.getCustomerName() != null && !pet.getCustomerName().isEmpty()) {
                        binding.tvPetOwner.setText(pet.getCustomerName());
                    } else {
                        binding.tvPetOwner.setText("No Owner");
                    }
                } else {
                    binding.layoutPetOwner.setVisibility(View.GONE);
                }

                if ("Available".equalsIgnoreCase(status) || "Adopted".equalsIgnoreCase(status) || "Pending".equalsIgnoreCase(status)) {
                    binding.layoutPetStore.setVisibility(View.VISIBLE);
                    if (pet.getStoreName() != null && !pet.getStoreName().isEmpty()) {
                        binding.tvPetStore.setText(pet.getStoreName());
                    } else {
                        binding.tvPetStore.setText("No Store");
                    }
                } else {
                    binding.layoutPetStore.setVisibility(View.GONE);
                }
            } else if (resource.status == Resource.Status.ERROR) {
                Toast.makeText(getContext(), "Failed to load pet data: " + resource.message, Toast.LENGTH_SHORT).show();
            }
        });
    }

    private void loadPetImage(int petId) {
        String imageUrl = baseUrl + String.format(Locale.US, PetApi.PET_IMAGE_PATH, petId);
        String token = tokenManager.getToken();

        GlideUtils.loadImageWithToken(requireContext(), binding.imgPet, imageUrl, token, R.drawable.placeholder, new GlideUtils.ImageLoadListener() {
            @Override
            public void onResourceReady() {
                hasImage = true;
            }

            @Override
            public void onLoadFailed() {
                hasImage = false;
            }
        });
    }

    private void uploadPetImage(Uri uri) {
        try {
            File file = FileUtils.getFileFromUri(requireContext(), uri);
            if (file == null) return;

            RequestBody requestFile = RequestBody.create(file, MediaType.parse(requireContext().getContentResolver().getType(uri)));
            MultipartBody.Part body = MultipartBody.Part.createFormData("image", file.getName(), requestFile);

            viewModel.uploadPetImage(petId, body).observe(getViewLifecycleOwner(), resource -> {
                if (resource == null) return;
                setLoading(resource.status == Resource.Status.LOADING);
                if (resource.status == Resource.Status.SUCCESS) {
                    Toast.makeText(getContext(), "Pet photo updated successfully", Toast.LENGTH_SHORT).show();
                    loadPetImage((int) petId);
                } else if (resource.status == Resource.Status.ERROR) {
                    Toast.makeText(getContext(), "Upload failed: " + resource.message, Toast.LENGTH_SHORT).show();
                }
            });
        } catch (Exception e) {
            Log.e("UPLOAD_PET_IMAGE", "Error: " + e.getMessage());
        }
    }

    private void deletePetImage() {
        viewModel.deletePetImage(petId).observe(getViewLifecycleOwner(), resource -> {
            if (resource == null) return;
            setLoading(resource.status == Resource.Status.LOADING);
            if (resource.status == Resource.Status.SUCCESS) {
                Toast.makeText(getContext(), "Pet photo removed", Toast.LENGTH_SHORT).show();
                hasImage = false;
                binding.imgPet.setImageResource(R.drawable.placeholder);
            } else if (resource.status == Resource.Status.ERROR) {
                Toast.makeText(getContext(), "Delete failed: " + resource.message, Toast.LENGTH_SHORT).show();
            }
        });
    }
}
