package com.example.petstoremobile.fragments.listfragments;

import android.app.DatePickerDialog;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.widget.Toast;

import androidx.navigation.fragment.NavHostFragment;

import com.example.petstoremobile.adapters.ActivityLogAdapter;
import com.example.petstoremobile.api.auth.TokenManager;
import com.example.petstoremobile.databinding.FragmentActivityLogBinding;
import com.example.petstoremobile.dtos.ActivityLogDTO;
import com.example.petstoremobile.dtos.DropdownDTO;
import com.example.petstoremobile.utils.SpinnerUtils;
import com.example.petstoremobile.utils.UIUtils;
import com.example.petstoremobile.viewmodels.ActivityLogListViewModel;

import javax.inject.Inject;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import dagger.hilt.android.AndroidEntryPoint;

@AndroidEntryPoint
public class ActivityLogFragment extends Fragment {
    private FragmentActivityLogBinding binding;
    private ActivityLogListViewModel viewModel;
    private ActivityLogAdapter adapter;
    private final List<ActivityLogDTO> logList = new ArrayList<>();
    private List<DropdownDTO> storeList = new ArrayList<>();
    private String selectedStartDate = null;
    private String selectedEndDate = null;

    @Inject TokenManager tokenManager;

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

        if (!"ADMIN".equalsIgnoreCase(tokenManager.getRole())) {
            Toast.makeText(requireContext(), "Access denied", Toast.LENGTH_SHORT).show();
            NavHostFragment.findNavController(this).popBackStack();
            return binding.getRoot();
        }

        viewModel = new ViewModelProvider(this).get(ActivityLogListViewModel.class);

        setupRecyclerView();
        setupFilters();
        observeViewModel();

        binding.swipeRefreshActivityLog.setOnRefreshListener(() -> viewModel.loadInitialData());
        UIUtils.setupHamburgerMenu(binding.btnHamburgerActivityLog, this);

        return binding.getRoot();
    }

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

    private void setupRecyclerView() {
        adapter = new ActivityLogAdapter(logList);
        binding.recyclerViewActivityLog.setLayoutManager(new LinearLayoutManager(getContext()));
        binding.recyclerViewActivityLog.setAdapter(adapter);

        binding.recyclerViewActivityLog.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
                if (dy <= 0) return;
                LinearLayoutManager lm = (LinearLayoutManager) binding.recyclerViewActivityLog.getLayoutManager();
                if (lm == null) return;
                int visible = lm.getChildCount();
                int total = lm.getItemCount();
                int firstVis = lm.findFirstVisibleItemPosition();
                Boolean isLoading = viewModel.getIsLoading().getValue();
                if ((isLoading == null || !isLoading) && !viewModel.isLastPage() && (visible + firstVis) >= total - 3) {
                    viewModel.loadLogs(false);
                }
            }
        });
    }

    private void setupFilters() {
        UIUtils.setupFilterToggle(binding.btnToggleFilter, binding.layoutFilter,
                binding.etSearchLog, binding.spinnerRoleFilter, binding.spinnerStoreFilter);

        UIUtils.attachSearch(binding.etSearchLog, () ->
                viewModel.setSearchQuery(binding.etSearchLog.getText().toString()));

        String[] roles = {"All Roles", "Admin", "Staff", "Customer"};
        SpinnerUtils.setupStringFilterSpinner(requireContext(), binding.spinnerRoleFilter, roles, () ->
                viewModel.setRoleFilter(binding.spinnerRoleFilter.getSelectedItem() != null
                        ? binding.spinnerRoleFilter.getSelectedItem().toString() : "All Roles"));

        SpinnerUtils.setupFilterSpinner(binding.spinnerStoreFilter, this::onStoreSelected);

        binding.btnStartDate.setOnClickListener(v -> showDatePicker(true));
        binding.btnEndDate.setOnClickListener(v -> showDatePicker(false));
        binding.btnClearDates.setOnClickListener(v -> {
            selectedStartDate = null;
            selectedEndDate = null;
            binding.btnStartDate.setText("Start Date");
            binding.btnEndDate.setText("End Date");
            binding.btnClearDates.setVisibility(View.GONE);
            viewModel.setDateRange(null, null);
        });
    }

    private void showDatePicker(boolean isStart) {
        Calendar cal = Calendar.getInstance();
        new DatePickerDialog(requireContext(), (view, year, month, day) -> {
            String date = String.format("%04d-%02d-%02d", year, month + 1, day);
            String label = String.format("%02d/%02d/%04d", day, month + 1, year);
            if (isStart) {
                selectedStartDate = date;
                binding.btnStartDate.setText(label);
            } else {
                selectedEndDate = date;
                binding.btnEndDate.setText(label);
            }
            binding.btnClearDates.setVisibility(
                    selectedStartDate != null || selectedEndDate != null ? View.VISIBLE : View.GONE);
            viewModel.setDateRange(selectedStartDate, selectedEndDate);
        }, cal.get(Calendar.YEAR), cal.get(Calendar.MONTH), cal.get(Calendar.DAY_OF_MONTH)).show();
    }

    private void onStoreSelected() {
        int pos = binding.spinnerStoreFilter.getSelectedItemPosition();
        Long storeId = (pos > 0 && !storeList.isEmpty()) ? storeList.get(pos - 1).getId() : null;
        viewModel.setStoreFilter(storeId);
    }

    private void observeViewModel() {
        viewModel.getLogs().observe(getViewLifecycleOwner(), list -> {
            logList.clear();
            logList.addAll(list);
            adapter.notifyDataSetChanged();
        });

        viewModel.getStoreOptions().observe(getViewLifecycleOwner(), stores -> {
            storeList = stores;
            SpinnerUtils.populateWhiteSpinner(requireContext(), binding.spinnerStoreFilter,
                    stores, DropdownDTO::getLabel, "All Stores", -1L, DropdownDTO::getId);
        });

        viewModel.getIsLoading().observe(getViewLifecycleOwner(), loading ->
                binding.swipeRefreshActivityLog.setRefreshing(loading));
    }

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