package com.lnkj.ln_jq_app;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.amap.api.services.help.Inputtips;
import com.amap.api.services.help.InputtipsQuery;
import com.amap.api.services.help.Tip;

import java.util.ArrayList;
import java.util.List;

import androidx.activity.ComponentActivity;

/**
 * 搜索目的地页面
 */
public class SearchDestinationActivity extends ComponentActivity implements Inputtips.InputtipsListener {
    private static final String TAG = "SearchDestinationActivity";

    public static final String EXTRA_RESULT_NAME = "result_name";
    public static final String EXTRA_RESULT_ADDRESS = "result_address";
    public static final String EXTRA_RESULT_LAT = "result_lat";
    public static final String EXTRA_RESULT_LON = "result_lon";
    public static final String EXTRA_RESULT_DISTRICT = "result_district";

    // 静态回调接口
    public interface DestinationCallback {
        void onDestinationSelected(String name, String address, double lat, double lon, String district);
    }

    private static DestinationCallback callback;

    public static void setCallback(DestinationCallback callback) {
        SearchDestinationActivity.callback = callback;
    }

    private EditText searchInput;
    private ListView suggestionList;
    private ImageView backBtn;

    private ArrayAdapter<String> suggestionAdapter;
    private List<Tip> currentTipList;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        try {
            setContentView(R.layout.activity_search_destination);

            initViews();
            setupListeners();

            // 自动显示键盘
            showKeyboard();
        } catch (Exception e) {
            Log.e(TAG, "Error in onCreate", e);
            e.printStackTrace();
            finish();
        }
    }

    private void initViews() {
        try {
            Log.d(TAG, "initViews started");
            searchInput = findViewById(R.id.search_input);
            suggestionList = findViewById(R.id.suggestion_list);
            backBtn = findViewById(R.id.back_btn);

            currentTipList = new ArrayList<>();

            Log.d(TAG, "initViews completed: searchInput=" + (searchInput != null ? "ok" : "null") + ", suggestionList=" + (suggestionList != null ? "ok" : "null") + ", backBtn=" + (backBtn != null ? "ok" : "null"));
        } catch (Exception e) {
            Log.e(TAG, "Error in initViews", e);
            e.printStackTrace();
        }

        suggestionAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, new ArrayList<>()) {
            @Override
            public View getView(int position, android.view.View convertView, android.view.ViewGroup parent) {
                View view = super.getView(position, convertView, parent);
                TextView text = view.findViewById(android.R.id.text1);
                text.setTextColor(Color.parseColor("#333333"));
                text.setTextSize(14);
                view.setBackgroundColor(Color.TRANSPARENT);
                return view;
            }
        };
        suggestionList.setAdapter(suggestionAdapter);
        suggestionList.setDivider(new ColorDrawable(Color.LTGRAY));
        suggestionList.setDividerHeight(1);
    }


    private void setupListeners() {
        try {
            Log.d(TAG, "setupListeners started");

            // 返回按钮
            backBtn.setOnClickListener(v -> {
                Log.d(TAG, "Back button clicked");
                hideKeyboard();
                finish();
            });

            // 文本变化监听
            searchInput.addTextChangedListener(new TextWatcher() {
                @Override
                public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                }

                @Override
                public void onTextChanged(CharSequence s, int start, int before, int count) {
                    Log.d(TAG, "Text changed: " + (s != null ? s.toString() : "null") + ", length=" + (s != null ? s.length() : 0));
                    if (s.length() > 1) {
                        searchLocation(s.toString());
                    } else {
                        suggestionList.setVisibility(View.GONE);
                    }
                }

                @Override
                public void afterTextChanged(Editable s) {
                }
            });

            // 列表点击
            suggestionList.setOnItemClickListener((parent, view, position, id) -> {
                Log.d(TAG, "Suggestion clicked at position: " + position);
                try {
                    Tip tip = currentTipList.get(position);
                    if (tip.getPoint() != null) {
                        String name = tip.getName();
                        String address = tip.getAddress();
                        String district = tip.getDistrict();
                        double lat = tip.getPoint().getLatitude();
                        double lon = tip.getPoint().getLongitude();

                        Log.d(TAG, "Selected destination: " + name + ", lat=" + lat + ", lon=" + lon);

                        // 优先使用静态回调
                        if (callback != null) {
                            callback.onDestinationSelected(name, address, lat, lon, district);
                        } else {
                            // 降级使用 Intent 回调
                            Intent result = new Intent();
                            result.putExtra(EXTRA_RESULT_NAME, name);
                            result.putExtra(EXTRA_RESULT_ADDRESS, address);
                            result.putExtra(EXTRA_RESULT_LAT, lat);
                            result.putExtra(EXTRA_RESULT_LON, lon);
                            result.putExtra(EXTRA_RESULT_DISTRICT, district);
                            setResult(RESULT_OK, result);
                        }

                        hideKeyboard();
                        finish();
                    }
                } catch (Exception e) {
                    Log.e(TAG, "Error handling suggestion click", e);
                    e.printStackTrace();
                }
            });

            Log.d(TAG, "setupListeners completed");
        } catch (Exception e) {
            Log.e(TAG, "Error in setupListeners", e);
            e.printStackTrace();
        }
    }

    private void searchLocation(String keyword) {
        try {
            Log.d(TAG, "Searching for: " + keyword);
            InputtipsQuery query = new InputtipsQuery(keyword, "");
            query.setCityLimit(false);
            Inputtips inputtips = new Inputtips(this, query);
            inputtips.setInputtipsListener(this);
            inputtips.requestInputtipsAsyn();
        } catch (Exception e) {
            Log.e(TAG, "Error in searchLocation", e);
            e.printStackTrace();
        }
    }


    @Override
    public void onGetInputtips(List<Tip> tipList, int rCode) {
        Log.d(TAG, "onGetInputtips called, rCode=" + rCode + ", tipList size=" + (tipList != null ? tipList.size() : "null"));
        if (rCode == 1000 && tipList != null && !tipList.isEmpty()) {
            currentTipList.clear();
            currentTipList.addAll(tipList);

            List<String> suggestionNames = new ArrayList<>();
            for (Tip tip : tipList) {
                String name = tip.getName();
                String district = tip.getDistrict();
                String displayText = district != null && !district.isEmpty() ? name + " " + district : name;
                suggestionNames.add(displayText);
            }

            runOnUiThread(() -> {
                suggestionAdapter.clear();
                suggestionAdapter.addAll(suggestionNames);
                suggestionAdapter.notifyDataSetChanged();

                if (suggestionNames.size() > 0) {
                    suggestionList.setVisibility(View.VISIBLE);
                } else {
                    suggestionList.setVisibility(View.GONE);
                }
            });
        } else {
            runOnUiThread(() -> {
                suggestionList.setVisibility(View.GONE);
            });
        }
    }


    private void showKeyboard() {
        searchInput.requestFocus();
        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        if (imm != null) {
            imm.showSoftInput(searchInput, InputMethodManager.SHOW_IMPLICIT);
        }
    }

    private void hideKeyboard() {
        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        if (imm != null) {
            imm.hideSoftInputFromWindow(searchInput.getWindowToken(), 0);
        }
    }


    @Override
    public void onPointerCaptureChanged(boolean hasCapture) {
        super.onPointerCaptureChanged(hasCapture);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        // 清理回调，避免内存泄漏
        callback = null;
    }
}