package com.auto.clicker.autoclicker.ui.activity.menu;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import android.view.View;
import android.widget.EditText;

import androidx.activity.EdgeToEdge;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.auto.clicker.autoclicker.R;
import com.auto.clicker.autoclicker.databinding.ActivityScriptsBinding;
import com.auto.clicker.autoclicker.room.SolutionWithEventsAndPoints;
import com.auto.clicker.autoclicker.room.entity.Solution;
import com.auto.clicker.autoclicker.room.repository.EventRepository;
import com.auto.clicker.autoclicker.ui.adapter.floating.SolutionAdapter;
import com.auto.clicker.autoclicker.ui.dialog.CreateModeSelectionDialog;
import com.auto.clicker.autoclicker.view.FloatingViewManager;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;

public class ScriptsActivity extends AppCompatActivity implements SolutionAdapter.OnOptionMenuClickListener {
    private ActivityScriptsBinding binding;
    private SolutionAdapter solutionsAdapter;
    private FloatingViewManager floatingViewManager;
    private String tempExportJson;

    private static final String TAG = "ScriptsActivity";
    private static final int CREATE_FILE_REQUEST_CODE = 1;
    private static final int PICK_FILE_REQUEST_CODE = 2;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        binding = ActivityScriptsBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> {
            Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
            return insets;
        });

        binding.scriptsRecyclerView.setLayoutManager(new LinearLayoutManager(this));
        solutionsAdapter = new SolutionAdapter(new ArrayList<>(), this::onSolutionSelected, this);
        binding.scriptsRecyclerView.setAdapter(solutionsAdapter);

        floatingViewManager = new FloatingViewManager(this);

        binding.btnBack.setOnClickListener(v -> finish());

        binding.create.setOnClickListener(v -> {
            CreateModeSelectionDialog dialog = new CreateModeSelectionDialog();
            dialog.show(getSupportFragmentManager(), "CreateModeSelectionDialog");
        });

        binding.importScripts.setOnClickListener(v -> {
            pickJsonFileForImport();
        });

        binding.customImportView.setOnClickListener(v -> {
            pickJsonFileForImport();
        });

        loadSolutions();
    }

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

    private void loadSolutions() {
        if (floatingViewManager == null) {
            Log.e(TAG, "FloatingViewManager 未设置，无法加载方案列表。");
            updateLayout(true);
            return;
        }

        floatingViewManager.getEventRepository().getAllSolutions(new EventRepository.RepositoryCallback<List<Solution>>() {
            @Override
            public void onComplete(List<Solution> solutions) {
                new Handler(Looper.getMainLooper()).post(() -> {
                    solutionsAdapter.setSolutions(solutions);
                    updateLayout(solutions.isEmpty());
                });
            }

            @Override
            public void onError(Exception e) {
                new Handler(Looper.getMainLooper()).post(() -> {
                    Log.e(TAG, "加载方案列表失败: " + e.getMessage(), e);
                    updateLayout(true);
                });
            }
        });
    }

    private void updateLayout(boolean isEmpty) {
        if (isEmpty) {
            binding.noScriptsGroup.setVisibility(View.VISIBLE);
            binding.scriptsRecyclerView.setVisibility(View.GONE);
            binding.customImportView.setVisibility(View.GONE);
        } else {
            binding.noScriptsGroup.setVisibility(View.GONE);
            binding.scriptsRecyclerView.setVisibility(View.VISIBLE);
            binding.customImportView.setVisibility(View.VISIBLE);
        }
    }

    private void onSolutionSelected(Solution solution) {
        if (floatingViewManager != null) {
            floatingViewManager.showFloatingViews(solution.getMode());
            floatingViewManager.loadSolution(solution.getSolutionId());
        } else {
            Log.e(TAG, "FloatingViewManager 未设置！无法加载方案。");
        }
    }

    @Override
    public void onRenameClick(Solution solution) {
        showRenameDialog(solution);
    }

    @Override
    public void onDuplicateClick(Solution solution) {
        duplicateSolution(solution);
    }

    @Override
    public void onDeleteClick(Solution solution) {
        showDeleteConfirmationDialog(solution);
    }

    @Override
    public void onExportClick(Solution solution) {
        exportSolution(solution);
    }

    private void showRenameDialog(final Solution solution) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("重命名方案");

        final EditText input = new EditText(this);
        input.setText(solution.getSolutionName());
        builder.setView(input);

        builder.setPositiveButton("确定", (dialog, which) -> {
            String newName = input.getText().toString().trim();
            if (!newName.isEmpty() && !newName.equals(solution.getSolutionName())) {
                floatingViewManager.getEventRepository().updateSolutionName(solution.getSolutionId(), newName, new EventRepository.RepositoryCallback<Void>() {
                    @Override
                    public void onComplete(Void result) {
                        new Handler(Looper.getMainLooper()).post(() -> {
                            loadSolutions();
                        });
                    }

                    @Override
                    public void onError(Exception e) {
                        new Handler(Looper.getMainLooper()).post(() -> {
                            Log.e(TAG, "重命名失败: " + e.getMessage(), e);
                        });
                    }
                });
            }
        });
        builder.setNegativeButton("取消", (dialog, which) -> dialog.cancel());
        builder.show();
    }

    private void duplicateSolution(final Solution originalSolution) {
        floatingViewManager.getEventRepository().getSolutionWithEventsAndPoints(originalSolution.getSolutionId(), new EventRepository.RepositoryCallback<SolutionWithEventsAndPoints>() {
            @Override
            public void onComplete(SolutionWithEventsAndPoints originalData) {
                if (originalData != null) {
                    floatingViewManager.getEventRepository().saveDuplicateSolution(originalData, new EventRepository.RepositoryCallback<Void>() {
                        @Override
                        public void onComplete(Void result) {
                            new Handler(Looper.getMainLooper()).post(ScriptsActivity.this::loadSolutions);
                        }

                        @Override
                        public void onError(Exception e) {
                            new Handler(Looper.getMainLooper()).post(() -> {
                                Log.e(TAG, "复制方案失败: " + e.getMessage(), e);
                            });
                        }
                    });
                } else {
                    new Handler(Looper.getMainLooper()).post(() -> {
                    });
                }
            }

            @Override
            public void onError(Exception e) {
                new Handler(Looper.getMainLooper()).post(() -> {
                    Log.e(TAG, "获取原始方案数据失败: " + e.getMessage(), e);
                });
            }
        });
    }

    private void showDeleteConfirmationDialog(final Solution solution) {
        new AlertDialog.Builder(this)
                .setTitle("删除方案")
                .setMessage("确定要删除方案 '" + solution.getSolutionName() + "' 吗？\n此操作不可撤销！")
                .setPositiveButton("删除", (dialog, which) -> deleteSolution(solution))
                .setNegativeButton("取消", null)
                .show();
    }

    private void deleteSolution(final Solution solution) {
        floatingViewManager.getEventRepository().deleteSolution(solution.getSolutionId(), new EventRepository.RepositoryCallback<Void>() {
            @Override
            public void onComplete(Void result) {
                new Handler(Looper.getMainLooper()).post(() -> {
                    loadSolutions();
                });
            }

            @Override
            public void onError(Exception e) {
                new Handler(Looper.getMainLooper()).post(() -> {
                    Log.e(TAG, "删除方案失败: " + e.getMessage(), e);
                });
            }
        });
    }

    private void pickJsonFileForImport() {
        Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
        intent.addCategory(Intent.CATEGORY_OPENABLE);
        intent.setType("application/json");
        startActivityForResult(intent, PICK_FILE_REQUEST_CODE);
    }

    private void exportSolution(final Solution solution) {
        floatingViewManager.getEventRepository().getSolutionWithEventsAndPoints(solution.getSolutionId(), new EventRepository.RepositoryCallback<SolutionWithEventsAndPoints>() {
            @Override
            public void onComplete(SolutionWithEventsAndPoints data) {
                if (data != null) {
                    tempExportJson = floatingViewManager.getEventRepository().exportSolutionToJson(data);
                    if (tempExportJson != null && !tempExportJson.isEmpty()) {
                        Intent intent = new Intent(Intent.ACTION_CREATE_DOCUMENT);
                        intent.addCategory(Intent.CATEGORY_OPENABLE);
                        intent.setType("application/json");
                        intent.putExtra(Intent.EXTRA_TITLE, solution.getSolutionName() + ".json");
                        startActivityForResult(intent, CREATE_FILE_REQUEST_CODE);
                    }
                }
            }

            @Override
            public void onError(Exception e) {
                new Handler(Looper.getMainLooper()).post(() -> {
                    Log.e(TAG, "获取方案数据失败: " + e.getMessage(), e);
                });
            }
        });
    }

    private void importSolutionFromFile(Uri uri) {
        try {
            InputStream inputStream = getContentResolver().openInputStream(uri);
            if (inputStream == null) {
                return;
            }

            StringBuilder stringBuilder = new StringBuilder();
            try (BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream))) {
                String line;
                while ((line = reader.readLine()) != null) {
                    stringBuilder.append(line);
                }
            }

            String jsonString = stringBuilder.toString();
            if (jsonString.isEmpty()) {
                return;
            }

            SolutionWithEventsAndPoints importedData = floatingViewManager.getEventRepository().importSolutionFromJson(jsonString);

            if (importedData != null && importedData.solution != null) {
                // 保存到数据库
                floatingViewManager.getEventRepository().importSolutionFromData(importedData, new EventRepository.RepositoryCallback<Void>() {
                    @Override
                    public void onComplete(Void result) {
                        new Handler(Looper.getMainLooper()).post(() -> {
                            loadSolutions(); // 刷新列表
                        });
                    }

                    @Override
                    public void onError(Exception e) {
                        new Handler(Looper.getMainLooper()).post(() -> {
                            Log.e(TAG, "导入方案失败: " + e.getMessage(), e);
                        });
                    }
                });
            }

        } catch (Exception e) {
            Log.e(TAG, "读取或解析导入文件失败: " + e.getMessage(), e);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == CREATE_FILE_REQUEST_CODE && resultCode == RESULT_OK) {
            if (data != null && data.getData() != null) {
                Uri uri = data.getData();
                if (tempExportJson != null) {
                    try (OutputStream outputStream = getContentResolver().openOutputStream(uri)) {
                        if (outputStream != null) {
                            outputStream.write(tempExportJson.getBytes());
                        }
                    } catch (Exception e) {
                        Log.e(TAG, "保存文件失败: " + e.getMessage(), e);
                    } finally {
                        tempExportJson = null;
                    }
                }
            }
        } else if (requestCode == PICK_FILE_REQUEST_CODE && resultCode == RESULT_OK) {
            if (data != null && data.getData() != null) {
                Uri uri = data.getData();
                importSolutionFromFile(uri);
            }
        }
    }

}