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

import android.os.Bundle;
import android.view.*;
import android.widget.*;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProvider;
import androidx.navigation.fragment.NavHostFragment;
import com.example.petstoremobile.databinding.FragmentCustomerDetailBinding;
import com.example.petstoremobile.dtos.CustomerDTO;
import com.example.petstoremobile.utils.DialogUtils;
import com.example.petstoremobile.utils.InputValidator;
import com.example.petstoremobile.utils.SpinnerUtils;
import com.example.petstoremobile.utils.UIUtils;
import com.example.petstoremobile.viewmodels.CustomerDetailViewModel;
import com.example.petstoremobile.api.auth.TokenManager;
import com.example.petstoremobile.utils.Resource;

import javax.inject.Inject;

import dagger.hilt.android.AndroidEntryPoint;

@AndroidEntryPoint
public class CustomerDetailFragment extends Fragment {

    private FragmentCustomerDetailBinding binding;
    private CustomerDetailViewModel viewModel;

    @Inject TokenManager tokenManager;

    private final String[] STATUSES = {"Active", "Inactive"};

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        binding = FragmentCustomerDetailBinding.inflate(inflater, container, false);
        viewModel = new ViewModelProvider(this).get(CustomerDetailViewModel.class);

        setupSpinners();
        handleArguments();

        binding.btnCustomerBack.setOnClickListener(v -> navigateBack());
        binding.btnSaveCustomer.setOnClickListener(v -> save());
        binding.btnDeleteCustomer.setOnClickListener(v -> confirmDelete());

        UIUtils.formatPhoneInput(binding.etCustomerPhone);

        return binding.getRoot();
    }

    private void setupSpinners() {
        SpinnerUtils.setupStringSpinner(requireContext(), binding.spinnerCustomerStatus, STATUSES);
    }

    private void handleArguments() {
        Bundle a = getArguments();
        if (a != null && a.getBoolean("isEditing", false)) {
            long customerId = a.getLong("customerId", -1);
            viewModel.setCustomerId(customerId, true);

            binding.tvCustomerMode.setText("Edit Customer");
            binding.tvCustomerId.setText("ID: " + customerId);
            binding.tvCustomerId.setVisibility(View.VISIBLE);
            binding.btnDeleteCustomer.setVisibility(View.VISIBLE);

            // Hide password field in edit mode
            binding.tvCustomerPasswordLabel.setVisibility(View.GONE);
            binding.etCustomerPassword.setVisibility(View.GONE);

            // Show loyalty points
            binding.tvLoyaltyPointsLabel.setVisibility(View.VISIBLE);
            binding.etCustomerLoyaltyPoints.setVisibility(View.VISIBLE);

            boolean isAdmin = "ADMIN".equalsIgnoreCase(tokenManager.getRole());
            binding.etCustomerLoyaltyPoints.setEnabled(isAdmin);

            loadCustomerData(customerId);
        } else {
            viewModel.setCustomerId(-1, false);
            binding.tvCustomerMode.setText("Add Customer");
            binding.btnDeleteCustomer.setVisibility(View.GONE);
            binding.tvCustomerId.setVisibility(View.GONE);
            binding.tvLoyaltyPointsLabel.setVisibility(View.GONE);
            binding.etCustomerLoyaltyPoints.setVisibility(View.GONE);
        }
    }

    private void loadCustomerData(long id) {
        viewModel.loadCustomer(id).observe(getViewLifecycleOwner(), resource -> {
            if (resource != null) {
                setLoading(resource.status == Resource.Status.LOADING);
                if (resource.status == Resource.Status.SUCCESS && resource.data != null) {
                    CustomerDTO c = resource.data;
                    binding.etCustomerUsername.setText(c.getUsername() != null ? c.getUsername() : "");
                    binding.etCustomerFirstName.setText(c.getFirstName() != null ? c.getFirstName() : "");
                    binding.etCustomerLastName.setText(c.getLastName() != null ? c.getLastName() : "");
                    binding.etCustomerEmail.setText(c.getEmail() != null ? c.getEmail() : "");
                    binding.etCustomerPhone.setText(c.getPhone() != null ? c.getPhone() : "");
                    binding.spinnerCustomerStatus.setSelection(Boolean.TRUE.equals(c.getActive()) ? 0 : 1);
                    int pts = c.getLoyaltyPoints() != null ? c.getLoyaltyPoints() : 0;
                    binding.etCustomerLoyaltyPoints.setText(String.valueOf(pts));
                }
            }
        });
    }

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

    private void save() {
        if (!InputValidator.isNotEmpty(binding.etCustomerUsername, "Username")) return;

        if (!viewModel.isEditing()) {
            if (!InputValidator.isNotEmpty(binding.etCustomerPassword, "Password")) return;
            String pass = binding.etCustomerPassword.getText().toString();
            if (pass.length() < 6) {
                binding.etCustomerPassword.setError("At least 6 characters");
                binding.etCustomerPassword.requestFocus();
                return;
            }
        }

        if (!InputValidator.isNotEmpty(binding.etCustomerFirstName, "First Name")) return;
        if (!InputValidator.isNotEmpty(binding.etCustomerLastName, "Last Name")) return;
        if (!InputValidator.isValidEmail(binding.etCustomerEmail)) return;
        if (!InputValidator.isValidPhone(binding.etCustomerPhone)) return;

        Integer loyaltyPoints = null;
        if (viewModel.isEditing()) {
            if (!InputValidator.isPositiveInteger(binding.etCustomerLoyaltyPoints, "Loyalty Points")) return;
            loyaltyPoints = Integer.parseInt(binding.etCustomerLoyaltyPoints.getText().toString().trim());
        }

        String username  = binding.etCustomerUsername.getText().toString().trim();
        String password  = viewModel.isEditing() ? null : binding.etCustomerPassword.getText().toString().trim();
        String firstName = binding.etCustomerFirstName.getText().toString().trim();
        String lastName  = binding.etCustomerLastName.getText().toString().trim();
        String email     = binding.etCustomerEmail.getText().toString().trim();
        String phone     = binding.etCustomerPhone.getText().toString().trim();
        boolean active   = binding.spinnerCustomerStatus.getSelectedItemPosition() == 0;

        CustomerDTO dto = viewModel.createCustomerDto(username, password, firstName, lastName, email, phone, active, loyaltyPoints);

        viewModel.saveCustomer(dto).observe(getViewLifecycleOwner(), resource -> {
            if (resource != null) {
                setLoading(resource.status == Resource.Status.LOADING);
                if (resource.status == Resource.Status.SUCCESS) {
                    Toast.makeText(getContext(),
                            viewModel.isEditing() ? "Updated successfully" : "Customer created",
                            Toast.LENGTH_SHORT).show();
                    navigateBack();
                } else if (resource.status == Resource.Status.ERROR) {
                    Toast.makeText(getContext(), "Error: " + resource.message, Toast.LENGTH_LONG).show();
                }
            }
        });
    }

    private void confirmDelete() {
        DialogUtils.showDeleteConfirmDialog(requireContext(), "Customer", () ->
                viewModel.deleteCustomer().observe(getViewLifecycleOwner(), resource -> {
                    if (resource != null) {
                        setLoading(resource.status == Resource.Status.LOADING);
                        if (resource.status == Resource.Status.SUCCESS) {
                            navigateBack();
                        } else if (resource.status == Resource.Status.ERROR) {
                            Toast.makeText(getContext(), "Delete failed: " + resource.message,
                                    Toast.LENGTH_SHORT).show();
                        }
                    }
                }));
    }

    private void navigateBack() {
        NavHostFragment.findNavController(this).popBackStack();
    }

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