import React from 'react';

interface SnippetInputProps extends React.TextareaHTMLAttributes<HTMLTextAreaElement> {
  value: string;
  onChange: (value: string) => void;
}

const SNIPPETS: Record<string, string> = {
  ';daily': 'Daily standup',
  ';mtg': 'Meeting',
  ';review': 'Code review',
  ';bug': 'Bugfix ',
};

export const SnippetInput: React.FC<SnippetInputProps> = ({ value, onChange, ...rest }) => {
  const handleChange = (e: React.ChangeEvent<HTMLTextAreaElement>) => {
    const newValue = e.target.value;
    
    // Find the last occurrence of a semicolon to check for a snippet
    const lastSemicolonIndex = newValue.lastIndexOf(';');
    
    if (lastSemicolonIndex !== -1) {
      const trailingText = newValue.slice(lastSemicolonIndex);
      
      // Check if the trailing text matches any of our snippet keys
      const snippetKey = Object.keys(SNIPPETS).find(key => trailingText === key);
      
      if (snippetKey) {
        const expandedValue = newValue.slice(0, lastSemicolonIndex) + SNIPPETS[snippetKey];
        onChange(expandedValue);
        return;
      }
    }
    
    onChange(newValue);
  };

  return (
    <textarea
      {...rest}
      value={value}
      onChange={handleChange}
      className={`w-full p-2 border rounded-md focus:ring-2 focus:ring-blue-500 outline-none transition-all ${rest.className || ''}`}
    />
  );
};