import React from "react";
import { Form, Switch, Button, Tag } from "antd";
import { Link } from "@reach/router";
import {
  SettingOutlined,
  FullscreenOutlined,
  LinkOutlined,
  FullscreenExitOutlined,
  FormOutlined,
  StopOutlined,
  DisconnectOutlined,
  DesktopOutlined,
  AudioOutlined,
  AudioMutedOutlined,
  ReloadOutlined,
} from "@ant-design/icons";
import AudioPlayer from "./AudioPlayer";
import { useEventListener, useKeyPress } from "ahooks";

export default function Status({
  statusInfo,
  wsConnected,
  delay = 0,
  isFullscreen,
  setting,
  isLogin,
  session,
  changeEditabled,
  channelStatus,
  changeChannel,
  serverConfig,
  connectType,
  onCarMicphoneChange,
  locked,
  onControllerMicphoneChange = () => {},
  enabledControllerMicphone = true,
  onReboot,
}) {
  const isWebRTC = connectType === "webrtc";

  const gamepadPress = ({ detail: { index, value } }) => {
    if (index === 3 && value > 0.5) {
      onControllerMicphoneChange(!enabledControllerMicphone);
    }
  };

  useKeyPress(
    "t",
    () => onControllerMicphoneChange(!enabledControllerMicphone),
    {
      events: ["keyup"],
    }
  );

  useEventListener("gamepadpress", gamepadPress);

  const shouldHideLowVoltage = (label, value) => {
    if (!label || !String(label).includes("电压")) return false;
    const numeric = Number(String(value).replace(/[^\d.]/g, ""));
    if (!Number.isFinite(numeric)) return false;
    return numeric < 2.5;
  };

  return (
    <Form layout="inline" className="app-status" size="small">
      <Form.Item>
        <Link to={`${process.env.PUBLIC_URL}/controller`}>
          <img className="logo" src="/logo-256.png" alt="N-RC" />
        </Link>
        <span>N RC</span>
      </Form.Item>
      <Form.Item>
        <Tag
          style={{
            width: "7em",
          }}
          icon={
            locked ? (
              <StopOutlined />
            ) : wsConnected ? (
              <LinkOutlined />
            ) : (
              <DisconnectOutlined />
            )
          }
          color={locked || delay > 80 || !wsConnected ? "red" : "green"}
          size="xs"
        >
          {isWebRTC ? "直连" : "中转"}:{delay.toFixed(0)}
        </Tag>
      </Form.Item>
      {(serverConfig.channelList || [])
        .filter(({ enabled, type }) => enabled && type === "switch")
        .map(({ pin, name }) => (
          <Form.Item key={pin}>
            <Switch
              checked={channelStatus[pin] || false}
              checkedChildren={name}
              unCheckedChildren={name}
              onChange={(value) => changeChannel({ pin, value })}
            />
          </Form.Item>
        ))}

      <Form.Item>
        <AudioPlayer
          session={session}
          connectType={connectType}
          onMicphoneChange={onCarMicphoneChange}
          disabled={!isLogin}
          url={`${
            window.location.protocol === "https:" ? "wss://" : "ws://"
          }${setting.host}/microphone`}
        />
      </Form.Item>

      <Form.Item>
        <Switch
          checked={enabledControllerMicphone}
          onChange={onControllerMicphoneChange}
          disabled={!isLogin || !isWebRTC}
          checkedChildren={
            <>
              <DesktopOutlined /> <AudioOutlined />
            </>
          }
          unCheckedChildren={
            <>
              <DesktopOutlined /> <AudioMutedOutlined />
            </>
          }
        />
      </Form.Item>

      <Form.Item>
        <Switch
          checkedChildren={<FormOutlined />}
          unCheckedChildren={<FormOutlined />}
          onChange={changeEditabled}
        ></Switch>
      </Form.Item>

      <Form.Item>
        <Link to={`${process.env.PUBLIC_URL}/setting`}>
          <Button
            size="small"
            icon={<SettingOutlined />}
            shape="circle"
          ></Button>
        </Link>
      </Form.Item>

      {document.body.requestFullscreen && (
        <Form.Item>
          <Button
            type="primary"
            shape="circle"
            icon={
              isFullscreen ? <FullscreenExitOutlined /> : <FullscreenOutlined />
            }
            onClick={() => {
              if (isFullscreen) {
                document.exitFullscreen();
              } else {
                document.body.requestFullscreen();
              }
            }}
          ></Button>
        </Form.Item>
      )}

      {wsConnected && isLogin && (
        <Form.Item>
          <Button
            shape="circle"
            icon={<ReloadOutlined />}
            onClick={onReboot}
          ></Button>
        </Form.Item>
      )}

      {wsConnected &&
        isLogin &&
        Object.keys(statusInfo).map((key) => {
          const { color, label, value } = statusInfo[key];

          if (shouldHideLowVoltage(label, value)) return undefined;
          return (
            <Form.Item key={key}>
              <Tag color={color}>
                {label}:{value}
              </Tag>
            </Form.Item>
          );
        })}

    </Form>
  );
}
