package com.example.myapplication;

import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.OpenableColumns;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.appcompat.app.AppCompatActivity;

import com.google.android.material.card.MaterialCardView;
import com.google.android.material.textfield.TextInputEditText;

import com.example.myapplication.domain.Chapter;
// import com.example.myapplication.domain.ClassificationResult; // 使用ClassificationService.Result替代
import com.example.myapplication.domain.Course;
import com.example.myapplication.domain.Note;
import com.example.myapplication.repository.CourseRepository;
import com.example.myapplication.repository.NoteRepository;
import com.example.myapplication.service.ClassificationService;
import com.example.myapplication.service.OCRService;
import com.example.myapplication.service.ClassificationService.Result;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;

public class NoteUploadActivity extends AppCompatActivity {
    private static final String TAG = "NoteUploadActivity";
    private static final int PICK_FILE_REQUEST = 1;
    
    // UI组件
    private Button btnSelectFile, btnUpload, btnCancel, btnAcceptClassification, btnRejectClassification;
    private TextInputEditText etNoteTitle, etNoteDescription;
    private TextView tvSelectedFile, tvClassificationResult, tvClassificationConfidence;
    private MaterialCardView cardClassification, cardManualSelection;
    private Spinner spinnerCourse, spinnerChapter;
    private ProgressBar progressBar;
    
    // 数据存储
    private CourseRepository courseRepository;
    private NoteRepository noteRepository;
    private ClassificationService classificationService;
    // 状态变量
    private Uri selectedFileUri;
    private String savedFilePath;
    private ClassificationService.Result currentClassification;
    private List<Course> availableCourses;
    private List<Chapter> availableChapters;
    
    // Activity结果启动器
    private ActivityResultLauncher<Intent> filePickerLauncher;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_note_upload);
        
        initViews();
        initRepositories();
        setupListeners();
        setupFilePicker();
        loadAvailableCourses();
    }
    
    private void initViews() {
        btnSelectFile = findViewById(R.id.btn_select_file);
        btnUpload = findViewById(R.id.btn_upload);
        btnCancel = findViewById(R.id.btn_cancel);
        btnAcceptClassification = findViewById(R.id.btn_accept_classification);
        btnRejectClassification = findViewById(R.id.btn_reject_classification);
        
        etNoteTitle = findViewById(R.id.et_note_title);
        etNoteDescription = findViewById(R.id.et_note_description);
        
        tvSelectedFile = findViewById(R.id.tv_selected_file);
        tvClassificationResult = findViewById(R.id.tv_classification_result);
        tvClassificationConfidence = findViewById(R.id.tv_classification_confidence);
        
        cardClassification = findViewById(R.id.card_classification);
        cardManualSelection = findViewById(R.id.card_manual_selection);
        
        spinnerCourse = findViewById(R.id.spinner_course);
        spinnerChapter = findViewById(R.id.spinner_chapter);
        
        progressBar = findViewById(R.id.progress_bar);
    }
    
    private void initRepositories() {
        courseRepository = new CourseRepository(this);
        noteRepository = new NoteRepository(this);
        classificationService = new ClassificationService(this);
        // OCRService是静态工具类，不需要实例化
    }
    
    private void setupListeners() {
        btnSelectFile.setOnClickListener(v -> openFilePicker());
        btnUpload.setOnClickListener(v -> uploadNote());
        btnCancel.setOnClickListener(v -> finish());
        btnAcceptClassification.setOnClickListener(v -> acceptClassification());
        btnRejectClassification.setOnClickListener(v -> showManualSelection());
        
        spinnerCourse.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                if (position >= 0 && position < availableCourses.size()) {
                    Course selectedCourse = availableCourses.get(position);
        loadChaptersForCourse(String.valueOf(selectedCourse.getId()));
                }
            }
            
            @Override
            public void onNothingSelected(AdapterView<?> parent) {
                // Do nothing
            }
        });
    }
    
    private void setupFilePicker() {
        filePickerLauncher = registerForActivityResult(
            new ActivityResultContracts.StartActivityForResult(),
            result -> {
                if (result.getResultCode() == Activity.RESULT_OK && result.getData() != null) {
                    Uri uri = result.getData().getData();
                    if (uri != null) {
                        handleFileSelection(uri);
                    }
                }
            }
        );
    }
    
    private void openFilePicker() {
        Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
        intent.setType("*/*");
        String[] mimeTypes = {"image/*", "application/pdf"};
        intent.putExtra(Intent.EXTRA_MIME_TYPES, mimeTypes);
        intent.addCategory(Intent.CATEGORY_OPENABLE);
        
        Intent chooser = Intent.createChooser(intent, "选择文件");
        filePickerLauncher.launch(chooser);
    }
    
    private void handleFileSelection(Uri uri) {
        selectedFileUri = uri;
        String fileName = getFileName(uri);
        tvSelectedFile.setText("已选择: " + fileName);
        
        // 保存文件到应用目录
        savedFilePath = saveFileToAppDirectory(uri);
        if (savedFilePath == null) {
            Toast.makeText(this, "文件保存失败", Toast.LENGTH_SHORT).show();
        }
    }
    
    private String getFileName(Uri uri) {
        String result = null;
        if (uri.getScheme().equals("content")) {
            Cursor cursor = getContentResolver().query(uri, null, null, null, null);
            try {
                if (cursor != null && cursor.moveToFirst()) {
                    int nameIndex = cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME);
                    if (nameIndex >= 0) {
                        result = cursor.getString(nameIndex);
                    }
                }
            } finally {
                if (cursor != null) {
                    cursor.close();
                }
            }
        }
        if (result == null) {
            result = uri.getPath();
            int cut = result.lastIndexOf('/');
            if (cut != -1) {
                result = result.substring(cut + 1);
            }
        }
        return result;
    }
    
    private String saveFileToAppDirectory(Uri uri) {
        try {
            InputStream inputStream = getContentResolver().openInputStream(uri);
            if (inputStream == null) return null;
            
            String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault()).format(new Date());
            String fileName = "note_" + timeStamp + getFileExtension(uri);
            File outputFile = new File(getFilesDir(), fileName);
            
            OutputStream outputStream = new FileOutputStream(outputFile);
            byte[] buffer = new byte[4096];
            int length;
            while ((length = inputStream.read(buffer)) > 0) {
                outputStream.write(buffer, 0, length);
            }
            
            inputStream.close();
            outputStream.close();
            
            return outputFile.getAbsolutePath();
        } catch (IOException e) {
            Log.e(TAG, "保存文件失败", e);
            return null;
        }
    }
    
    private String getFileExtension(Uri uri) {
        String fileName = getFileName(uri);
        int lastDotIndex = fileName.lastIndexOf('.');
        return lastDotIndex >= 0 ? fileName.substring(lastDotIndex) : "";
    }
    
    private void loadAvailableCourses() {
        String account = com.example.myapplication.service.AuthService.getCurrentUser(this);
        com.example.myapplication.repository.UserRepository ur = new com.example.myapplication.repository.UserRepository(this);
        com.example.myapplication.domain.User u = ur.getUserByAccount(account);
        Long majorId = u != null ? u.getMajorId() : null;
        String gradeText = ur.getGradeText(account);
        availableCourses = courseRepository.getCoursesByMajorAndGrade(majorId, gradeText);
        if (availableCourses == null || availableCourses.isEmpty()) {
            availableCourses = courseRepository.getAllCourses();
        }
        if (availableCourses == null || availableCourses.isEmpty()) {
            Toast.makeText(this, "暂无课程数据，请稍后重试", Toast.LENGTH_LONG).show();
        } else {
            setupCourseSpinner();
        }
    }
    
    private void setupCourseSpinner() {
        List<String> courseNames = new ArrayList<>();
        for (Course course : availableCourses) {
            courseNames.add(course.getName());
        }
        
        ArrayAdapter<String> adapter = new ArrayAdapter<>(this, 
            android.R.layout.simple_spinner_item, courseNames);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinnerCourse.setAdapter(adapter);
    }
    
    private void loadChaptersForCourse(String courseId) {
        long sid = 0L;
        try { sid = Long.parseLong(courseId); } catch (Exception ignored) {}
        availableChapters = courseRepository.getChaptersBySubjectId(sid);
        List<String> chapterTitles = new ArrayList<>();
        for (Chapter ch : availableChapters) chapterTitles.add(ch.getName());
        if (chapterTitles.isEmpty()) chapterTitles.add("暂无章节");
        ArrayAdapter<String> adapter = new ArrayAdapter<>(this,
                android.R.layout.simple_spinner_item, chapterTitles);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinnerChapter.setAdapter(adapter);
    }
    
    private void uploadNote() {
        String title = etNoteTitle.getText().toString().trim();
        String description = etNoteDescription.getText().toString().trim();
        
        if (title.isEmpty()) {
            Toast.makeText(this, "请输入笔记标题", Toast.LENGTH_SHORT).show();
            return;
        }
        
        if (selectedFileUri == null) {
            Toast.makeText(this, "请选择文件", Toast.LENGTH_SHORT).show();
            return;
        }
        
        showProgress(true);
        
        // 在后台线程中处理
        new Thread(() -> {
            try {
                // 1. 执行OCR提取文本
                String ocrText = performOCR();
                
                // 2. 创建笔记对象
                Note note = createNote(title, description, ocrText);
                
                // 3. 进行自动分类
                if (note.getOcrText() != null && !note.getOcrText().isEmpty()) {
                    performClassification(note);
                } else {
                    runOnUiThread(() -> {
                        showProgress(false);
                        showManualSelection();
                    });
                    return;
                }
                
                runOnUiThread(() -> {
                    showProgress(false);
                    showClassificationResult();
                });
                
            } catch (Exception e) {
                Log.e(TAG, "处理笔记失败", e);
                runOnUiThread(() -> {
                    showProgress(false);
                    Toast.makeText(this, "处理失败: " + e.getMessage(), Toast.LENGTH_SHORT).show();
                });
            }
        }).start();
    }
    
    private String performOCR() {
        if (savedFilePath == null) return "";
        try {
            String text = com.example.myapplication.service.OCRService.extractTextFromFile(this, savedFilePath);
            if (text == null || text.trim().isEmpty()) {
                Toast.makeText(this, "识别暂不可用，您可手动填写内容", Toast.LENGTH_SHORT).show();
                return "";
            }
            return text;
        } catch (Exception e) {
            Log.e(TAG, "OCR处理失败", e);
            Toast.makeText(this, "识别失败，已保留上传与编辑", Toast.LENGTH_SHORT).show();
            return "";
        }
    }
    
    private Note createNote(String title, String description, String ocrText) {
        Note note = new Note();
        note.setTitle(title);
        note.setDescription(description);
        note.setOcrText(ocrText);
        note.setFilePath(savedFilePath);
        
        long currentTime = System.currentTimeMillis();
        note.setUploadTime(currentTime);
        note.setUpdateTime(currentTime);
        
        return note;
    }
    
    private void performClassification(Note note) {
        currentClassification = classificationService.classifyWithSegmentation(note.getOcrText());
    }
    
    private void showClassificationResult() {
        if (currentClassification == null) {
            Toast.makeText(this, "分类失败", Toast.LENGTH_SHORT).show();
            return;
        }
        
        if (currentClassification.category.isEmpty()) {
            tvClassificationResult.setText("无法自动分类，请手动选择");
            tvClassificationConfidence.setText("");
            showManualSelection();
        } else {
            String result = String.format("分类结果: %s - %s", currentClassification.category, currentClassification.chapter);
            tvClassificationResult.setText(result);
            String confidence = String.format("置信度: %.2f%%", currentClassification.confidence * 100);
            tvClassificationConfidence.setText(confidence);
            if (currentClassification.confidence >= 0.6) {
                preselectByClassification();
                cardClassification.setVisibility(View.VISIBLE);
                cardManualSelection.setVisibility(View.GONE);
            } else {
                cardClassification.setVisibility(View.VISIBLE);
                cardManualSelection.setVisibility(View.VISIBLE);
                Toast.makeText(this, "置信度较低，请确认或手动选择", Toast.LENGTH_SHORT).show();
            }
        }
    }

    private void preselectByClassification() {
        if (availableCourses != null && !availableCourses.isEmpty()) {
            int courseIndex = -1;
            for (int i = 0; i < availableCourses.size(); i++) {
                if (availableCourses.get(i).getName().equals(currentClassification.category)) {
                    courseIndex = i;
                    break;
                }
            }
            if (courseIndex >= 0) {
                spinnerCourse.setSelection(courseIndex);
                Course selectedCourse = availableCourses.get(courseIndex);
                loadChaptersForCourse(String.valueOf(selectedCourse.getId()));
                if (availableChapters != null && !availableChapters.isEmpty()) {
                    int chapterIndex = -1;
                    for (int j = 0; j < availableChapters.size(); j++) {
                        if (availableChapters.get(j).getName().equals(currentClassification.chapter)) {
                            chapterIndex = j;
                            break;
                        }
                    }
                    if (chapterIndex >= 0) spinnerChapter.setSelection(chapterIndex);
                }
            }
        }
    }
    
    private void acceptClassification() {
        if (currentClassification == null || currentClassification.category.isEmpty()) {
            Toast.makeText(this, "没有有效的分类结果", Toast.LENGTH_SHORT).show();
            return;
        }
        // 创建最终笔记并保存（科目、章节均使用数据库选择结果）
        Note finalNote = createNote(
            etNoteTitle.getText().toString().trim(),
            etNoteDescription.getText().toString().trim(),
            "自动分类: " + currentClassification.category + " - " + currentClassification.chapter
        );

        int coursePos = spinnerCourse.getSelectedItemPosition();
        if (availableCourses == null || availableCourses.isEmpty() || coursePos < 0 || coursePos >= availableCourses.size()) {
            Toast.makeText(this, "请选择科目", Toast.LENGTH_SHORT).show();
            showManualSelection();
            return;
        }
        Course selectedCourse = availableCourses.get(coursePos);

        int chapterPos = spinnerChapter.getSelectedItemPosition();
        if (availableChapters == null || availableChapters.isEmpty() || chapterPos < 0 || chapterPos >= availableChapters.size()) {
            Toast.makeText(this, "请选择章节", Toast.LENGTH_SHORT).show();
            showManualSelection();
            return;
        }
        Chapter selectedChapter = availableChapters.get(chapterPos);

        finalNote.setCourseId(selectedCourse.getId());
        finalNote.setChapterId(selectedChapter.getId());
        finalNote.setUploaderId(com.example.myapplication.service.AuthService.getCurrentUser(this));

        long result = noteRepository.insertNote(finalNote);
        if (result != -1) {
            Toast.makeText(this, "笔记上传成功！", Toast.LENGTH_SHORT).show();
            finish();
        } else {
            Toast.makeText(this, "保存笔记失败", Toast.LENGTH_SHORT).show();
        }
    }
    
    private void showManualSelection() {
        cardClassification.setVisibility(View.GONE);
        cardManualSelection.setVisibility(View.VISIBLE);
    }
    
    private void showProgress(boolean show) {
        progressBar.setVisibility(show ? View.VISIBLE : View.GONE);
        btnUpload.setEnabled(!show);
        btnCancel.setEnabled(!show);
    }
    
    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (courseRepository != null) {
            courseRepository.close();
        }
        if (noteRepository != null) {
            noteRepository.close();
        }
    }
}