"use client";

import type { ExternalEmbed } from "@/data/queries";
import { parseEmbedPlayerFromUrl, getPlayerAspect } from "./utils/embed-player";
import "./LinkPreview.css";

// BlobRef type for ATProto blob references
type BlobRef = {
  $type: "blob";
  ref: { $link: string };
  mimeType: string;
};

// External embed can have thumb as either string (draft) or BlobRef (published)
type ExternalEmbedWithThumb = Omit<ExternalEmbed, "thumb"> & {
  thumb?: string | BlobRef;
};

interface LinkPreviewProps {
  external: ExternalEmbedWithThumb;
  fallbackToUrl?: boolean; // if true, show URL as title/desc when they're missing
  onDelete?: () => void; // if provided, shows delete button (edit mode only)
}

export function LinkPreview({ external, fallbackToUrl = true, onDelete }: LinkPreviewProps) {
  // Check if this is a special embed (YouTube, Spotify, GIF, etc.)
  const embedParams = parseEmbedPlayerFromUrl(external.uri);

  const thumbUrl = external.thumb
    ? typeof external.thumb === "string"
      ? external.thumb
      : `https://cdn.bsky.app/img/feed_thumbnail/plain/${external.thumb.ref.$link}`
    : undefined;

  // Handle GIF embeds
  if (embedParams?.isGif) {
    const aspectRatio = embedParams.dimensions
      ? embedParams.dimensions.width / embedParams.dimensions.height
      : 16 / 9;

    const gifContent = (
      <div className="LinkPreview-gif" style={{ aspectRatio }}>
        <img
          src={embedParams.playerUri}
          alt={external.title || "GIF"}
          className="LinkPreview-gif-image"
        />
        <div className="LinkPreview-gif-label">GIF</div>
      </div>
    );

    if (onDelete) {
      return (
        <div className="LinkPreview-container">
          {gifContent}
          <button
            onClick={(e) => {
              e.preventDefault();
              e.stopPropagation();
              onDelete();
            }}
            className="LinkPreview-deleteButton"
            title="remove link"
          >
            ×
          </button>
        </div>
      );
    }

    return gifContent;
  }

  // Handle video/audio player embeds (YouTube, Spotify, etc.)
  if (embedParams && !embedParams.isGif) {
    const aspect = getPlayerAspect({
      type: embedParams.type,
      width: 600, // Default width for web
      hasThumb: !!thumbUrl,
    });
    const isAppleMusic = embedParams.source === "appleMusic";

    const playerContent = (
      <div
        className="LinkPreview-player"
        style={aspect.aspectRatio ? { aspectRatio: aspect.aspectRatio } : { height: aspect.height }}
      >
        <iframe
          src={embedParams.playerUri}
          className="LinkPreview-player-iframe"
          allow={
            isAppleMusic
              ? "autoplay *; encrypted-media *; fullscreen *; clipboard-write"
              : "accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"
          }
          sandbox={
            isAppleMusic
              ? "allow-forms allow-popups allow-same-origin allow-scripts allow-storage-access-by-user-activation allow-top-navigation-by-user-activation"
              : undefined
          }
          allowFullScreen
          title={external.title || "Embedded player"}
        />
      </div>
    );

    if (onDelete) {
      return (
        <div className="LinkPreview-container">
          {playerContent}
          <button
            onClick={(e) => {
              e.preventDefault();
              e.stopPropagation();
              onDelete();
            }}
            onTouchEnd={(e) => {
              e.preventDefault();
              e.stopPropagation();
              onDelete();
            }}
            className="LinkPreview-deleteButton"
            title="remove link"
          >
            ×
          </button>
        </div>
      );
    }

    return playerContent;
  }

  // Regular link preview
  const toNiceDomain = (url: string) => {
    try {
      const urlObj = new URL(url);
      return urlObj.host;
    } catch {
      return url;
    }
  };

  // Use URL as fallback if title/description are missing
  const title = external.title || (fallbackToUrl ? external.uri : "");
  const description = external.description || (fallbackToUrl ? "" : "");
  const showAsSimple = !external.thumb && !external.description && fallbackToUrl;

  const linkContent = (
    <a
      href={external.uri}
      target="_blank"
      rel="noopener noreferrer"
      className={`LinkPreview ${showAsSimple ? "LinkPreview--simple" : ""}`}
    >
      {thumbUrl && <img src={thumbUrl} alt={title} className="LinkPreview-thumb" />}
      <div className="LinkPreview-info">
        {!showAsSimple && <div className="LinkPreview-domain">{toNiceDomain(external.uri)}</div>}
        <div className="LinkPreview-title">{title}</div>
        {description && <div className="LinkPreview-desc">{description}</div>}
      </div>
    </a>
  );

  if (onDelete) {
    return (
      <div className="LinkPreview-container">
        {linkContent}
        <button
          onClick={(e) => {
            e.preventDefault();
            e.stopPropagation();
            onDelete();
          }}
          className="LinkPreview-deleteButton"
          title="remove link"
        >
          ×
        </button>
      </div>
    );
  }

  return linkContent;
}
