import React, { CSSProperties, useMemo } from 'react';
import { useNode, UserComponent } from '@craftjs/core';
import DOMPurify from 'dompurify';

interface HtmlBlockProps {
  code: string;
  style?: CSSProperties;
  aiName?: string;
  node_id?: string;
}

const PURIFY_CONFIG = {
  ALLOWED_TAGS: [
    'a','p','br','hr','div','span','section','article',
    'header','footer','main','aside','nav',
    'ul','ol','li',
    'h1','h2','h3','h4','h5','h6',
    'em','strong','b','i','u','s',
    'blockquote','code','pre',
    'img','figure','figcaption',
    'iframe',
  ],
  ALLOWED_ATTR: [
    'href','src','alt','title','target','rel',
    'width','height','class',
    'allowfullscreen','allow','frameborder',
  ],
  ALLOWED_URI_REGEXP: /^(?:(?:https?|mailto|tel|data:image\/[a-z]+;base64,):|[^a-z]|[a-z+.-]+(?:[^a-z+.\-:]|$))/i,
  FORBID_TAGS: ['script','style','object','embed','link','meta','form','input','button','select','textarea'],
  FORBID_ATTR: [/^on/i],
};

export function purifyHtml(input: string): string {
  return DOMPurify.sanitize(input || '', PURIFY_CONFIG as any) as unknown as string;
}

export const HtmlBlock: UserComponent<HtmlBlockProps> = ({ code = '', style = {} }) => {
  const { connectors: { connect, drag }, selected } = useNode((node) => ({ selected: node.events.selected }));
  const clean = useMemo(() => purifyHtml(code), [code]);
  const setRef = (ref: HTMLElement | null): void => { if (ref) connect(drag(ref)); };
  return React.createElement('div', {
    ref: setRef,
    style: {
      minHeight: '40px',
      outline: selected ? '2px solid #3b82f6' : 'none',
      ...style,
    },
    dangerouslySetInnerHTML: { __html: clean },
  });
};

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

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

  return (
    <div style={{ padding: '12px', display: 'flex', flexDirection: 'column', gap: '14px' }}>
      <div style={{
        padding: '8px 10px',
        background: '#44200a',
        border: '1px solid #92400e',
        borderRadius: 6,
        fontSize: 11,
        color: '#fbbf24',
        lineHeight: 1.4,
      }}>
        This block renders raw HTML. Use with caution.
      </div>

      <div>
        <label style={{ fontSize: 11, color: '#a1a1aa', display: 'block', marginBottom: 6 }}>HTML Code</label>
        <textarea
          value={props.code || ''}
          onChange={(e) => setProp((p: HtmlBlockProps) => { p.code = e.target.value; })}
          placeholder="<div>Your HTML here...</div>"
          rows={16}
          style={{
            width: '100%',
            padding: '10px',
            background: '#1a1a2e',
            color: '#a5f3fc',
            border: '1px solid #3f3f46',
            borderRadius: 6,
            fontSize: 12,
            fontFamily: '"Source Code Pro", "Fira Code", monospace',
            lineHeight: 1.5,
            resize: 'vertical',
            boxSizing: 'border-box',
            whiteSpace: 'pre',
            tabSize: 2,
          }}
        />
      </div>

      {/* Outer container style */}
      <div>
        <label style={{ fontSize: 11, color: '#a1a1aa', display: 'block', marginBottom: 6 }}>Padding</label>
        <div style={{ display: 'flex', gap: 4, flexWrap: 'wrap' }}>
          {['0px', '8px', '16px', '24px', '32px'].map((p) => (
            <button
              key={p}
              onClick={() => setProp((pr: HtmlBlockProps) => { pr.style = { ...pr.style, padding: p }; })}
              style={{
                padding: '4px 10px', fontSize: 11, borderRadius: 4, cursor: 'pointer',
                border: '1px solid #3f3f46',
                background: props.style?.padding === p ? '#3b82f6' : '#27272a',
                color: '#e4e4e7',
              }}
            >
              {p}
            </button>
          ))}
        </div>
      </div>
    </div>
  );
};

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

HtmlBlock.craft = {
  displayName: 'HTML',
  props: {
    code: '',
    style: {},
  },
  rules: {
    canDrag: () => true,
    canMoveIn: () => false,
    canMoveOut: () => true,
  },
  related: {
    settings: HtmlBlockSettings,
  },
};

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

(HtmlBlock as any).toHtml = (props: HtmlBlockProps, _childrenHtml: string) => {
  // Output the raw code as-is
  return { html: props.code || '' };
};
