import { Component, createSignal, createMemo, onMount } from 'solid-js';
import {
  ScreenplayElement,
  ScreenplayElementType,
  TemplateType,
  KeyboardShortcut,
} from '../../lib/screenplay/types';
import { formatScreenplay, getTemplate, elementTypeClass, generateId } from '../../lib/screenplay/format';
import { detectElementType } from '../../lib/screenplay/detect';

export interface ScreenplayEditorProps {
  template?: TemplateType;
  initialContent?: string;
  onChange?: (content: string) => void;
  onElementsChange?: (elements: ScreenplayElement[]) => void;
}

const SHORTCUTS: KeyboardShortcut[] = [
  { key: '1', ctrl: true, shift: true, elementType: 'sceneHeading', label: 'Scene Heading' },
  { key: '2', ctrl: true, shift: true, elementType: 'action', label: 'Action' },
  { key: '3', ctrl: true, shift: true, elementType: 'character', label: 'Character' },
  { key: '4', ctrl: true, shift: true, elementType: 'dialogue', label: 'Dialogue' },
  { key: '5', ctrl: true, shift: true, elementType: 'parenthetical', label: 'Parenthetical' },
  { key: '6', ctrl: true, shift: true, elementType: 'transition', label: 'Transition' },
];

export const ScreenplayEditor: Component<ScreenplayEditorProps> = (props) => {
  const [content, setContent] = createSignal(props.initialContent || '');
  const [currentType, setCurrentType] = createSignal<ScreenplayElementType>('action');
  const [template] = createSignal(props.template || 'standard');

  let textareaRef: HTMLTextAreaElement | undefined;

  const elements = createMemo(() => {
    return formatScreenplay(content(), template(), detectElementType).elements;
  });

  onMount(() => {
    if (textareaRef) {
      textareaRef.focus();
    }
  });

  const handleInput = (e: Event) => {
    const target = e.target as HTMLTextAreaElement;
    const newContent = target.value;
    setContent(newContent);
    props.onChange?.(newContent);

    const cursorPos = target.selectionStart;
    const textBeforeCursor = newContent.substring(0, cursorPos);
    const lastLine = textBeforeCursor.split('\n').pop() || '';
    const detected = detectElementType(lastLine);
    setCurrentType(detected);
  };

  const handleKeyDown = (e: KeyboardEvent) => {
    for (const shortcut of SHORTCUTS) {
      const matchesCtrl = shortcut.ctrl === e.ctrlKey;
      const matchesShift = shortcut.shift === e.shiftKey;
      const matchesAlt = (shortcut.alt || false) === e.altKey;
      const matchesKey = e.key.toLowerCase() === shortcut.key.toLowerCase();

      if (matchesKey && matchesCtrl && matchesShift && matchesAlt) {
        e.preventDefault();
        setCurrentType(shortcut.elementType);
        break;
      }
    }

    if (e.key === 'Enter') {
      const target = e.target as HTMLTextAreaElement;
      const cursorPos = target.selectionStart;
      const textBefore = content().substring(0, cursorPos);
      const lastLine = textBefore.split('\n').pop() || '';
      const detected = detectElementType(lastLine);

      if (detected === 'dialogue' || detected === 'parenthetical') {
        // Keep dialogue/parenthetical context on Enter
        return;
      }

      if (detected === 'character') {
        setCurrentType('dialogue');
      } else if (detected === 'sceneHeading' || detected === 'action') {
        setCurrentType('action');
      }
    }
  };

  const insertElement = (type: ScreenplayElementType) => {
    const prefixes: Record<ScreenplayElementType, string> = {
      sceneHeading: 'INT. ',
      action: '',
      character: '        ',
      dialogue: '',
      parenthetical: '(',
      transition: 'CUT TO:',
      note: '[NOTE: ',
      retained: '[RETAINED: ',
      centered: '',
    };

    const prefix = prefixes[type] || '';
    const newContent = content() + '\n' + prefix;
    setContent(newContent);
    setCurrentType(type);
    props.onChange?.(newContent);

    if (textareaRef) {
      textareaRef.focus();
      textareaRef.selectionStart = newContent.length;
      textareaRef.selectionEnd = newContent.length;
    }
  };

  const templateConfig = getTemplate(template());

  return (
    <div class="screenplay-editor-container">
      <div class="screenplay-toolbar">
        <span class="current-type">{currentType()}</span>
        <div class="shortcuts">
          {SHORTCUTS.map((s) => (
            <button
              class="shortcut-btn"
              onClick={() => insertElement(s.elementType)}
              title={`${s.label} (Ctrl+Shift+${s.key.toUpperCase()})`}
            >
              {s.label}
            </button>
          ))}
        </div>
      </div>
      <textarea
        ref={textareaRef}
        value={content()}
        onInput={handleInput}
        onKeyDown={handleKeyDown}
        class={`screenplay-textarea ${elementTypeClass(currentType())}`}
        style={{
          'font-family': templateConfig.fontFamily,
          'font-size': `${templateConfig.fontSize}px`,
          'line-height': '1.5',
          'white-space': 'pre-wrap',
          'tab-size': '4',
        }}
        placeholder="Start writing your screenplay..."
      />
    </div>
  );
};

export default ScreenplayEditor;
