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

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

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

  const onConnect = (mac: string) => {
    Bridge.connectPeripheral({ mac }).then((res) => {
      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(updateBleLinkStatus({mac, link: false}))
      }
    });
  };
  return (
    <div>
      <NavBar className="bg-white" back={null}>
        蓝牙
      </NavBar>
      <div className="home-page-content 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>
            <SpinLoading />
          </div>
          <div className="bg-white px-5 text-sm text-text">
            {contextState.bleList.map((ble) => (
              <div
                key={ble.mac}
                className="h-12 flex items-center border-b border-[#eee]"
                onClick={
                  contextState.bleList.some((bl) => bl.linked)
                    ? undefined
                    : () => onConnect(ble.mac)
                }
              >
                <span>{ble.name}</span>
                <span className="text-xs text-title ml-2">{ble.linked ? '已连接' : ''}</span>
                {ble.linked && (
                  <button
                    className="btn-contained px-2 py-1 rounded ml-auto"
                    onClick={() => onDisconnect(ble.mac)}
                  >
                    断开
                  </button>
                )}
              </div>
            ))}
          </div>
        </section>
      </div>
    </div>
  );
}
