import { useEffect, useState } from 'react';
import { shouldShowVoiceInputControl, isVoiceInputAvailable } from '../voice/capabilities';
import { VoiceInputDialog } from './VoiceInputDialog';

function MicIcon() {
  return (
    <svg viewBox="0 0 24 24" width="18" height="18" aria-hidden="true">
      <path
        fill="currentColor"
        d="M12 14a3 3 0 0 0 3-3V6a3 3 0 1 0-6 0v5a3 3 0 0 0 3 3Zm5-3a1 1 0 1 0-2 0 5 5 0 0 1-10 0 1 1 0 1 0-2 0 7 7 0 0 0 6 6.92V19H9a1 1 0 1 0 0 2h6a1 1 0 1 0 0-2h-2v-1.08A7 7 0 0 0 17 11Z"
      />
    </svg>
  );
}

export function VoiceInputButton({
  disabled = false,
  onSend,
  onError,
}: {
  disabled?: boolean;
  onSend: (text: string) => void;
  onError?: (message: string) => void;
}) {
  const [open, setOpen] = useState(false);
  const [sessionKey, setSessionKey] = useState(0);
  const [available, setAvailable] = useState(true);

  useEffect(() => {
    setAvailable(isVoiceInputAvailable());
  }, []);

  if (!shouldShowVoiceInputControl()) return null;

  const blocked = disabled || !available;

  return (
    <>
      <button
        type="button"
        className={`voice-btn${open ? ' voice-btn-recording' : ''}`}
        disabled={blocked}
        aria-label="语音输入"
        title={available ? '语音输入' : '当前浏览器不支持麦克风，请改用文字输入'}
        onClick={() => {
          if (blocked) {
            if (!available) onError?.('当前浏览器不支持语音输入');
            return;
          }
          setSessionKey((value) => value + 1);
          setOpen(true);
        }}
      >
        <MicIcon />
      </button>
      <VoiceInputDialog
        key={sessionKey}
        open={open}
        disabled={disabled}
        onClose={() => setOpen(false)}
        onSend={onSend}
        onError={onError}
      />
    </>
  );
}
