/*
 * Copyright (c) 2025, Modern Notes Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *        http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package net.micode.notes.ui;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.TextView;

import net.micode.notes.R;
import net.micode.notes.data.NotesRepository;
import net.micode.notes.tool.ResourceParser;
import net.micode.notes.tool.ResourceParser.NoteItemBgResources;

import android.util.Log;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;

/**
 * 便签列表适配器
 * <p>
 * 将 List<NoteInfo> 数据绑定到 ListView
 * 支持便签显示、选中状态、图标显示
 * </p>
 * <p>
 * 现代化实现：使用 ViewHolder 模式优化性能
 * </p>
 */
public class NoteInfoAdapter extends BaseAdapter {
    private LayoutInflater inflater;
    private List<NotesRepository.NoteInfo> notes;
    private HashSet<Long> selectedIds;
    private OnNoteButtonClickListener buttonClickListener;
    private OnNoteItemClickListener itemClickListener;
    private OnNoteItemLongClickListener itemLongClickListener;
    
    /**
     * 便签按钮点击事件回调接口
     */
    public interface OnNoteButtonClickListener {
        /**
         * 编辑按钮点击事件
         *
         * @param position 位置
         * @param noteId   便签 ID
         */
        void onEditButtonClick(int position, long noteId);
    }

    /**
     * 便签项点击事件回调接口
     */
    public interface OnNoteItemClickListener {
        void onNoteItemClick(int position, long noteId);
    }

    /**
     * 便签项长按事件回调接口
     */
    public interface OnNoteItemLongClickListener {
        void onNoteItemLongClick(int position, long noteId);
    }
    
    /**
     * 构造函数
     *
     * @param context 上下文
     */
    public NoteInfoAdapter(Context context) {
        this.inflater = LayoutInflater.from(context);
        this.notes = new ArrayList<>();
        this.selectedIds = new HashSet<>();
    }
    
    /**
     * 设置便签列表
     *
     * @param notes 便签列表
     */
    public void setNotes(List<NotesRepository.NoteInfo> notes) {
        this.notes = notes != null ? notes : new ArrayList<>();
        notifyDataSetChanged();
    }
    
    /**
     * 设置选中的便签 ID 集合
     * <p>
     * 用于多选模式同步，让 ViewModel 更新 selectedNoteIds 后，
     * Adapter 的 selectedIds 也能同步更新
     * </p>
     *
     * @param selectedIds 选中的便签 ID 集合
     */
    public void setSelectedIds(HashSet<Long> selectedIds) {
        if (selectedIds != null && selectedIds != this.selectedIds) {
            this.selectedIds.clear();
            this.selectedIds.addAll(selectedIds);
            notifyDataSetChanged();
        } else if (selectedIds == null) {
            this.selectedIds.clear();
            notifyDataSetChanged();
        }
    }

    /**
     * 设置选中的便签 ID 列表
     * <p>
     * 重载方法，接受 List<Long> 参数，在内部转换为 HashSet
     * </p>
     *
     * @param selectedIds 选中的便签 ID 列表
     */
    public void setSelectedIds(List<Long> selectedIds) {
        if (selectedIds != null && !selectedIds.isEmpty()) {
            this.selectedIds.clear();
            this.selectedIds.addAll(selectedIds);
            notifyDataSetChanged();
        } else {
            this.selectedIds.clear();
            notifyDataSetChanged();
        }
    }

    /**
     * 获取选中的便签 ID
     *
     * @return 选中的便签 ID 集合
     */
    public HashSet<Long> getSelectedIds() {
        return selectedIds;
    }
    
    /**
     * 切换选中状态
     *
     * @param noteId 便签 ID
     */
    public void toggleSelection(long noteId) {
        if (selectedIds.contains(noteId)) {
            selectedIds.remove(noteId);
        } else {
            selectedIds.add(noteId);
        }
        notifyDataSetChanged();
    }
    
    /**
     * 设置按钮点击监听器
     *
     * @param listener 监听器
     */
    public void setOnNoteButtonClickListener(OnNoteButtonClickListener listener) {
        this.buttonClickListener = listener;
    }

    public void setOnNoteItemClickListener(OnNoteItemClickListener listener) {
        this.itemClickListener = listener;
    }

    public void setOnNoteItemLongClickListener(OnNoteItemLongClickListener listener) {
        this.itemLongClickListener = listener;
    }
    
    @Override
    public int getCount() {
        return notes.size();
    }
    
    @Override
    public Object getItem(int position) {
        return position >= 0 && position < notes.size() ? notes.get(position) : null;
    }
    
    @Override
    public long getItemId(int position) {
        NotesRepository.NoteInfo note = (NotesRepository.NoteInfo) getItem(position);
        return note != null ? note.getId() : -1;
    }
    
    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        Log.d("NoteInfoAdapter", "getView called, position: " + position + ", convertView: " + (convertView != null ? "REUSED" : "NEW"));
        ViewHolder holder;
        
        if (convertView == null) {
            convertView = inflater.inflate(R.layout.note_item, parent, false);
            holder = new ViewHolder();
            holder.title = convertView.findViewById(R.id.tv_title);
            holder.time = convertView.findViewById(R.id.tv_time);
            holder.checkBox = convertView.findViewById(android.R.id.checkbox);
            holder.pinnedIcon = convertView.findViewById(R.id.iv_pinned_icon);
            convertView.setTag(holder);
            
            convertView.setOnClickListener(v -> {
                Log.d("NoteInfoAdapter", "===== onClick TRIGGERED =====");
                ViewHolder currentHolder = (ViewHolder) v.getTag();
                if (currentHolder != null && itemClickListener != null) {
                    Log.d("NoteInfoAdapter", "Calling itemClickListener");
                    NotesRepository.NoteInfo note = (NotesRepository.NoteInfo) getItem(currentHolder.position);
                    if (note != null) {
                        itemClickListener.onNoteItemClick(currentHolder.position, note.getId());
                    }
                }
                Log.d("NoteInfoAdapter", "===== onClick END =====");
            });
            
            convertView.setOnLongClickListener(v -> {
                Log.d("NoteInfoAdapter", "===== setOnLongClickListener TRIGGERED =====");
                Log.d("NoteInfoAdapter", "Event triggered on view: " + v.getClass().getSimpleName());
                ViewHolder currentHolder = (ViewHolder) v.getTag();
                if (currentHolder != null && itemLongClickListener != null) {
                    Log.d("NoteInfoAdapter", "Calling itemLongClickListener");
                    itemLongClickListener.onNoteItemLongClick(currentHolder.position, currentHolder.position < notes.size() ? notes.get(currentHolder.position).getId() : -1);
                } else {
                    Log.e("NoteInfoAdapter", "itemLongClickListener is NULL!");
                }
                Log.d("NoteInfoAdapter", "===== setOnLongClickListener END =====");
                return true;
            });
        } else {
            holder = (ViewHolder) convertView.getTag();
        }
        
        holder.position = position;
        
        NotesRepository.NoteInfo note = (NotesRepository.NoteInfo) getItem(position);
        if (note != null) {
            String title = note.snippet;
            if (title == null || title.trim().isEmpty()) {
                title = "无标题";
            }
            holder.title.setText(title);
            
            holder.time.setText(formatDate(note.modifiedDate));
            
            int bgResId;
            int totalCount = getCount();
            int bgColorId = note.bgColorId;
            
            if (totalCount == 1) {
                bgResId = NoteItemBgResources.getNoteBgSingleRes(bgColorId);
            } else if (position == 0) {
                bgResId = NoteItemBgResources.getNoteBgFirstRes(bgColorId);
            } else if (position == totalCount - 1) {
                bgResId = NoteItemBgResources.getNoteBgLastRes(bgColorId);
            } else {
                bgResId = NoteItemBgResources.getNoteBgNormalRes(bgColorId);
            }
            
            convertView.setBackgroundResource(bgResId);

            if (selectedIds.contains(note.getId())) {
                convertView.setActivated(true);
            } else {
                convertView.setActivated(false);
            }

            Log.d("NoteInfoAdapter", "===== Setting checkbox visibility =====");
            Log.d("NoteInfoAdapter", "selectedIds.isEmpty(): " + selectedIds.isEmpty());
            Log.d("NoteInfoAdapter", "selectedIds.size(): " + selectedIds.size());
            Log.d("NoteInfoAdapter", "selectedIds contains note " + note.getId() + ": " + selectedIds.contains(note.getId()));

            if (!selectedIds.isEmpty()) {
                Log.d("NoteInfoAdapter", "Setting checkbox VISIBLE");
                holder.checkBox.setVisibility(View.VISIBLE);
                holder.checkBox.setChecked(selectedIds.contains(note.getId()));
                holder.checkBox.setClickable(false);
            } else {
                Log.d("NoteInfoAdapter", "Setting checkbox GONE");
                holder.checkBox.setVisibility(View.GONE);
            }
            Log.d("NoteInfoAdapter", "===== Checkbox visibility set =====");

            if (note.isPinned) {
                holder.pinnedIcon.setVisibility(View.VISIBLE);
            } else {
                holder.pinnedIcon.setVisibility(View.GONE);
            }
        }

        return convertView;
    }
    
    /**
     * 格式化日期
     *
     * @param timestamp 时间戳
     * @return 格式化后的日期字符串
     */
    private String formatDate(long timestamp) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.getDefault());
        return sdf.format(new Date(timestamp));
    }
    
    /**
     * ViewHolder 模式：优化 ListView 性能
     */
    private static class ViewHolder {
        TextView title;
        TextView time;
        CheckBox checkBox;
        ImageView pinnedIcon;
        int position;
    }
}
