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

public class UserCenterUI extends AppCompatActivity {
    private TextView statUploaded, statLikes, statPoints, majorNameTv, gradeNameTv;
    private EditText usernameEt;

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

        findViewById(R.id.backBtn).setOnClickListener(v -> finish());

        statUploaded = findViewById(R.id.statUploaded);
        statLikes = findViewById(R.id.statLikes);
        statPoints = findViewById(R.id.statPoints);
        majorNameTv = findViewById(R.id.majorNameTv);
        gradeNameTv = findViewById(R.id.gradeNameTv);

        usernameEt = findViewById(R.id.usernameInput);
        

        // 可选：去掉写死示例，统一由 refreshStats() 赋值
        statUploaded.setText("15");
        statLikes.setText("128");

        usernameEt.setText(com.example.myapplication.service.UserService.getUser(this));

        

        // 刷新数据库统计
        refreshStats();
        // 动态渲染我的笔记
        renderMyNotes();

    }

    @Override
    protected void onResume() {
        super.onResume();
        refreshStats();
        renderMyNotes();
    }

    private void refreshStats() {
        String account = com.example.myapplication.service.AuthService.getCurrentUser(this);
        com.example.myapplication.repository.NoteRepository noteRepo =
                new com.example.myapplication.repository.NoteRepository(this);
        java.util.List<com.example.myapplication.domain.Note> myNotes =
                noteRepo.getNotesByUser(account);
        int uploadedCount = myNotes != null ? myNotes.size() : 0;

        int totalLikes = new com.example.myapplication.repository.NoteRepository(this)
                .getTotalLikesByUser(account);

        com.example.myapplication.repository.UserRepository userRepo =
                new com.example.myapplication.repository.UserRepository(this);
        int points = userRepo.getPoints(account);

        com.example.myapplication.domain.User u = userRepo.getUserByAccount(account);
        String majorName = "未设置";
        String gradeText = null;
        if (u != null && u.getMajorId() != null) {
            com.example.myapplication.repository.MajorRepository mr = new com.example.myapplication.repository.MajorRepository(this);
            com.example.myapplication.domain.Major m = mr.getById(u.getMajorId());
            if (m != null && m.getName() != null) majorName = m.getName();
        }

        statUploaded.setText(String.valueOf(uploadedCount));
        statLikes.setText(String.valueOf(totalLikes));
        statPoints.setText(String.valueOf(points));
        if (majorNameTv != null) majorNameTv.setText("专业：" + majorName);
        gradeText = new com.example.myapplication.repository.UserRepository(this).getGradeText(account);
        if (gradeNameTv != null) gradeNameTv.setText("年级：" + (gradeText == null ? "未设置" : gradeText));
    }

    // 动态渲染“我的笔记”
    private void renderMyNotes() {
        android.widget.LinearLayout container = findViewById(R.id.myNotesContainer);
        if (container == null) return;

        container.removeAllViews();

        String account = com.example.myapplication.service.AuthService.getCurrentUser(this);
        com.example.myapplication.repository.NoteRepository repo =
                new com.example.myapplication.repository.NoteRepository(this);
        java.util.List<com.example.myapplication.domain.Note> notes =
                repo.getNotesByUser(account);

        if (notes == null || notes.isEmpty()) {
            android.widget.TextView empty = new android.widget.TextView(this);
            empty.setText("暂无笔记，点击“上传笔记”添加吧～");
            empty.setTextColor(android.graphics.Color.parseColor("#666666"));
            container.addView(empty);
            return;
        }

        float density = getResources().getDisplayMetrics().density;
        int pad = (int) (12 * density);
        int mt = (int) (12 * density);

        com.example.myapplication.repository.LikeRepository likeRepo =
                new com.example.myapplication.repository.LikeRepository(this);

        for (com.example.myapplication.domain.Note n : notes) {
            android.widget.LinearLayout item = new android.widget.LinearLayout(this);
            item.setOrientation(android.widget.LinearLayout.VERTICAL);
            item.setBackgroundResource(R.drawable.card_background);
            item.setPadding(pad, pad, pad, pad);

            android.widget.LinearLayout.LayoutParams lp =
                    new android.widget.LinearLayout.LayoutParams(
                            android.widget.LinearLayout.LayoutParams.MATCH_PARENT,
                            android.widget.LinearLayout.LayoutParams.WRAP_CONTENT);
            lp.setMargins(0, mt, 0, 0);
            item.setLayoutParams(lp);
            item.setElevation(4f);

            android.widget.TextView titleTv = new android.widget.TextView(this);
            titleTv.setText(n.getTitle() != null ? n.getTitle() : "(无标题)");
            titleTv.setTextColor(getResources().getColor(R.color.text_primary));
            titleTv.setTypeface(android.graphics.Typeface.DEFAULT_BOLD);
            titleTv.setTextSize(16);

            int likes = n.getLikeCount();
            String created = n.getCreated() != null ? n.getCreated() : "";
            android.widget.TextView metaTv = new android.widget.TextView(this);
            metaTv.setText((TextUtils.isEmpty(created) ? "📅 未知" : "📅 " + created) + "  👍 " + likes);
            metaTv.setTextColor(getResources().getColor(R.color.text_secondary));
            metaTv.setTextSize(14);

            item.addView(titleTv);
            item.addView(metaTv);

            android.widget.LinearLayout actions = new android.widget.LinearLayout(this);
            actions.setOrientation(android.widget.LinearLayout.HORIZONTAL);
            android.widget.LinearLayout.LayoutParams alp = new android.widget.LinearLayout.LayoutParams(
                    android.widget.LinearLayout.LayoutParams.WRAP_CONTENT,
                    android.widget.LinearLayout.LayoutParams.WRAP_CONTENT
            );
            alp.topMargin = (int) (12 * density);
            actions.setLayoutParams(alp);

            android.widget.Button viewBtn = new android.widget.Button(this);
            viewBtn.setText("查看");
            viewBtn.setAllCaps(false);
            viewBtn.setPadding(pad, pad / 2, pad, pad / 2);
            viewBtn.setTextColor(android.graphics.Color.WHITE);
            androidx.core.view.ViewCompat.setBackgroundTintList(viewBtn,
                    android.content.res.ColorStateList.valueOf(getResources().getColor(R.color.primary)));

            android.widget.Button editBtn = new android.widget.Button(this);
            editBtn.setText("编辑");
            editBtn.setAllCaps(false);
            editBtn.setPadding(pad, pad / 2, pad, pad / 2);
            editBtn.setTextColor(android.graphics.Color.WHITE);
            androidx.core.view.ViewCompat.setBackgroundTintList(editBtn,
                    android.content.res.ColorStateList.valueOf(getResources().getColor(R.color.success)));

            android.widget.Button delBtn = new android.widget.Button(this);
            delBtn.setText("删除");
            delBtn.setAllCaps(false);
            delBtn.setPadding(pad, pad / 2, pad, pad / 2);
            delBtn.setTextColor(android.graphics.Color.WHITE);
            androidx.core.view.ViewCompat.setBackgroundTintList(delBtn,
                    android.content.res.ColorStateList.valueOf(getResources().getColor(R.color.danger)));

            android.widget.LinearLayout.LayoutParams btnLp = new android.widget.LinearLayout.LayoutParams(
                    android.widget.LinearLayout.LayoutParams.WRAP_CONTENT,
                    android.widget.LinearLayout.LayoutParams.WRAP_CONTENT
            );
            actions.addView(viewBtn, btnLp);
            android.widget.Space sp1 = new android.widget.Space(this);
            actions.addView(sp1, new android.widget.LinearLayout.LayoutParams((int)(8 * density), 1));
            actions.addView(editBtn, btnLp);
            android.widget.Space sp2 = new android.widget.Space(this);
            actions.addView(sp2, new android.widget.LinearLayout.LayoutParams((int)(8 * density), 1));
            actions.addView(delBtn, btnLp);

            viewBtn.setOnClickListener(v -> {
                com.example.myapplication.service.NoteService.setCurrentNoteId(this, (int) n.getId());
                android.content.Intent intent = new android.content.Intent(this, com.example.myapplication.ui.NoteDetailUI.class);
                intent.putExtra("noteId", (int) n.getId());
                startActivity(intent);
            });

            editBtn.setOnClickListener(v -> {
                com.example.myapplication.service.NoteService.setCurrentNoteId(this, (int) n.getId());
                android.content.Intent intent = new android.content.Intent(this, com.example.myapplication.ui.NoteEditUI.class);
                startActivity(intent);
            });

            delBtn.setOnClickListener(v -> {
                android.app.AlertDialog.Builder b = new android.app.AlertDialog.Builder(this);
                b.setTitle("删除笔记");
                b.setMessage("确定要删除这条笔记吗？");
                b.setPositiveButton("删除", (d, which) -> {
                    boolean okDel = new com.example.myapplication.repository.NoteRepository(this).deleteNote(n.getId());
                    if (okDel) {
                        com.example.myapplication.Utils.toast(this, "已删除");
                        refreshStats();
                        renderMyNotes();
                    } else {
                        com.example.myapplication.Utils.toast(this, "删除失败");
                    }
                });
                b.setNegativeButton("取消", (d, which) -> {});
                b.show();
            });

            item.addView(actions);

            container.addView(item);
        }
    }
}