import React from 'react';
import url from 'url';
import { Slice } from './types';
import './figma-slice.scss';

type Data = {
  figmaFileUrl?: string;
  height?: number;
};

export const figmaSlice: Slice<Data> = {
  id: 'figma-slice',
  title: 'Figma Embed',
  render: props => {
    const { figmaFileUrl, height = 500 } = props?.data ?? {};
    if (!figmaFileUrl) {
      return (
        <div className="ks-figma-slice__empty-state">
          <h3>Figma Embed Slice</h3>
          <p>A Figma URL has not been provided yet.</p>
          <p>
            <strong>Getting Started:</strong>
          </p>
          <ol>
            <li>From Figma, copy a share link (not embed code).</li>
            <ol>
              <li>
                For a whole Page, click the share button at the top right, then
                click Copy Link.
              </li>
              <li>
                For a single Frame, right click on the frame and select
                Copy/Past, then Copy Link.
              </li>
            </ol>
            <li>Provide the link in the slice settings.</li>
          </ol>
          <p className="ks-figma-slice__empty-state__note">
            If using a single frame from a page and this slice shows the whole
            page initially, this is because Figma is still working on the single
            frame preview. After a minute, refresh and it should be working.
          </p>
        </div>
      );
    }

    const { host } = url.parse(figmaFileUrl, true);
    if (host !== 'www.figma.com') {
      throw new Error(
        `Provided url needs to be for Figma.com, received "${figmaFileUrl}"`,
      );
    }
    const src = url.format({
      protocol: 'https',
      hostname: 'www.figma.com',
      pathname: '/embed',
      query: {
        // eslint-disable-next-line @typescript-eslint/camelcase
        embed_host: 'share',
        url: figmaFileUrl,
      },
    });
    return (
      <div className="ks-figma-slice">
        <iframe
          src={src}
          width="100%"
          height={height}
          allowFullScreen
          title="Figma"
        />
      </div>
    );
  },
  schema: {
    type: 'object',
    required: ['figmaFileUrl'],
    properties: {
      figmaFileUrl: {
        title: 'Figma Url',
        description: 'Link to Figma file from share url (not embed code)',
        type: 'string',
      },
      height: {
        title: 'Embed Height',
        type: 'number',
        default: 480,
      },
    },
  },
};
