package com.example.petstoremobile.adapters;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.example.petstoremobile.R;
import com.example.petstoremobile.dtos.ActivityLogDTO;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Locale;

public class ActivityLogAdapter extends RecyclerView.Adapter<ActivityLogAdapter.ViewHolder> {

    private static final String SEPARATOR = "  |  ";
    private static final SimpleDateFormat INPUT_FORMAT = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss", Locale.getDefault());
    private static final SimpleDateFormat OUTPUT_FORMAT = new SimpleDateFormat("MMM d, HH:mm", Locale.getDefault());

    private final List<ActivityLogDTO> items;

    public ActivityLogAdapter(List<ActivityLogDTO> items) {
        this.items = items;
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.item_activity_log, parent, false);
        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
        ActivityLogDTO log = items.get(position);

        String activity = log.getActivity() != null ? log.getActivity() : "";
        int separatorIndex = activity.indexOf(SEPARATOR);
        if (separatorIndex >= 0) {
            holder.tvActivity.setText(activity.substring(0, separatorIndex).trim());
            holder.tvTechnical.setText(activity.substring(separatorIndex + SEPARATOR.length()).trim());
            holder.tvTechnical.setVisibility(View.VISIBLE);
        } else {
            holder.tvActivity.setText(activity);
            holder.tvTechnical.setVisibility(View.GONE);
        }

        String fullName = firstNonBlank(log.getFullName(), log.getFullNameSnapshot(), "Unknown");
        String username = firstNonBlank(log.getUsername(), log.getUsernameSnapshot(), "");
        holder.tvUser.setText(username.isEmpty() ? fullName : fullName + " (" + username + ")");

        String role = firstNonBlank(log.getRole(), log.getRoleSnapshot(), "");
        String store = firstNonBlank(log.getStoreName(), log.getStoreNameSnapshot(), "");
        if (!role.isEmpty() && !store.isEmpty()) {
            holder.tvMeta.setText(store + " · " + formatRole(role));
        } else if (!role.isEmpty()) {
            holder.tvMeta.setText(formatRole(role));
        } else if (!store.isEmpty()) {
            holder.tvMeta.setText(store);
        } else {
            holder.tvMeta.setText("");
        }

        holder.tvTimestamp.setText(formatTimestamp(log.getLogTimestamp()));
    }

    @Override
    public int getItemCount() { return items.size(); }

    private String formatTimestamp(String raw) {
        if (raw == null) return "";
        try {
            String normalized = raw.length() > 19 ? raw.substring(0, 19) : raw;
            Date date = INPUT_FORMAT.parse(normalized);
            return date != null ? OUTPUT_FORMAT.format(date) : raw.substring(0, Math.min(16, raw.length())).replace("T", " ");
        } catch (ParseException e) {
            return raw.length() >= 16 ? raw.substring(0, 16).replace("T", " ") : raw;
        }
    }

    private String formatRole(String role) {
        if (role == null) return "";
        switch (role.toUpperCase(Locale.ROOT)) {
            case "ADMIN":    return "Admin";
            case "STAFF":    return "Staff";
            case "CUSTOMER": return "Customer";
            default:         return role;
        }
    }

    private String firstNonBlank(String... values) {
        for (String v : values) {
            if (v != null && !v.isBlank()) return v;
        }
        return "";
    }

    public static class ViewHolder extends RecyclerView.ViewHolder {
        TextView tvActivity, tvTechnical, tvUser, tvMeta, tvTimestamp;

        public ViewHolder(@NonNull View itemView) {
            super(itemView);
            tvActivity  = itemView.findViewById(R.id.tvLogActivity);
            tvTechnical = itemView.findViewById(R.id.tvLogTechnical);
            tvUser      = itemView.findViewById(R.id.tvLogUser);
            tvMeta      = itemView.findViewById(R.id.tvLogMeta);
            tvTimestamp = itemView.findViewById(R.id.tvLogTimestamp);
        }
    }
}
