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

interface SocialLink {
  platform: string;
  url: string;
}

interface SocialLinksProps {
  links?: SocialLink[];
  iconSize?: string;
  iconColor?: string;
  iconBgColor?: string;
  iconShape?: 'none' | 'circle' | 'square' | 'rounded';
  gap?: string;
  alignment?: 'left' | 'center' | 'right';
  style?: CSSProperties;
}

const platformIcons: Record<string, string> = {
  facebook: 'fa-facebook',
  twitter: 'fa-twitter',
  instagram: 'fa-instagram',
  linkedin: 'fa-linkedin',
  youtube: 'fa-youtube',
  github: 'fa-github',
  tiktok: 'fa-music',
  pinterest: 'fa-pinterest',
  snapchat: 'fa-snapchat',
  whatsapp: 'fa-whatsapp',
  spotify: 'fa-spotify',
  twitch: 'fa-twitch',
};

const platformLabels: Record<string, string> = {
  facebook: 'Facebook',
  twitter: 'Twitter / X',
  instagram: 'Instagram',
  linkedin: 'LinkedIn',
  youtube: 'YouTube',
  github: 'GitHub',
  tiktok: 'TikTok',
  pinterest: 'Pinterest',
  snapchat: 'Snapchat',
  whatsapp: 'WhatsApp',
  spotify: 'Spotify',
  twitch: 'Twitch',
};

const allPlatforms = Object.keys(platformIcons);

const defaultLinks: SocialLink[] = [
  { platform: 'facebook', url: '#' },
  { platform: 'twitter', url: '#' },
  { platform: 'instagram', url: '#' },
  { platform: 'linkedin', url: '#' },
];

const getShapeStyle = (shape: string, size: string): CSSProperties => {
  if (shape === 'none') return {};
  const numSize = parseInt(size) || 24;
  const boxSize = `${numSize + 16}px`;
  const base: CSSProperties = {
    display: 'inline-flex',
    alignItems: 'center',
    justifyContent: 'center',
    width: boxSize,
    height: boxSize,
  };
  if (shape === 'circle') return { ...base, borderRadius: '50%' };
  if (shape === 'square') return { ...base, borderRadius: '0' };
  if (shape === 'rounded') return { ...base, borderRadius: '6px' };
  return base;
};

const alignMap: Record<string, string> = {
  left: 'flex-start',
  center: 'center',
  right: 'flex-end',
};

export const SocialLinks: UserComponent<SocialLinksProps> = ({
  links = defaultLinks,
  iconSize = '20px',
  iconColor = '#ffffff',
  iconBgColor = '#374151',
  iconShape = 'circle',
  gap = '10px',
  alignment = 'center',
  style = {},
}) => {
  const {
    connectors: { connect, drag },
    selected,
  } = useNode((node) => ({
    selected: node.events.selected,
  }));

  return (
    <div
      ref={(ref: HTMLDivElement | null): void => { if (ref) connect(drag(ref)); }}
      style={{
        display: 'flex',
        flexWrap: 'wrap',
        gap,
        justifyContent: alignMap[alignment] || 'center',
        alignItems: 'center',
        outline: selected ? '2px solid #3b82f6' : 'none',
        ...style,
      }}
    >
      {links.map((link, i) => {
        const iconClass = platformIcons[link.platform] || 'fa-link';
        const shapeStyle = getShapeStyle(iconShape, iconSize);
        const hasBg = iconShape !== 'none';

        return (
          <a
            key={i}
            href={link.url || '#'}
            target="_blank"
            rel="noopener noreferrer"
            onClick={(e) => e.preventDefault()}
            title={platformLabels[link.platform] || link.platform}
            style={{
              textDecoration: 'none',
              color: iconColor,
              backgroundColor: hasBg ? iconBgColor : 'transparent',
              transition: 'opacity 0.2s',
              ...shapeStyle,
            }}
          >
            <i className={`fa ${iconClass}`} style={{ fontSize: iconSize }} />
          </a>
        );
      })}
    </div>
  );
};

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

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

  const links = props.links || defaultLinks;

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

  const updateLink = (index: number, field: keyof SocialLink, value: string) => {
    setProp((p: SocialLinksProps) => {
      const updated = [...(p.links || defaultLinks)];
      updated[index] = { ...updated[index], [field]: value };
      p.links = updated;
    });
  };

  const addLink = (platform: string) => {
    setProp((p: SocialLinksProps) => {
      p.links = [...(p.links || defaultLinks), { platform, url: '#' }];
    });
  };

  const removeLink = (index: number) => {
    setProp((p: SocialLinksProps) => {
      const updated = [...(p.links || defaultLinks)];
      updated.splice(index, 1);
      p.links = updated;
    });
  };

  const usedPlatforms = new Set(links.map((l) => l.platform));
  const availablePlatforms = allPlatforms.filter((p) => !usedPlatforms.has(p));

  const sizePresets = ['14px', '18px', '20px', '24px', '28px', '32px'];
  const gapPresets = ['4px', '8px', '10px', '14px', '20px'];
  const iconColorPresets = ['#ffffff', '#18181b', '#3b82f6', '#10b981', '#ef4444', '#8b5cf6', '#f59e0b', '#a1a1aa'];
  const bgColorPresets = ['#374151', '#18181b', '#3b82f6', '#10b981', '#ef4444', '#8b5cf6', '#0ea5e9', 'transparent'];

  return (
    <div style={{ padding: '12px', display: 'flex', flexDirection: 'column', gap: '14px' }}>
      {/* Links Editor */}
      <div>
        <label style={{ fontSize: 11, color: '#a1a1aa', display: 'block', marginBottom: 6 }}>Social Links</label>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
          {links.map((link, 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' }}>
                <span style={{ fontSize: 14, width: 20, textAlign: 'center', flex: 'none' }}>
                  <i className={`fa ${platformIcons[link.platform] || 'fa-link'}`} style={{ color: '#a1a1aa' }} />
                </span>
                <span style={{ fontSize: 11, color: '#e4e4e7', flex: 1 }}>
                  {platformLabels[link.platform] || link.platform}
                </span>
                <button
                  onClick={() => removeLink(i)}
                  style={{ padding: '2px 6px', fontSize: 11, background: '#ef4444', color: '#fff', border: 'none', borderRadius: 4, cursor: 'pointer', flex: 'none' }}
                >
                  X
                </button>
              </div>
              <input
                type="text"
                value={link.url}
                onChange={(e) => updateLink(i, 'url', e.target.value)}
                placeholder="https://..."
                style={inputStyle}
              />
            </div>
          ))}
        </div>

        {availablePlatforms.length > 0 && (
          <div style={{ marginTop: 6 }}>
            <select
              onChange={(e) => {
                if (e.target.value) {
                  addLink(e.target.value);
                  e.target.value = '';
                }
              }}
              defaultValue=""
              style={{ ...inputStyle, width: '100%', padding: '6px', cursor: 'pointer' }}
            >
              <option value="">+ Add Platform...</option>
              {availablePlatforms.map((p) => (
                <option key={p} value={p}>{platformLabels[p]}</option>
              ))}
            </select>
          </div>
        )}
      </div>

      {/* Alignment */}
      <div>
        <label style={{ fontSize: 11, color: '#a1a1aa', display: 'block', marginBottom: 6 }}>Alignment</label>
        <div style={{ display: 'flex', gap: 4 }}>
          {(['left', 'center', 'right'] as const).map((a) => (
            <button
              key={a}
              onClick={() => setProp((p: SocialLinksProps) => { p.alignment = a; })}
              style={{
                padding: '4px 10px', fontSize: 11, borderRadius: 4, cursor: 'pointer',
                border: '1px solid #3f3f46',
                background: props.alignment === a ? '#3b82f6' : '#27272a',
                color: '#e4e4e7',
                textTransform: 'capitalize',
              }}
            >
              {a}
            </button>
          ))}
        </div>
      </div>

      {/* Icon Shape */}
      <div>
        <label style={{ fontSize: 11, color: '#a1a1aa', display: 'block', marginBottom: 6 }}>Icon Shape</label>
        <div style={{ display: 'flex', gap: 4, flexWrap: 'wrap' }}>
          {(['none', 'circle', 'square', 'rounded'] as const).map((s) => (
            <button
              key={s}
              onClick={() => setProp((p: SocialLinksProps) => { p.iconShape = s; })}
              style={{
                padding: '4px 10px', fontSize: 11, borderRadius: 4, cursor: 'pointer',
                border: '1px solid #3f3f46',
                background: props.iconShape === s ? '#3b82f6' : '#27272a',
                color: '#e4e4e7',
                textTransform: 'capitalize',
              }}
            >
              {s}
            </button>
          ))}
        </div>
      </div>

      {/* Icon Size */}
      <div>
        <label style={{ fontSize: 11, color: '#a1a1aa', display: 'block', marginBottom: 6 }}>Icon Size</label>
        <div style={{ display: 'flex', gap: 4, flexWrap: 'wrap' }}>
          {sizePresets.map((s) => (
            <button
              key={s}
              onClick={() => setProp((p: SocialLinksProps) => { p.iconSize = s; })}
              style={{
                padding: '4px 8px', fontSize: 11, borderRadius: 4, cursor: 'pointer',
                border: '1px solid #3f3f46',
                background: props.iconSize === s ? '#3b82f6' : '#27272a',
                color: '#e4e4e7',
              }}
            >
              {s}
            </button>
          ))}
        </div>
      </div>

      {/* Icon Color */}
      <div>
        <label style={{ fontSize: 11, color: '#a1a1aa', display: 'block', marginBottom: 6 }}>Icon Color</label>
        <div style={{ display: 'flex', gap: 4, flexWrap: 'wrap' }}>
          {iconColorPresets.map((c) => (
            <button
              key={c}
              onClick={() => setProp((p: SocialLinksProps) => { p.iconColor = c; })}
              style={{
                width: 24, height: 24, borderRadius: 4, border: '1px solid #3f3f46',
                backgroundColor: c, cursor: 'pointer',
                outline: props.iconColor === c ? '2px solid #3b82f6' : 'none',
                outlineOffset: 1,
              }}
            />
          ))}
        </div>
      </div>

      {/* Icon Background Color */}
      {props.iconShape !== 'none' && (
        <div>
          <label style={{ fontSize: 11, color: '#a1a1aa', display: 'block', marginBottom: 6 }}>Icon Background</label>
          <div style={{ display: 'flex', gap: 4, flexWrap: 'wrap' }}>
            {bgColorPresets.map((c) => (
              <button
                key={c}
                onClick={() => setProp((p: SocialLinksProps) => { p.iconBgColor = c; })}
                style={{
                  width: 24, height: 24, borderRadius: 4,
                  border: c === 'transparent' ? '2px dashed #3f3f46' : '1px solid #3f3f46',
                  backgroundColor: c === 'transparent' ? undefined : c,
                  cursor: 'pointer',
                  outline: props.iconBgColor === c ? '2px solid #3b82f6' : 'none',
                  outlineOffset: 1,
                }}
              />
            ))}
          </div>
        </div>
      )}

      {/* Gap */}
      <div>
        <label style={{ fontSize: 11, color: '#a1a1aa', display: 'block', marginBottom: 6 }}>Gap</label>
        <div style={{ display: 'flex', gap: 4, flexWrap: 'wrap' }}>
          {gapPresets.map((g) => (
            <button
              key={g}
              onClick={() => setProp((p: SocialLinksProps) => { p.gap = g; })}
              style={{
                padding: '4px 8px', fontSize: 11, borderRadius: 4, cursor: 'pointer',
                border: '1px solid #3f3f46',
                background: props.gap === g ? '#3b82f6' : '#27272a',
                color: '#e4e4e7',
              }}
            >
              {g}
            </button>
          ))}
        </div>
      </div>
    </div>
  );
};

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

SocialLinks.craft = {
  displayName: 'Social Links',
  props: {
    links: defaultLinks,
    iconSize: '20px',
    iconColor: '#ffffff',
    iconBgColor: '#374151',
    iconShape: 'circle',
    gap: '10px',
    alignment: 'center',
    style: {},
  },
  rules: {
    canDrag: () => true,
    canMoveIn: () => false,
    canMoveOut: () => true,
  },
  related: {
    settings: SocialLinksSettings,
  },
};

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

(SocialLinks as any).toHtml = (props: SocialLinksProps, _childrenHtml: string) => {
  const links = props.links || defaultLinks;
  const iconSize = props.iconSize || '20px';
  const iconColor = props.iconColor || '#ffffff';
  const iconBgColor = props.iconBgColor || '#374151';
  const iconShape = props.iconShape || 'circle';
  const gap = props.gap || '10px';
  const alignment = props.alignment || 'center';
  const hasBg = iconShape !== 'none';

  const wrapperStyle = cssPropsToString({
    display: 'flex',
    flexWrap: 'wrap',
    gap,
    justifyContent: alignMap[alignment] || 'center',
    alignItems: 'center',
    ...props.style,
  });

  const numSize = parseInt(iconSize) || 20;
  const boxSize = `${numSize + 16}px`;

  const getShapeStr = (): string => {
    const parts: string[] = [
      `display:inline-flex`,
      `align-items:center`,
      `justify-content:center`,
      `width:${boxSize}`,
      `height:${boxSize}`,
    ];
    if (iconShape === 'circle') parts.push('border-radius:50%');
    else if (iconShape === 'square') parts.push('border-radius:0');
    else if (iconShape === 'rounded') parts.push('border-radius:6px');
    return parts.join(';');
  };

  const linksHtml = links.map((link) => {
    const iconClass = platformIcons[link.platform] || 'fa-link';
    const title = platformLabels[link.platform] || link.platform;
    let aStyle = `text-decoration:none;color:${iconColor};background-color:${hasBg ? iconBgColor : 'transparent'}`;
    if (hasBg) {
      aStyle += `;${getShapeStr()}`;
    }
    return `<a href="${link.url || '#'}" target="_blank" rel="noopener noreferrer" title="${title}" style="${aStyle}"><i class="fa ${iconClass}" style="font-size:${iconSize}"></i></a>`;
  }).join('\n  ');

  return {
    html: `<div${wrapperStyle ? ` style="${wrapperStyle}"` : ''}>
  ${linksHtml}
</div>`,
  };
};
