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

import android.os.Bundle;

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

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.Toast;

import com.example.petstoremobile.databinding.FragmentSupplierDetailBinding;
import com.example.petstoremobile.dtos.SupplierDTO;
import com.example.petstoremobile.utils.ActivityLogger;
import com.example.petstoremobile.utils.DateTimeUtils;
import com.example.petstoremobile.utils.DialogUtils;
import com.example.petstoremobile.utils.InputValidator;
import com.example.petstoremobile.utils.Resource;
import com.example.petstoremobile.utils.UIUtils;
import com.example.petstoremobile.viewmodels.SupplierDetailViewModel;

import dagger.hilt.android.AndroidEntryPoint;

/**
 * Fragment for displaying and editing supplier details.
 */
@AndroidEntryPoint
public class SupplierDetailFragment extends Fragment {

    private FragmentSupplierDetailBinding binding;
    private SupplierDetailViewModel viewModel;

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

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

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        UIUtils.formatPhoneInput(binding.etSupPhone);
        observeViewModel();
        handleArguments();

        binding.btnBack.setOnClickListener(v -> navigateBack());
        binding.btnSaveSupplier.setOnClickListener(v -> saveSupplier());
        binding.btnDeleteSupplier.setOnClickListener(v -> deleteSupplier());
    }

    private void observeViewModel() {
        viewModel.getViewState().observe(getViewLifecycleOwner(), this::applyViewState);
    }

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

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

    private void saveSupplier() {
        if (!InputValidator.isNotEmpty(binding.etSupCompany, "Company Name")) return;
        if (!InputValidator.isNotEmpty(binding.etSupContactFirstName, "First Name")) return;
        if (!InputValidator.isNotEmpty(binding.etSupContactLastName, "Last Name")) return;
        if (!InputValidator.isValidEmail(binding.etSupEmail)) return;
        if (!InputValidator.isValidPhone(binding.etSupPhone)) return;

        String company = binding.etSupCompany.getText().toString().trim();
        String firstName = binding.etSupContactFirstName.getText().toString().trim();
        String lastName = binding.etSupContactLastName.getText().toString().trim();
        String email = binding.etSupEmail.getText().toString().trim();
        String phone = binding.etSupPhone.getText().toString().trim();

        SupplierDTO supplierDTO = new SupplierDTO();
        supplierDTO.setSupCompany(company);
        supplierDTO.setSupContactFirstName(firstName);
        supplierDTO.setSupContactLastName(lastName);
        supplierDTO.setSupEmail(email);
        supplierDTO.setSupPhone(phone);

        viewModel.saveSupplier(supplierDTO).observe(getViewLifecycleOwner(), resource -> {
            if (resource == null) return;
            setLoading(resource.status == Resource.Status.LOADING);
            if (resource.status == Resource.Status.SUCCESS) {
                if (viewModel.isEditing()) {
                    ActivityLogger.logChange(requireContext(), "Supplier", "UPDATED", (int) viewModel.getSupId());
                    Toast.makeText(getContext(), "Supplier updated successfully!", Toast.LENGTH_SHORT).show();
                } else {
                    ActivityLogger.log(requireContext(), "Added new Supplier: " + company);
                    Toast.makeText(getContext(), "Supplier added successfully!", Toast.LENGTH_SHORT).show();
                }
                navigateBack();
            } else if (resource.status == Resource.Status.ERROR) {
                Toast.makeText(getContext(), "Error: " + resource.message, Toast.LENGTH_SHORT).show();
            }
        });
    }

    private void deleteSupplier() {
        DialogUtils.showDeleteConfirmDialog(requireContext(), "Supplier", () ->
                viewModel.deleteSupplier().observe(getViewLifecycleOwner(), resource -> {
                    if (resource == null) return;
                    setLoading(resource.status == Resource.Status.LOADING);
                    if (resource.status == Resource.Status.SUCCESS) {
                        ActivityLogger.logChange(requireContext(), "Supplier", "DELETED", (int) viewModel.getSupId());
                        Toast.makeText(getContext(), "Supplier deleted successfully!", Toast.LENGTH_SHORT).show();
                        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();
    }

    private void handleArguments() {
        if (getArguments() != null && getArguments().containsKey("supId")) {
            viewModel.setSupId(getArguments().getLong("supId"));
            loadSupplierData();
            return;
        }

        viewModel.setSupId(-1);
    }

    private void loadSupplierData() {
        viewModel.loadSupplier().observe(getViewLifecycleOwner(), resource -> {
            if (resource == null) return;
            setLoading(resource.status == Resource.Status.LOADING);
            if (resource.status == Resource.Status.ERROR) {
                Toast.makeText(getContext(), "Failed to load supplier: " + resource.message, Toast.LENGTH_SHORT).show();
            }
        });
    }

    private void applyViewState(SupplierDetailViewModel.ViewState state) {
        binding.tvMode.setText(state.modeTitle);
        binding.tvSupId.setText(DateTimeUtils.formatId(viewModel.getSupId()));
        binding.tvSupId.setVisibility(state.isSupIdVisible ? View.VISIBLE : View.GONE);
        binding.btnDeleteSupplier.setVisibility(state.isDeleteVisible ? View.VISIBLE : View.GONE);
        binding.btnSaveSupplier.setText(state.saveButtonText);

        UIUtils.setViewsEnabled(state.isFieldsEnabled,
                binding.etSupCompany,
                binding.etSupContactFirstName,
                binding.etSupContactLastName,
                binding.etSupEmail,
                binding.etSupPhone);

        updateIfDifferent(binding.etSupCompany, state.supCompany);
        updateIfDifferent(binding.etSupContactFirstName, state.supFirstName);
        updateIfDifferent(binding.etSupContactLastName, state.supLastName);
        updateIfDifferent(binding.etSupEmail, state.supEmail);
        updateIfDifferent(binding.etSupPhone, state.supPhone);
    }

    private void updateIfDifferent(EditText field, String value) {
        String current = field.getText() != null ? field.getText().toString() : "";
        String next = value != null ? value : "";
        if (!current.equals(next)) {
            field.setText(next);
        }
    }
}
