package com.example.myapplication.ui;
import com.example.myapplication.R;
import com.example.myapplication.Utils;
import com.example.myapplication.service.NoteService;
import android.os.Bundle;
import android.widget.Button;
import android.widget.TextView;
import android.text.TextUtils;
import androidx.appcompat.app.AppCompatActivity;

public class NoteDetailUI extends androidx.appcompat.app.AppCompatActivity {
    private int likeCount = 18; // 示例初始点赞数

    @Override
    protected void onCreate(android.os.Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_note_detail);

        int noteId = getIntent().getIntExtra("noteId", 1);

        TextView titleTv = findViewById(R.id.noteTitle);
        TextView metaTv = findViewById(R.id.noteMeta);
        TextView bodyTv = findViewById(R.id.noteBody);
        android.widget.EditText editTitleEt = findViewById(R.id.editNoteTitle);
        android.widget.EditText editBodyEt = findViewById(R.id.editNoteBody);
        android.widget.LinearLayout editActions = findViewById(R.id.editActions);
        android.widget.Button startEditBtn = findViewById(R.id.startEditBtn);
        android.widget.Button saveEditBtn = findViewById(R.id.saveEditBtn);
        android.widget.Button deleteNoteBtn = findViewById(R.id.deleteNoteBtn);
        TextView likeTv = findViewById(R.id.likeCount);
        Button backBtn = findViewById(R.id.backBtn);
        Button likeBtn = findViewById(R.id.likeBtn);
        Button downloadBtn = findViewById(R.id.downloadBtn);
        android.widget.LinearLayout commentList = findViewById(R.id.commentListContainer);
        android.widget.EditText commentInput = findViewById(R.id.commentInput);
        android.widget.Button commentSubmit = findViewById(R.id.commentSubmitBtn);

        // 读取数据库中的真实笔记
        com.example.myapplication.repository.NoteRepository repo =
                new com.example.myapplication.repository.NoteRepository(this);
        com.example.myapplication.domain.Note note = repo.getNoteById(noteId);
        if (note == null) {
            com.example.myapplication.Utils.toast(this, "未找到该笔记");
            finish();
            return;
        }

        titleTv.setText(note.getTitle() != null ? note.getTitle() : "(无标题)");

        String uploader = note.getUploaderId() != null ? note.getUploaderId() : "未知";
        String created = note.getCreated() != null ? note.getCreated() : "";
        String fileSummary = summarizeFile(note.getFilePath());
        metaTv.setText("👤 " + uploader +
                (TextUtils.isEmpty(created) ? "" : "  📅 " + created) +
                (TextUtils.isEmpty(fileSummary) ? "" : "  💾 " + fileSummary));

        // 修复：正文统一使用 content，不再重复声明 bodyTv，也不访问 description/ocrText
        String content = note.getContent();
        bodyTv.setText(content != null && !content.trim().isEmpty() ? content : "暂无内容");

        String currentUser = com.example.myapplication.service.AuthService.getCurrentUser(this);
        boolean isOwner = note.getUploaderId() != null && note.getUploaderId().equals(currentUser);
        editActions.setVisibility(android.view.View.GONE);

        // 数据库读取真实点赞数与用户点赞状态
        int dbLikeCount = note.getLikeCount();
        boolean[] liked = new boolean[] {
                com.example.myapplication.service.LikeService.hasLiked(this, currentUser, noteId)
        };
        likeTv.setText("👍 " + dbLikeCount);
        likeBtn.setText(liked[0] ? "取消点赞" : "点赞");

        backBtn.setOnClickListener(v -> finish());
        likeBtn.setOnClickListener(v -> {
            if (!com.example.myapplication.service.AuthService.isLoggedIn(this)) {
                com.example.myapplication.Utils.toast(this, "请先登录");
                return;
            }
            boolean ok;
            if (liked[0]) {
                ok = com.example.myapplication.service.LikeService.removeLike(this, currentUser, noteId);
                if (ok) liked[0] = false;
            } else {
                ok = com.example.myapplication.service.LikeService.addLike(this, currentUser, noteId);
                if (ok) liked[0] = true;
            }
            com.example.myapplication.domain.Note refreshed = repo.getNoteById(noteId);
            int newCount = refreshed != null ? refreshed.getLikeCount() : 0;
            likeTv.setText("👍 " + newCount);
            likeBtn.setText(liked[0] ? "取消点赞" : "点赞");
        });

        downloadBtn.setOnClickListener(v -> {
            String title = note.getTitle() != null ? note.getTitle() : "未命名笔记";
            String body = note.getContent() != null ? note.getContent() : "";
            StringBuilder sb = new StringBuilder();
            sb.append(title).append("\n");
            if (created != null && !created.isEmpty()) sb.append("时间: ").append(created).append("\n");
            sb.append("作者: ").append(uploader).append("\n\n");
            sb.append(body);
            String filename = sanitizeFileName(title) + ".txt";
            android.net.Uri saved = com.example.myapplication.service.DownloadService.saveTextToDownloadsReturnUri(this, filename, "text/plain", sb.toString());
            if (saved != null) {
                com.example.myapplication.Utils.toast(this, "已保存笔记内容到下载");
                if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.Q) {
                    try {
                        android.content.Intent view = new android.content.Intent(android.content.Intent.ACTION_VIEW);
                        view.setDataAndType(saved, "text/plain");
                        view.addFlags(android.content.Intent.FLAG_GRANT_READ_URI_PERMISSION);
                        startActivity(view);
                    } catch (Exception ignored) {}
                }
                android.content.ContentValues cv = new android.content.ContentValues();
                cv.put("download_count", note.getDownloadCount() + 1);
                new com.example.myapplication.repository.NoteRepository(this).updateNote(noteId, cv);
            } else {
                com.example.myapplication.Utils.toast(this, "保存失败，请检查权限或存储空间");
            }
        });

        java.util.List<com.example.myapplication.domain.Comment> cs = com.example.myapplication.service.CommentService.listComments(this, noteId);
        commentList.removeAllViews();
        if (cs != null && !cs.isEmpty()) {
            for (com.example.myapplication.domain.Comment cm : cs) {
                android.widget.LinearLayout item = new android.widget.LinearLayout(this);
                item.setOrientation(android.widget.LinearLayout.VERTICAL);
                android.widget.TextView meta = new android.widget.TextView(this);
                meta.setText((cm.getUploaderId() == null ? "匿名" : cm.getUploaderId()) + "  " + (cm.getCreatedAt() == null ? "" : cm.getCreatedAt()));
                meta.setTextColor(android.graphics.Color.parseColor("#666666"));
                android.widget.TextView body = new android.widget.TextView(this);
                body.setText(cm.getContent() == null ? "" : cm.getContent());
                body.setTextColor(android.graphics.Color.parseColor("#333333"));
                item.addView(meta);
                item.addView(body);
                item.setPadding(0, 12, 0, 12);
                commentList.addView(item);
            }
        } else {
            android.widget.TextView empty = new android.widget.TextView(this);
            empty.setText("暂无评论，来说两句吧～");
            empty.setTextColor(android.graphics.Color.parseColor("#999999"));
            commentList.addView(empty);
        }

        if (commentSubmit != null) {
            commentSubmit.setOnClickListener(v -> {
                if (!com.example.myapplication.service.AuthService.isLoggedIn(this)) {
                    com.example.myapplication.Utils.toast(this, "请先登录");
                    return;
                }
                String userId2 = com.example.myapplication.service.AuthService.getCurrentUser(this);
                String txt = commentInput != null ? commentInput.getText().toString() : "";
                boolean ok = com.example.myapplication.service.CommentService.addComment(this, userId2, noteId, txt);
                if (!ok) {
                    com.example.myapplication.Utils.toast(this, "评论失败，检查内容长度");
                    return;
                }
                com.example.myapplication.Utils.toast(this, "发布成功");
                if (commentInput != null) commentInput.setText("");
                java.util.List<com.example.myapplication.domain.Comment> cs2 = com.example.myapplication.service.CommentService.listComments(this, noteId);
                commentList.removeAllViews();
                if (cs2 != null && !cs2.isEmpty()) {
                    for (com.example.myapplication.domain.Comment cm : cs2) {
                        android.widget.LinearLayout item = new android.widget.LinearLayout(this);
                        item.setOrientation(android.widget.LinearLayout.VERTICAL);
                        android.widget.TextView meta = new android.widget.TextView(this);
                        meta.setText((cm.getUploaderId() == null ? "匿名" : cm.getUploaderId()) + "  " + (cm.getCreatedAt() == null ? "" : cm.getCreatedAt()));
                        meta.setTextColor(android.graphics.Color.parseColor("#666666"));
                        android.widget.TextView body = new android.widget.TextView(this);
                        body.setText(cm.getContent() == null ? "" : cm.getContent());
                        body.setTextColor(android.graphics.Color.parseColor("#333333"));
                        item.addView(meta);
                        item.addView(body);
                        item.setPadding(0, 12, 0, 12);
                        commentList.addView(item);
                    }
                }
            });
        }
    }

    // 简单的文件信息摘要：扩展名 + 大小（若可读）
    private String summarizeFile(String path) {
        if (path == null || path.isEmpty()) return "";
        String ext = "";
        int dot = path.lastIndexOf('.');
        if (dot >= 0 && dot < path.length() - 1) {
            ext = path.substring(dot + 1).toUpperCase();
        }
        java.io.File f = new java.io.File(path);
        String size = "";
        if (f.exists()) {
            long bytes = f.length();
            if (bytes > 1024 * 1024) {
                size = String.format(java.util.Locale.getDefault(), "%.1fMB", bytes / 1024f / 1024f);
            } else if (bytes > 1024) {
                size = String.format(java.util.Locale.getDefault(), "%.0fKB", bytes / 1024f);
            } else {
                size = bytes + "B";
            }
        }
        if (!ext.isEmpty() && !size.isEmpty()) return ext + ", " + size;
        if (!ext.isEmpty()) return ext;
        return size;
    }

    private String sanitizeFileName(String name) {
        String n = name == null ? "note" : name.trim();
        n = n.replaceAll("[\\/:*?\"<>|]", "_");
        if (n.isEmpty()) n = "note";
        return n;
    }
}