import React, { useEffect, useState } from 'react';
import { as } from 'folds';
import * as css from './GiphyEmbed.css';

const GIPHY_URL_PATTERNS = [
  /(?:https?:\/\/)?(?:www\.)?giphy\.com\/gifs\/(?:[\w-]+-)([a-zA-Z0-9]+)(?:\?|$)/,
  /(?:https?:\/\/)?(?:www\.)?giphy\.com\/embed\/([a-zA-Z0-9]+)(?:\?|$)/,
  /(?:https?:\/\/)?(?:media\.)?giphy\.com\/media\/([a-zA-Z0-9]+)/,
];

export function isGiphyUrl(url: string): boolean {
  return GIPHY_URL_PATTERNS.some((pattern) => pattern.test(url));
}

export function extractGiphyId(url: string): string | null {
  let gifId: string | null = null;
  GIPHY_URL_PATTERNS.some((pattern) => {
    const match = url.match(pattern);
    if (match) {
      const [, id] = match;
      if (id) {
        gifId = id;
        return true;
      }
    }
    return false;
  });
  return gifId;
}

type GiphyEmbedProps = {
  url: string;
};

export const GiphyEmbed = as<'div', GiphyEmbedProps>(({ url, ...props }, ref) => {
  const gifId = extractGiphyId(url);
  const [mediaUrl, setMediaUrl] = useState<string | null>(null);

  useEffect(() => {
    if (!gifId) return;

    // Try to get the direct media URL from Giphy
    // Format: https://i.giphy.com/media/{ID}/giphy.mp4 or giphy.gif
    const mp4Url = `https://i.giphy.com/media/${gifId}/giphy.mp4`;
    setMediaUrl(mp4Url);
  }, [gifId]);

  if (!gifId || !mediaUrl) {
    return null;
  }

  return (
    <div className={css.GiphyEmbed} {...props} ref={ref}>
      <video
        className={css.GiphyVideo}
        src={mediaUrl}
        autoPlay
        loop
        muted
        playsInline
      />
    </div>
  );
});
