import React, { CSSProperties, useCallback, useRef, useEffect } from 'react';
import { useNode, UserComponent } from '@craftjs/core';
import { cssPropsToString } from '../../utils/style-helpers';
import { SettingsTabs } from '../../ui/SettingsTabs';
import { TypographyControl } from '../../ui/TypographyControl';
import { AdvancedTab } from '../../ui/AdvancedTab';

interface TextBlockProps {
  text?: string;
  style?: CSSProperties;
  cssId?: string;
  cssClass?: string;
  hideOnDesktop?: boolean;
  hideOnTablet?: boolean;
  hideOnMobile?: boolean;
  animation?: string;
  animationDelay?: string;
}

export const TextBlock: UserComponent<TextBlockProps> = ({
  text = 'Start typing here...',
  style = {},
}) => {
  const {
    connectors: { connect, drag },
    selected,
    actions: { setProp },
  } = useNode((node) => ({
    selected: node.events.selected,
  }));

  const elRef = useRef<HTMLParagraphElement | null>(null);
  const editedTextRef = useRef<string | null>(null);

  const commitText = useCallback(() => {
    if (elRef.current) {
      const newText = elRef.current.innerText;
      editedTextRef.current = newText;
      setProp((p: TextBlockProps) => { p.text = newText; });
    }
  }, [setProp]);

  const handleBlur = useCallback(() => { commitText(); }, [commitText]);

  useEffect(() => {
    if (!selected && editedTextRef.current !== null) {
      setProp((p: TextBlockProps) => { p.text = editedTextRef.current!; });
      editedTextRef.current = null;
    }
  }, [selected, setProp]);

  useEffect(() => {
    if (elRef.current && !selected && editedTextRef.current === null) {
      elRef.current.innerText = text || '';
    }
  }, [text, selected]);

  return (
    <p
      ref={(ref: HTMLParagraphElement | null) => {
        elRef.current = ref;
        if (ref) connect(drag(ref));
      }}
      contentEditable={selected}
      suppressContentEditableWarning
      onBlur={handleBlur}
      onInput={() => { if (elRef.current) editedTextRef.current = elRef.current.innerText; }}
      style={{
        outline: 'none',
        cursor: selected ? 'text' : 'pointer',
        minHeight: '1em',
        ...style,
      }}
    />
  );
};

/* ---------- Settings panel ---------- */

const TextBlockSettings: React.FC = () => {
  const { actions: { setProp }, props } = useNode((node) => ({
    props: node.data.props as TextBlockProps,
  }));

  return (
    <SettingsTabs
      general={
        <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
          <div>
            <label style={{ fontSize: 11, fontWeight: 600, color: '#a1a1aa', display: 'block', marginBottom: 6, textTransform: 'uppercase', letterSpacing: '0.3px' }}>Text Content</label>
            <textarea
              value={props.text || ''}
              onChange={(e) => setProp((p: TextBlockProps) => { p.text = e.target.value; })}
              rows={4}
              style={{ width: '100%', padding: '6px 8px', background: '#27272a', color: '#e4e4e7', border: '1px solid #3f3f46', borderRadius: 4, fontSize: 12, resize: 'vertical' }}
            />
          </div>
        </div>
      }
      style={
        <TypographyControl
          style={props.style || {}}
          onChange={(updates) => setProp((p: TextBlockProps) => { p.style = { ...p.style, ...updates }; })}
        />
      }
      advanced={
        <AdvancedTab
          style={props.style || {}}
          onStyleChange={(updates) => setProp((p: TextBlockProps) => { p.style = { ...p.style, ...updates }; })}
          cssId={props.cssId || ''}
          onCssIdChange={(id) => setProp((p: TextBlockProps) => { p.cssId = id; })}
          cssClass={props.cssClass || ''}
          onCssClassChange={(cls) => setProp((p: TextBlockProps) => { p.cssClass = cls; })}
          hideOnDesktop={props.hideOnDesktop}
          onHideOnDesktopChange={(v) => setProp((p: TextBlockProps) => { p.hideOnDesktop = v; })}
          hideOnTablet={props.hideOnTablet}
          onHideOnTabletChange={(v) => setProp((p: TextBlockProps) => { p.hideOnTablet = v; })}
          hideOnMobile={props.hideOnMobile}
          onHideOnMobileChange={(v) => setProp((p: TextBlockProps) => { p.hideOnMobile = v; })}
          animation={props.animation}
          onAnimationChange={(v) => setProp((p: TextBlockProps) => { p.animation = v; })}
          animationDelay={props.animationDelay}
          onAnimationDelayChange={(v) => setProp((p: TextBlockProps) => { p.animationDelay = v; })}
        />
      }
    />
  );
};

/* ---------- Craft config ---------- */

TextBlock.craft = {
  displayName: 'Text',
  props: {
    text: 'Start typing here...',
    style: {
      fontSize: '16px',
      lineHeight: '1.6',
      color: '#3f3f46',
    },
  },
  rules: {
    canDrag: () => true,
    canMoveIn: () => false,
    canMoveOut: () => true,
  },
  related: {
    settings: TextBlockSettings,
  },
};

/* ---------- HTML export ---------- */

(TextBlock as any).toHtml = (props: TextBlockProps, _childrenHtml: string) => {
  const styleStr = cssPropsToString(props.style);
  const escapedText = (props.text || '').replace(/</g, '&lt;').replace(/>/g, '&gt;');
  return { html: `<p${styleStr ? ` style="${styleStr}"` : ''}>${escapedText}</p>` };
};
