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

public class MainUI extends AppCompatActivity {
    private SharedPreferences prefs;
    private int recommendedOffset = 0;
    private final int recommendedPageSize = 10;
    private int recommendedFilterMode = 0; // 0:全部 1:同专业 2:同年级

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        // 全局初始化数据库连接（可选，但推荐）
        try {
            com.example.myapplication.repository.DatabaseManager.init(getApplicationContext());
        } catch (Exception e) {
            android.util.Log.e("MainUI", "Database init failed", e);
        }
        prefs = getSharedPreferences("app_prefs", MODE_PRIVATE);

        boolean isLoggedIn = AuthService.isLoggedIn(this);
        if (!isLoggedIn) {
            Utils.toast(this, "请先登录");
            startActivity(new Intent(this, LoginUI.class));
            finish();
            return;
        }

        String currentUser = AuthService.getCurrentUser(this);
        TextView welcomeTv = findViewById(R.id.welcomeText);
        String majorName = null;
        String gradeText = null;
        com.example.myapplication.repository.UserRepository ur0 = new com.example.myapplication.repository.UserRepository(this);
        com.example.myapplication.domain.User u0 = ur0.getUserByAccount(currentUser);
        gradeText = ur0.getGradeText(currentUser);
        if (u0 != null && u0.getMajorId() != null) {
            com.example.myapplication.repository.MajorRepository mr0 = new com.example.myapplication.repository.MajorRepository(this);
            com.example.myapplication.domain.Major m0 = mr0.getById(u0.getMajorId());
            if (m0 != null) majorName = m0.getName();
        }
        String extra = "";
        if (majorName != null) extra += "（专业：" + majorName + ")";
        if (gradeText != null && !gradeText.isEmpty()) extra += (extra.isEmpty() ? "（" : " ") + "年级：" + gradeText + (extra.contains("（") ? "" : ")");
        welcomeTv.setText("欢迎，" + currentUser + (extra.isEmpty() ? "" : " " + extra));

        Button logoutBtn = findViewById(R.id.logoutBtn);
        Button searchBtn = findViewById(R.id.searchBtn);
        Button uploadBtn = findViewById(R.id.uploadBtn);
        Button userCenterBtn = findViewById(R.id.userCenterBtn);

        searchBtn.setOnClickListener(v -> startActivity(new Intent(this, SearchUI.class)));
        uploadBtn.setOnClickListener(v -> startActivity(new Intent(this, UploadUI.class)));
        userCenterBtn.setOnClickListener(v -> startActivity(new Intent(this, UserCenterUI.class)));

        logoutBtn.setOnClickListener(v -> {
            AuthService.logout(this);
            Utils.toast(this, "已退出登录");
            startActivity(new Intent(this, LoginUI.class));
            finish();
        });

        

        // 动态渲染
        renderRecommendedNotes(true);
        renderLatestNotes();
    }

    @Override
    protected void onResume() {
        super.onResume();
        renderRecommendedNotes(false);
        renderLatestNotes();
    }

    private void renderLatestNotes() {
        android.widget.LinearLayout container = findViewById(R.id.latestNotesContainer);
        if (container == null) return;

        container.removeAllViews();

        com.example.myapplication.repository.NoteRepository repo =
                new com.example.myapplication.repository.NoteRepository(this);
        java.util.List<com.example.myapplication.domain.Note> notes = repo.getRecentNotes(20);

        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;
        }

        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);
            int pad = (int) (20 * getResources().getDisplayMetrics().density);
            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.topMargin = (int) (12 * getResources().getDisplayMetrics().density);
            item.setLayoutParams(lp);
            item.setElevation(4f);

            // 标题
            android.widget.TextView title = new android.widget.TextView(this);
            title.setText(n.getTitle() != null ? n.getTitle() : "(无标题)");
            title.setTextColor(getResources().getColor(R.color.text_primary));
            title.setTextSize(18);
            title.setTypeface(android.graphics.Typeface.DEFAULT_BOLD);
            title.setLayoutParams(new android.widget.LinearLayout.LayoutParams(
                    android.widget.LinearLayout.LayoutParams.MATCH_PARENT,
                    android.widget.LinearLayout.LayoutParams.WRAP_CONTENT));

            // 元信息（上传者、时间、下载数/点赞数占位）
            android.widget.TextView meta = new android.widget.TextView(this);
            String uploader = n.getUploaderId() != null ? n.getUploaderId() : "未知";
            String created = n.getCreated() != null ? n.getCreated() : "";
            int likes = n.getLikeCount();
            meta.setText("上传者：" + uploader + (TextUtils.isEmpty(created) ? "" : " | " + created) + " | 👍 " + likes);
            meta.setTextColor(getResources().getColor(R.color.text_secondary));
            meta.setTextSize(14);
            meta.setLayoutParams(new android.widget.LinearLayout.LayoutParams(
                    android.widget.LinearLayout.LayoutParams.MATCH_PARENT,
                    android.widget.LinearLayout.LayoutParams.WRAP_CONTENT));

            // 描述摘要
            android.widget.TextView desc = new android.widget.TextView(this);
            String d = n.getContent();
            if (d == null) d = "";
            if (d.length() > 80) d = d.substring(0, 80) + "...";
            desc.setText(TextUtils.isEmpty(d) ? "暂无内容" : d);
            desc.setTextColor(getResources().getColor(R.color.text_secondary));
            desc.setTextSize(15);
            desc.setLineSpacing(0, 1.4f);
            desc.setLayoutParams(new android.widget.LinearLayout.LayoutParams(
                    android.widget.LinearLayout.LayoutParams.MATCH_PARENT,
                    android.widget.LinearLayout.LayoutParams.WRAP_CONTENT));

            item.addView(title);
            item.addView(meta);
            item.addView(desc);

            item.setOnClickListener(v -> openNote((int) n.getId()));
            container.addView(item);
        }
    }

    private void openNote(int id) {
        NoteService.setCurrentNoteId(this, id);
        Intent intent = new Intent(this, NoteDetailUI.class);
        intent.putExtra("noteId", id);
        startActivity(intent);
    }

    private void renderRecommendedNotes(boolean reset) {
        android.widget.LinearLayout container = findViewById(R.id.recommendedNotesContainer);
        android.widget.Button refreshBtn = findViewById(R.id.recommendedRefreshBtn);
        if (container == null) return;
        if (refreshBtn != null) refreshBtn.setOnClickListener(v -> renderRecommendedNotes(true));

        if (reset) {
            recommendedOffset = 0;
            container.removeAllViews();
        }

        String currentUserId = AuthService.getCurrentUser(this);
        com.example.myapplication.repository.UserRepository ur = new com.example.myapplication.repository.UserRepository(this);
        com.example.myapplication.domain.User u = ur.getUserByAccount(currentUserId);
        Long majorId2 = u != null ? u.getMajorId() : null;
        String gradeText2 = ur.getGradeText(currentUserId);
        String majorName2 = null;
        if (majorId2 != null) {
            com.example.myapplication.repository.MajorRepository mr2 = new com.example.myapplication.repository.MajorRepository(this);
            com.example.myapplication.domain.Major m2 = mr2.getById(majorId2);
            if (m2 != null) majorName2 = m2.getName();
        }

        if (reset) {
            com.example.myapplication.repository.NoteRepository.clearRecommendedCacheFor(majorId2, gradeText2);
        }
        com.example.myapplication.repository.NoteRepository repo = new com.example.myapplication.repository.NoteRepository(this);
        java.util.List<com.example.myapplication.domain.Note> notes = repo.getRecommendedNotes(majorId2, gradeText2, recommendedPageSize, recommendedOffset);

        if (notes == null || notes.isEmpty()) {
            if (recommendedOffset == 0) {
                android.widget.TextView empty = new android.widget.TextView(this);
                empty.setText("暂无推荐笔记，完善个人信息或上传吧～");
                empty.setTextColor(android.graphics.Color.parseColor("#666666"));
                container.addView(empty);
            }
            return;
        }

        for (com.example.myapplication.domain.Note n : notes) {
            String pubMajorName = null;
            String pubGradeText = null;
            if (n.getUploaderId() != null) {
                com.example.myapplication.repository.UserRepository urp = new com.example.myapplication.repository.UserRepository(this);
                com.example.myapplication.domain.User pu = urp.getUserByAccount(n.getUploaderId());
                if (pu != null && pu.getMajorId() != null) {
                    com.example.myapplication.repository.MajorRepository mrp = new com.example.myapplication.repository.MajorRepository(this);
                    com.example.myapplication.domain.Major mp = mrp.getById(pu.getMajorId());
                    if (mp != null) pubMajorName = mp.getName();
                }
                pubGradeText = urp.getGradeText(n.getUploaderId());
            }
            String relTag = buildRelevanceTagText(majorName2, gradeText2, pubMajorName, pubGradeText);
            if (relTag == null) relTag = "";
            // 客户端过滤
            if (recommendedFilterMode == 1 && (relTag == null || !relTag.contains("同专业"))) continue;
            if (recommendedFilterMode == 2 && (relTag == null || !relTag.contains("同年级"))) continue;
            android.widget.LinearLayout item = new android.widget.LinearLayout(this);
            item.setOrientation(android.widget.LinearLayout.VERTICAL);
            item.setBackgroundResource(R.drawable.card_background);
            int pad = (int) (20 * getResources().getDisplayMetrics().density);
            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.topMargin = (int) (12 * getResources().getDisplayMetrics().density);
            item.setLayoutParams(lp);
            item.setElevation(4f);

            // 标题
            android.widget.TextView title = new android.widget.TextView(this);
            title.setText(n.getTitle() != null ? n.getTitle() : "(无标题)");
            title.setTextColor(getResources().getColor(R.color.text_primary));
            title.setTextSize(18);
            title.setTypeface(android.graphics.Typeface.DEFAULT_BOLD);
            title.setLayoutParams(new android.widget.LinearLayout.LayoutParams(
                    android.widget.LinearLayout.LayoutParams.MATCH_PARENT,
                    android.widget.LinearLayout.LayoutParams.WRAP_CONTENT));

            // 元信息（相关性标签）
            android.widget.TextView meta = new android.widget.TextView(this);
            
            String created = n.getCreated() != null ? n.getCreated() : "";
            int likes2 = n.getLikeCount();
            meta.setText((TextUtils.isEmpty(relTag) ? "" : (relTag + " | ")) + (TextUtils.isEmpty(created) ? "" : (created)) + " | 👍 " + likes2);
            meta.setTextColor(getResources().getColor(R.color.text_secondary));
            meta.setTextSize(14);
            meta.setLayoutParams(new android.widget.LinearLayout.LayoutParams(
                    android.widget.LinearLayout.LayoutParams.MATCH_PARENT,
                    android.widget.LinearLayout.LayoutParams.WRAP_CONTENT));

            // 描述摘要
            android.widget.TextView desc = new android.widget.TextView(this);
            String d = n.getContent();
            if (d == null) d = "";
            if (d.length() > 80) d = d.substring(0, 80) + "...";
            desc.setText(TextUtils.isEmpty(d) ? "暂无内容" : d);
            desc.setTextColor(getResources().getColor(R.color.text_secondary));
            desc.setTextSize(15);
            desc.setLineSpacing(0, 1.4f);
            desc.setLayoutParams(new android.widget.LinearLayout.LayoutParams(
                    android.widget.LinearLayout.LayoutParams.MATCH_PARENT,
                    android.widget.LinearLayout.LayoutParams.WRAP_CONTENT));

            item.addView(title);
            item.addView(meta);
            item.addView(desc);

            item.setOnClickListener(v -> openNote((int) n.getId()));
            container.addView(item);
        }

        recommendedOffset += notes.size();
    }

    private String buildRelevanceTagText(String userMajor, String userGradeText, String pubMajor, String pubGradeText) {
        java.util.List<String> tags = new java.util.ArrayList<>();
        if (userMajor != null && pubMajor != null && userMajor.equals(pubMajor)) tags.add("同专业");
        if (userGradeText != null && pubGradeText != null && userGradeText.equals(pubGradeText)) tags.add("同年级");
        if (tags == null || tags.isEmpty()) return "";
        StringBuilder sb = new StringBuilder();
        for (String t : tags) {
            if (sb.length() > 0) sb.append("、");
            sb.append(t);
        }
        return sb.toString();
    }
}