"use client";
import React, { useEffect, useState } from "react";
import Image, { ImageProps } from "next/image";
import fallbackSrc from "@/public/logo.png";
import { StaticImageData } from "next/image";

interface MediaWithFallbackProps extends Omit<ImageProps, "src" | "onError"> {
  src: string | StaticImageData;
  fallbackSrc?: string | StaticImageData;
  isVideo?: boolean;
  isIframe?: boolean;
  isEmbed?: boolean;
  className?: string;
  videoProps?: React.VideoHTMLAttributes<HTMLVideoElement>;
  iframeProps?: React.IframeHTMLAttributes<HTMLIFrameElement>;
  embedProps?: React.EmbedHTMLAttributes<HTMLEmbedElement>;
}

const MediaWithFallback: React.FC<MediaWithFallbackProps> = ({
  src,
  fallbackSrc: customFallback,
  isVideo = false,
  isIframe = false,
  isEmbed = false,
  className = "",
  videoProps,
  iframeProps,
  embedProps,
  ...imageProps
}) => {
  const [mediaSrc, setMediaSrc] = useState<string | StaticImageData>(src);
  const [hasError, setHasError] = useState(false);
  const fallback = customFallback || fallbackSrc;

  useEffect(() => {
    setMediaSrc(src);
    setHasError(false);
  }, [src]);

  const handleError = () => {
    if (!hasError) {
      setMediaSrc(fallback);
      setHasError(true);
    }
  };

  if (hasError || !mediaSrc) {
    return (
      <Image
        {...imageProps}
        src={fallback}
        alt="Fallback content"
        className={`${className || ""} !object-contain`}
        unoptimized={!!customFallback}
        loading="lazy"
        width={imageProps.width || 800}
        height={imageProps.height || 800}
      />
    );
  }
  if (isVideo) {
    return (
      <video
        src={typeof mediaSrc === "string" ? mediaSrc : ""}
        className={`${className} w-full h-full`}
        onError={handleError}
        {...videoProps}
      />
    );
  }
  if (isIframe) {
    return (
      <iframe
        src={typeof mediaSrc === "string" ? mediaSrc : ""}
        className={`${className} w-full h-full`}
        onError={handleError}
        {...iframeProps}
      />
    );
  }
  if (isEmbed) {
    return (
      <embed
        type="application/pdf"
        src={typeof mediaSrc === "string" ? mediaSrc : ""}
        className={`${className}`}
        onError={handleError}
        {...embedProps}
      />
    );
  }
  return (
    <Image
      {...imageProps}
      src={hasError ? fallback : mediaSrc}
      className={`${className} ${hasError ? "!object-contain" : ""}`}
      onError={handleError}
      alt="Fallback content"
      unoptimized={!!customFallback}
      loading="lazy"
      width={imageProps.width || 800}
      height={imageProps.height || 800}
    />
  );
};

export default MediaWithFallback;
