import React, { CSSProperties } from 'react';
import { useNode, UserComponent } from '@craftjs/core';
import { cssPropsToString } from '../../utils/style-helpers';

interface Counter {
  number: number;
  suffix: string;
  label: string;
}

interface NumberCounterProps {
  counters?: Counter[];
  columns?: number;
  numberColor?: string;
  labelColor?: string;
  numberSize?: string;
  style?: CSSProperties;
}

const defaultCounters: Counter[] = [
  { number: 150, suffix: '+', label: 'Projects' },
  { number: 50, suffix: '+', label: 'Clients' },
  { number: 10, suffix: '', label: 'Years' },
  { number: 99, suffix: '%', label: 'Satisfaction' },
];

export const NumberCounter: UserComponent<NumberCounterProps> = ({
  counters = defaultCounters,
  columns = 4,
  numberColor = '#3b82f6',
  labelColor = '#6b7280',
  numberSize = '48px',
  style = {},
}) => {
  const {
    connectors: { connect, drag },
    selected,
  } = useNode((node) => ({
    selected: node.events.selected,
  }));

  const items = counters.length > 0 ? counters : defaultCounters;

  return (
    <section
      ref={(ref: HTMLElement | null): void => { if (ref) connect(drag(ref)); }}
      style={{
        padding: '60px 20px',
        backgroundColor: '#ffffff',
        outline: selected ? '2px solid #3b82f6' : 'none',
        ...style,
      }}
    >
      <div
        style={{
          maxWidth: '1100px',
          margin: '0 auto',
          display: 'grid',
          gridTemplateColumns: `repeat(${columns}, 1fr)`,
          gap: '32px',
          textAlign: 'center',
        }}
      >
        {items.map((counter, i) => (
          <div key={i} style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: '8px' }}>
            <span style={{
              fontSize: numberSize,
              fontWeight: '700',
              color: numberColor,
              lineHeight: '1.1',
              fontFamily: 'Inter, sans-serif',
            }}>
              {counter.number}{counter.suffix}
            </span>
            <span style={{
              fontSize: '15px',
              color: labelColor,
              fontFamily: 'Inter, sans-serif',
              fontWeight: '500',
            }}>
              {counter.label}
            </span>
          </div>
        ))}
      </div>
    </section>
  );
};

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

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

  const items = props.counters || defaultCounters;

  const labelStyle: CSSProperties = { fontSize: 11, color: '#a1a1aa', display: 'block', marginBottom: 6 };
  const inputStyle: CSSProperties = {
    width: '100%', padding: '3px 6px', background: '#27272a', color: '#e4e4e7',
    border: '1px solid #3f3f46', borderRadius: 4, fontSize: 11,
  };

  const columnOptions = [2, 3, 4, 5, 6];
  const sizePresets = ['32px', '40px', '48px', '56px', '64px'];
  const numberColorPresets = ['#3b82f6', '#10b981', '#8b5cf6', '#ef4444', '#f59e0b', '#18181b', '#ec4899', '#0ea5e9'];
  const labelColorPresets = ['#6b7280', '#374151', '#9ca3af', '#a1a1aa', '#64748b', '#18181b'];
  const bgPresets = ['#ffffff', '#f8fafc', '#f1f5f9', '#18181b', '#0f172a'];

  const updateCounter = (index: number, field: keyof Counter, value: string | number) => {
    setProp((p: NumberCounterProps) => {
      const updated = [...(p.counters || defaultCounters)];
      updated[index] = { ...updated[index], [field]: value };
      p.counters = updated;
    });
  };

  const addCounter = () => {
    setProp((p: NumberCounterProps) => {
      p.counters = [...(p.counters || defaultCounters), { number: 100, suffix: '+', label: 'New Stat' }];
    });
  };

  const removeCounter = (index: number) => {
    setProp((p: NumberCounterProps) => {
      const updated = [...(p.counters || defaultCounters)];
      updated.splice(index, 1);
      p.counters = updated;
    });
  };

  return (
    <div style={{ padding: '12px', display: 'flex', flexDirection: 'column', gap: '14px' }}>
      {/* Columns */}
      <div>
        <label style={labelStyle}>Columns</label>
        <div style={{ display: 'flex', gap: 4 }}>
          {columnOptions.map((n) => (
            <button
              key={n}
              onClick={() => setProp((p: NumberCounterProps) => { p.columns = n; })}
              style={{
                padding: '4px 10px', fontSize: 11, borderRadius: 4, cursor: 'pointer',
                border: '1px solid #3f3f46',
                background: (props.columns || 4) === n ? '#3b82f6' : '#27272a',
                color: '#e4e4e7',
              }}
            >
              {n}
            </button>
          ))}
        </div>
      </div>

      {/* Number Size */}
      <div>
        <label style={labelStyle}>Number Size</label>
        <div style={{ display: 'flex', gap: 4, flexWrap: 'wrap' }}>
          {sizePresets.map((s) => (
            <button
              key={s}
              onClick={() => setProp((p: NumberCounterProps) => { p.numberSize = s; })}
              style={{
                padding: '4px 8px', fontSize: 11, borderRadius: 4, cursor: 'pointer',
                border: '1px solid #3f3f46',
                background: (props.numberSize || '48px') === s ? '#3b82f6' : '#27272a',
                color: (props.numberSize || '48px') === s ? '#fff' : '#e4e4e7',
              }}
            >
              {s}
            </button>
          ))}
        </div>
      </div>

      {/* Number Color */}
      <div>
        <label style={labelStyle}>Number Color</label>
        <div style={{ display: 'flex', gap: 4, flexWrap: 'wrap' }}>
          {numberColorPresets.map((c) => (
            <button
              key={c}
              onClick={() => setProp((p: NumberCounterProps) => { p.numberColor = c; })}
              style={{
                width: 24, height: 24, borderRadius: 4, border: '1px solid #3f3f46',
                backgroundColor: c, cursor: 'pointer',
                outline: (props.numberColor || '#3b82f6') === c ? '2px solid #3b82f6' : 'none',
                outlineOffset: 1,
              }}
            />
          ))}
        </div>
      </div>

      {/* Label Color */}
      <div>
        <label style={labelStyle}>Label Color</label>
        <div style={{ display: 'flex', gap: 4, flexWrap: 'wrap' }}>
          {labelColorPresets.map((c) => (
            <button
              key={c}
              onClick={() => setProp((p: NumberCounterProps) => { p.labelColor = c; })}
              style={{
                width: 24, height: 24, borderRadius: 4, border: '1px solid #3f3f46',
                backgroundColor: c, cursor: 'pointer',
                outline: (props.labelColor || '#6b7280') === c ? '2px solid #3b82f6' : 'none',
                outlineOffset: 1,
              }}
            />
          ))}
        </div>
      </div>

      {/* Background */}
      <div>
        <label style={labelStyle}>Background</label>
        <div style={{ display: 'flex', gap: 4, flexWrap: 'wrap' }}>
          {bgPresets.map((c) => (
            <button
              key={c}
              onClick={() => setProp((p: NumberCounterProps) => { p.style = { ...p.style, backgroundColor: c }; })}
              style={{
                width: 24, height: 24, borderRadius: 4, border: '1px solid #3f3f46',
                backgroundColor: c, cursor: 'pointer',
                outline: props.style?.backgroundColor === c ? '2px solid #3b82f6' : 'none',
                outlineOffset: 1,
              }}
            />
          ))}
        </div>
      </div>

      {/* Counters */}
      <div>
        <label style={labelStyle}>Counters</label>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
          {items.map((counter, i) => (
            <div key={i} style={{ background: '#1e1e22', borderRadius: 6, padding: 8, display: 'flex', flexDirection: 'column', gap: 4 }}>
              <div style={{ display: 'flex', gap: 4, alignItems: 'center' }}>
                <input
                  type="number"
                  value={counter.number}
                  onChange={(e) => updateCounter(i, 'number', parseInt(e.target.value) || 0)}
                  placeholder="Number"
                  style={{ ...inputStyle, width: 70, flex: 'none' }}
                />
                <input
                  type="text"
                  value={counter.suffix}
                  onChange={(e) => updateCounter(i, 'suffix', e.target.value)}
                  placeholder="Suffix"
                  style={{ ...inputStyle, width: 40, flex: 'none' }}
                />
                <input
                  type="text"
                  value={counter.label}
                  onChange={(e) => updateCounter(i, 'label', e.target.value)}
                  placeholder="Label"
                  style={{ ...inputStyle, flex: 1 }}
                />
                <button
                  onClick={() => removeCounter(i)}
                  style={{ padding: '2px 6px', fontSize: 11, background: '#ef4444', color: '#fff', border: 'none', borderRadius: 4, cursor: 'pointer', flex: 'none' }}
                >
                  X
                </button>
              </div>
            </div>
          ))}
        </div>
        <button
          onClick={addCounter}
          style={{ marginTop: 6, width: '100%', padding: '6px', fontSize: 11, background: '#27272a', color: '#e4e4e7', border: '1px solid #3f3f46', borderRadius: 4, cursor: 'pointer' }}
        >
          + Add Counter
        </button>
      </div>
    </div>
  );
};

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

NumberCounter.craft = {
  displayName: 'Number Counter',
  props: {
    counters: defaultCounters,
    columns: 4,
    numberColor: '#3b82f6',
    labelColor: '#6b7280',
    numberSize: '48px',
    style: { backgroundColor: '#ffffff' },
  },
  rules: {
    canDrag: () => true,
    canMoveIn: () => false,
    canMoveOut: () => true,
  },
  related: {
    settings: NumberCounterSettings,
  },
};

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

(NumberCounter as any).toHtml = (props: NumberCounterProps, _childrenHtml: string) => {
  const esc = (s: any) => String(s ?? "").replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;');
  const {
    counters = defaultCounters,
    columns = 4,
    numberColor = '#3b82f6',
    labelColor = '#6b7280',
    numberSize = '48px',
    style = {},
  } = props;

  const items = counters.length > 0 ? counters : defaultCounters;
  const uid = 'nc_' + Math.random().toString(36).slice(2, 8);

  const sectionStyle = cssPropsToString({
    padding: '60px 20px',
    backgroundColor: '#ffffff',
    ...style,
  });

  const countersHtml = items.map((counter, i) => {
    return `<div style="display:flex;flex-direction:column;align-items:center;gap:8px">
      <span id="${uid}_n${i}" data-target="${counter.number}" data-suffix="${esc(counter.suffix)}" style="font-size:${numberSize};font-weight:700;color:${numberColor};line-height:1.1;font-family:Inter,sans-serif">0${esc(counter.suffix)}</span>
      <span style="font-size:15px;color:${labelColor};font-family:Inter,sans-serif;font-weight:500">${esc(counter.label)}</span>
    </div>`;
  }).join('\n    ');

  return {
    html: `<section${sectionStyle ? ` style="${sectionStyle}"` : ''}>
  <div id="${uid}" style="max-width:1100px;margin:0 auto;display:grid;grid-template-columns:repeat(${columns},1fr);gap:32px;text-align:center">
    ${countersHtml}
  </div>
  <script>
  (function(){
    var uid="${uid}",started=false;
    function animate(){
      if(started)return;started=true;
      for(var i=0;i<${items.length};i++){
        (function(el){
          var target=parseInt(el.getAttribute("data-target")),
              suffix=el.getAttribute("data-suffix")||"",
              current=0,
              step=Math.max(1,Math.floor(target/60)),
              timer=setInterval(function(){
                current+=step;
                if(current>=target){current=target;clearInterval(timer);}
                el.textContent=current+suffix;
              },16);
        })(document.getElementById(uid+"_n"+i));
      }
    }
    if("IntersectionObserver"in window){
      var obs=new IntersectionObserver(function(entries){
        entries.forEach(function(e){if(e.isIntersecting){animate();obs.disconnect();}});
      },{threshold:0.2});
      obs.observe(document.getElementById(uid));
    }else{animate();}
  })();
  </script>
</section>`,
  };
};
