import { NavBar, SpinLoading, Toast } from 'antd-mobile';
import './Bluetooth.scss';
import { useEffect, useState } from 'react';
import { useAppDispatch, useAppSelector } from '../utils/hooks';
import Bridge from '../utils/bridge';
import { updateBleLinkStatus, updateBleList } from '../store/features/contextSlice';

export default function Bluetooth() {
  const dispatch = useAppDispatch();
  const contextState = useAppSelector((state) => state.context);

  const [connectingMac, setConnectingMac] = useState('')

  useEffect(() => {
    Bridge.scanPeripherals().then((res) => {
      if (!res.success) {
        Toast.show(res.message);
      }
    });
    return () => {
      Bridge.stopScanPeripherals().then((res) => {});
    };
  }, []);

  const onConnect = (mac: string) => {
    setConnectingMac(mac);
    Bridge.connectPeripheral({ mac }).then((res) => {
      setConnectingMac('');
      if (!res.success) {
        Toast.show(res.message);
      } else {
        dispatch(updateBleLinkStatus({ mac, link: true }));
      }
    });
  };
  const onDisconnect = (mac: string) => {
    Bridge.disconnectPeripheral().then((res) => {
      if (!res.success) {
        Toast.show(res.message);
      } else {
        dispatch(updateBleList([])); // 清空列表
        // dispatch(updateBleLinkStatus({ mac, link: false }));
      }
    });
  };
  function scanning() {
    return <div className='flex items-center gap-x-3'><p>扫描中</p><SpinLoading /></div>
  }
  return (
    <div>
      <NavBar className="bg-white" back={null}>
        蓝牙
      </NavBar>
      <div className="home-page-content bluetooth-list overflow-x-hidden overflow-y-auto">
        <section>
          <div className="h-[42px] px-5 flex items-center justify-between">
            <h1 className="h-[42px] leading-[42px] text-base text-text font-medium">附近设备</h1>
            {contextState.bleList.some((bl) => bl.linked) || connectingMac ? undefined : scanning()}
          </div>
          <div className="bg-white px-5 text-sm text-text">
            {contextState.bleList.map((ble) => (
              <div
                key={ble.mac}
                className="py-2 flex items-center border-b border-[#eee]"
                onClick={
                  contextState.bleList.some((bl) => bl.linked) || connectingMac
                    ? undefined
                    : () => onConnect(ble.mac)
                }
              >
                <div>
                  <p>{ble.name}</p>
                  <p className='text-[10px] text-title'>{ble.mac}</p>
                </div>

                <span className="text-xs text-title ml-3">{ble.linked ? '已连接' : connectingMac === ble.mac ? '正在连接' : ''}</span>
                {connectingMac === ble.mac && <div className='ml-auto'><SpinLoading /></div>}
                {ble.linked && (
                  <button
                    className="btn-contained px-2 py-1 rounded ml-auto"
                    onClick={() => onDisconnect(ble.mac)}
                  >
                    断开
                  </button>
                )}
              </div>
            ))}
          </div>
        </section>
      </div>
    </div>
  );
}
