import React, { useCallback, useRef, useState } from 'react';
import type { ChatTriggerBarProps } from '../../types';
import micAiIcon from '../../assets/mic-ai.png';
import { TriggerBarSendIcon } from '../icons/TriggerBarSendIcon';
import styles from './index.module.less';

export const ChatTriggerBar: React.FC<ChatTriggerBarProps> = ({
  onOpenAssistant,
  onSubmitText,
  placeholder = '查找点位、资源、事件',
  className,
}) => {
  const [value, setValue] = useState('');
  const inputRef = useRef<HTMLInputElement>(null);

  const hasText = value.trim().length > 0;

  const handleSubmit = useCallback(() => {
    const text = value.trim();
    if (!text) return;
    onSubmitText?.(text);
    setValue('');
  }, [value, onSubmitText]);

  const handleKeyDown = (e: React.KeyboardEvent<HTMLInputElement>) => {
    if (e.key === 'Enter') {
      e.preventDefault();
      handleSubmit();
    }
  };

  const handleRightButtonClick = useCallback(
    (e: React.MouseEvent) => {
      e.stopPropagation();
      if (hasText) {
        handleSubmit();
      } else {
        onOpenAssistant?.();
      }
    },
    [hasText, handleSubmit, onOpenAssistant],
  );

  return (
    <div className={`${styles.bar} ${className ?? ''}`}>
      <div className={styles.left} onClick={() => inputRef.current?.focus()}>
        <span className={styles.searchIcon}>
          <SearchIcon />
        </span>
        <input
          ref={inputRef}
          className={styles.textInput}
          value={value}
          onChange={e => setValue(e.target.value)}
          onKeyDown={handleKeyDown}
          placeholder={placeholder}
          enterKeyHint="search"
          autoComplete="off"
          autoCorrect="off"
          autoCapitalize="off"
        />
      </div>

      <button
        type="button"
        className={styles.rightButton}
        onClick={handleRightButtonClick}
        aria-label={hasText ? '发送' : '语音助手'}
      >
        {hasText ? <TriggerBarSendIcon /> : <img src={micAiIcon} alt="" className={styles.micAiIcon} />}
      </button>
    </div>
  );
};

/* ---------- 内联 SVG ---------- */

const SearchIcon = () => (
  <svg width="40" height="40" viewBox="0 0 40 40" fill="none">
    <circle cx="18" cy="18" r="9" stroke="#8c8d91" strokeWidth="2" />
    <line x1="25" y1="25" x2="32" y2="32" stroke="#8c8d91" strokeWidth="2" strokeLinecap="round" />
  </svg>
);

