package ezviz.ezopensdkcommon.configwifi;

import android.Manifest;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import ezviz.ezopensdkcommon.R;
import ezviz.ezopensdkcommon.common.EZPermissionUtil;
import ezviz.ezopensdkcommon.common.IntentConstants;
import ezviz.ezopensdkcommon.common.RootActivity;
import ezviz.ezopensdkcommon.common.TitleBar;

/**
 * Wi-Fi 列表页面
 * 扫描周围的 Wi-Fi 网络，供用户选择。
 * 5G 频段的 Wi-Fi 会灰化显示且不可点击。
 */
public class AutoWifiListActivity extends RootActivity {

    private RecyclerView recyclerWifiList;
    private ImageView btnRefresh;
    private ProgressBar progressBar;
    private WifiManager mWifiManager;
    private WifiAdapter mAdapter;
    private List<WifiItem> mWifiList = new ArrayList<>();
    private boolean isSupport5G = false;

    private BroadcastReceiver mWifiReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            loadScanResults();
        }
    };

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

        isSupport5G = getIntent().getBooleanExtra(IntentConstants.EXTRA_SUPPORT_WIFI_5G, false);
        mWifiManager = (WifiManager) getApplicationContext().getSystemService(WIFI_SERVICE);

        initTitleBar();
        initViews();
        checkPermissions();
    }

    private void initTitleBar() {
        TitleBar titleBar = findViewById(R.id.title_bar);
        titleBar.setTitle(R.string.wifi_list_title);
        titleBar.addBackButton(v -> onBackPressed());
    }

    private void initViews() {
        recyclerWifiList = findViewById(R.id.recyclerWifiList);
        btnRefresh = findViewById(R.id.btnRefresh);
        progressBar = findViewById(R.id.progressBar);

        recyclerWifiList.setLayoutManager(new LinearLayoutManager(this));
        mAdapter = new WifiAdapter();
        recyclerWifiList.setAdapter(mAdapter);

        btnRefresh.setOnClickListener(v -> {
            progressBar.setVisibility(View.VISIBLE);
            startWifiScan();
        });
    }

    private void startWifiScan() {
        if (mWifiManager != null) {
            mWifiManager.startScan();
        }
    }

    private void loadScanResults() {
        if (mWifiManager == null) return;

        progressBar.setVisibility(View.GONE);

        List<ScanResult> results = mWifiManager.getScanResults();
        mWifiList.clear();
        Set<String> addedSsids = new HashSet<>();

        for (ScanResult result : results) {
            // 过滤空 SSID
            if (TextUtils.isEmpty(result.SSID)) continue;
            // 按 SSID 去重
            if (addedSsids.contains(result.SSID)) continue;
            addedSsids.add(result.SSID);

            WifiItem item = new WifiItem();
            item.ssid = result.SSID;
            item.level = result.level;
            // 5G 判定：频率大于 4900MHz
            item.is5G = result.frequency > 4900;
            mWifiList.add(item);
        }

        sortWifiList();
        mAdapter.notifyDataSetChanged();
    }

    /**
     * 排序：非5G在前（按信号强度降序），5G在后（按信号强度降序）
     */
    private void sortWifiList() {
        Collections.sort(mWifiList, (a, b) -> {
            // 非5G优先
            if (a.is5G != b.is5G) {
                return a.is5G ? 1 : -1;
            }
            // 信号强度降序（level越大信号越好）
            return Integer.compare(b.level, a.level);
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
        IntentFilter filter = new IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION);
        registerReceiver(mWifiReceiver, filter);
        progressBar.setVisibility(View.VISIBLE);
        startWifiScan();
    }

    @Override
    protected void onPause() {
        super.onPause();
        unregisterReceiver(mWifiReceiver);
    }

    /**
     * 动态权限请求
     */
    private void checkPermissions() {
        EZPermissionUtil.requestPermissions(this,
                new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
                1001, () -> startWifiScan());
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        EZPermissionUtil.handleResult(requestCode, permissions, grantResults);
    }

    // ======================== 数据模型 ========================

    static class WifiItem {
        String ssid;
        int level;
        boolean is5G;
    }

    // ======================== RecyclerView Adapter ========================

    class WifiAdapter extends RecyclerView.Adapter<WifiAdapter.ViewHolder> {

        @NonNull
        @Override
        public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            View view = LayoutInflater.from(parent.getContext())
                    .inflate(R.layout.item_wifi, parent, false);
            return new ViewHolder(view);
        }

        @Override
        public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
            WifiItem item = mWifiList.get(position);
            holder.tvWifiName.setText(item.ssid);

            // 根据信号强度选择对应图标（0-3共4级）
            int signalLevel = WifiManager.calculateSignalLevel(item.level, 4);
            int signalIcon;
            switch (signalLevel) {
                case 0: signalIcon = R.drawable.ic_wifi_signal_0; break;
                case 1: signalIcon = R.drawable.ic_wifi_signal_1; break;
                case 2: signalIcon = R.drawable.ic_wifi_signal_2; break;
                default: signalIcon = R.drawable.ic_wifi_signal_3; break;
            }
            holder.ivWifiSignal.setImageResource(signalIcon);

            // 5G 处理
            if (item.is5G && !isSupport5G) {
                holder.tvWifiNote.setVisibility(View.VISIBLE);
                holder.tvWifiNote.setText(R.string.wifi_5g_not_support);
                holder.itemView.setAlpha(0.5f);
                holder.ivWifiSignal.setAlpha(0.3f);
                holder.itemView.setOnClickListener(null);
                holder.itemView.setClickable(false);
            } else {
                holder.tvWifiNote.setVisibility(View.GONE);
                holder.itemView.setAlpha(1.0f);
                holder.ivWifiSignal.setAlpha(1.0f);
                holder.itemView.setOnClickListener(v -> {
                    Intent data = new Intent();
                    data.putExtra("ssid", item.ssid);
                    setResult(RESULT_OK, data);
                    finish();
                });
            }
        }

        @Override
        public int getItemCount() {
            return mWifiList.size();
        }

        class ViewHolder extends RecyclerView.ViewHolder {
            TextView tvWifiName;
            TextView tvWifiNote;
            ImageView ivWifiSignal;

            ViewHolder(View itemView) {
                super(itemView);
                tvWifiName = itemView.findViewById(R.id.tvWifiName);
                tvWifiNote = itemView.findViewById(R.id.tvWifiNote);
                ivWifiSignal = itemView.findViewById(R.id.ivWifiSignal);
            }
        }
    }
}
