import { Video } from '@os-design/core';
import { Video as VideoIcon } from '@os-design/icons';
import { EditorBlock } from 'draft-js';
import React from 'react';
import changeBlock from '../utils/changeBlock.js';
import getCurrentBlock from '../utils/getCurrentBlock.js';
import Figure from './Figure.js';
import FigureCaption from './FigureCaption.js';
import type { BlockProps, BlockToolbarItem } from './types.js';

const VideoBlock: React.FC<BlockProps> = (props) => {
  const { block } = props;
  const data = block.getData();
  const src = data.get('src');

  if (!src) return null;

  return (
    <Figure>
      <Video src={src} title={block.getText()} />
      <FigureCaption>
        <EditorBlock {...props} />
      </FigureCaption>
    </Figure>
  );
};

const videoTypes = [
  /**
   * YouTube. Supported formats:
   * https://www.youtube.com/watch?v=FJIhWbUt600&ab_channel=IlyaOrdin
   * https://www.youtube.com/embed/FJIhWbUt600
   * https://youtu.be/FJIhWbUt600
   */
  {
    re: /^https:\/\/(?:www\.youtube\.com\/(?:watch\?v=|embed\/)|youtu\.be\/)([A-z0-9-_]*).*$/,
    getUrl: (id: string) => `https://www.youtube.com/embed/${id}`,
  },
  /**
   * RuTube. Supported formats:
   * https://rutube.ru/video/d00526135b2b96d272f6d89b486036c1/
   * https://rutube.ru/play/embed/d00526135b2b96d272f6d89b486036c1
   */
  {
    re: /^https:\/\/rutube\.ru\/(?:video|play\/embed)\/([a-z0-9]*)\/?$/,
    getUrl: (id: string) => `https://rutube.ru/play/embed/${id}`,
  },
];

const detectVideo = (url: string) => {
  for (const { re, getUrl } of videoTypes) {
    const groups = url.match(re);
    if (groups && groups[1]) return getUrl(groups[1]);
  }
  return null;
};

export const VIDEO_BLOCK = 'atomic:video';

const videoBlock: BlockToolbarItem = {
  type: VIDEO_BLOCK,
  component: VideoBlock,
  icon: <VideoIcon />,
  onClick: ({ value, onChange }) => {
    const url = prompt('Insert a link to YouTube or RuTube');
    if (!url) return;

    const src = detectVideo(url);
    if (!src) return;

    const currentBlock = getCurrentBlock(value);
    const nextEditorState = changeBlock(value, currentBlock, VIDEO_BLOCK, {
      src,
    });

    onChange(nextEditorState);
  },
};

export default videoBlock;
