"use client";

import Image from "next/image";
import Link from "next/link";
import React, { useEffect, useRef, useState } from "react";
import { useTranslation } from "react-i18next";
import { SurveyType } from "@formbricks/database/prisma-browser";
import { isSafeThemeColor } from "@formbricks/types/styling-values";
import { TSurveyStyling } from "@formbricks/types/surveys/types";
import { TWorkspaceStyling } from "@formbricks/types/workspace";
import { cn } from "@/lib/cn";
import { isExternalImageSrc } from "@/lib/image-hosts";

type TBackground = (TSurveyStyling | TWorkspaceStyling)["background"];

// Unsplash credits travel in the image URL; default images have a relative URL and none.
const getUnsplashAuthor = (background: TBackground) => {
  if (background?.bgType !== "image" || !background.bg || background.bg.startsWith("/")) {
    return { authorName: "", authorURL: "" };
  }
  const params = new URL(background.bg).searchParams;
  return { authorName: params.get("authorName") || "", authorURL: params.get("authorLink") || "" };
};

/**
 * Whether the background has loaded. Media (an animation, or an image with a URL) reports it once it
 * has; colors and anything else count as loaded at once, adjusted during render.
 */
const useBackgroundLoaded = (background: TBackground) => {
  const [backgroundLoaded, setBackgroundLoaded] = useState(false);
  const isMediaBackground =
    background?.bgType === "animation" ||
    ((background?.bgType === "image" || background?.bgType === "upload") && !!background?.bg);
  if (!isMediaBackground && !backgroundLoaded) {
    setBackgroundLoaded(true);
  }
  return [backgroundLoaded, setBackgroundLoaded] as const;
};

interface MediaBackgroundProps {
  readonly children: React.ReactNode;
  readonly styling: TSurveyStyling | TWorkspaceStyling;
  readonly surveyType: SurveyType;
  readonly isEditorView?: boolean;
  readonly isMobilePreview?: boolean;
  readonly ContentRef?: React.RefObject<HTMLDivElement> | null;
  readonly onBackgroundLoaded?: (isLoaded: boolean) => void;
  readonly useNaturalHeight?: boolean;
}

export const MediaBackground: React.FC<MediaBackgroundProps> = ({
  children,
  styling,
  surveyType,
  isEditorView = false,
  isMobilePreview = false,
  ContentRef,
  onBackgroundLoaded,
  useNaturalHeight = false,
}) => {
  const { t } = useTranslation();
  const animatedBackgroundRef = useRef<HTMLVideoElement>(null);
  const background = styling.background;
  const [backgroundLoaded, setBackgroundLoaded] = useBackgroundLoaded(background);
  const authorDetailsForUnsplash = getUnsplashAuthor(background);

  useEffect(() => {
    if (background?.bgType === "animation" && animatedBackgroundRef.current) {
      const video = animatedBackgroundRef.current;
      const onCanPlayThrough = () => setBackgroundLoaded(true);
      video.addEventListener("canplaythrough", onCanPlayThrough);
      video.src = background?.bg || "";

      // Cleanup
      return () => video.removeEventListener("canplaythrough", onCanPlayThrough);
    }
  }, [background?.bg, background?.bgType, setBackgroundLoaded]);

  useEffect(() => {
    if (backgroundLoaded && onBackgroundLoaded) {
      onBackgroundLoaded(true);
    }
  }, [backgroundLoaded, onBackgroundLoaded]);

  const baseClasses = "absolute inset-0 h-full w-full transition-opacity duration-500 bg-slate-200";
  const loadedClass = backgroundLoaded ? "opacity-100" : "opacity-0";

  const getFilterStyle = () => {
    return `brightness(${background?.brightness ?? 100}%)`;
  };

  const renderBackground = () => {
    const filterStyle = getFilterStyle();

    switch (background?.bgType) {
      case "color":
        return (
          <div
            className={`${baseClasses} ${loadedClass}`}
            // A solid background lands in a server-rendered style attribute: anything that is not a
            // color (legacy rows predate the write-side check) falls back to white (ENG-2950).
            style={{
              backgroundColor: background?.bg && isSafeThemeColor(background.bg) ? background.bg : "#ffffff",
              filter: `${filterStyle}`,
            }}
          />
        );
      case "animation":
        return (
          <video
            ref={animatedBackgroundRef}
            muted
            loop
            autoPlay
            playsInline
            className={`${baseClasses} ${loadedClass} object-cover`}
            style={{ filter: `${filterStyle}` }}>
            <source src={background?.bg || ""} type="video/mp4" />
          </video>
        );
      case "image":
        if (!background?.bg) {
          return <div>{t("common.no_background_image_found")}</div>;
        }

        return (
          <>
            <div className={`${baseClasses} ${loadedClass} bg-cover bg-center`}>
              <Image
                src={background?.bg}
                alt="Background image"
                fill
                style={{ objectFit: "cover", filter: `${filterStyle}` }}
                unoptimized={isExternalImageSrc(background?.bg)}
                onLoad={() => setBackgroundLoaded(true)}
              />
              {authorDetailsForUnsplash.authorName && (
                <div className="absolute right-6 bottom-4 z-10 ml-auto hidden w-max text-xs text-slate-400 md:block">
                  <span>{t("common.photo_by")}</span>
                  <Link
                    href={authorDetailsForUnsplash.authorURL + "?utm_source=formbricks&utm_medium=referral"}
                    target="_blank"
                    className="hover:underline">
                    {authorDetailsForUnsplash.authorName}
                  </Link>
                  <span> {t("common.on")} </span>
                  <Link
                    href="https://unsplash.com/?utm_source=formbricks&utm_medium=referral"
                    target="_blank"
                    className="hover:underline">
                    Unsplash
                  </Link>
                </div>
              )}
            </div>
          </>
        );
      case "upload":
        if (!background?.bg) {
          return <div>{t("common.no_background_image_found")}</div>;
        }
        return (
          <div className={`${baseClasses} ${loadedClass} bg-cover bg-center`}>
            <Image
              src={background?.bg}
              alt="Background image"
              fill
              style={{ objectFit: "cover", filter: `${filterStyle}` }}
              unoptimized={isExternalImageSrc(background?.bg)}
              onLoad={() => setBackgroundLoaded(true)}
            />
          </div>
        );
      default:
        return <div className={`${baseClasses} ${loadedClass}`} />;
    }
  };

  const renderContent = () => (
    <div
      className={cn(
        "absolute flex h-full w-full no-scrollbar overflow-hidden",
        useNaturalHeight
          ? "flex-col items-stretch overflow-hidden"
          : "items-center justify-center overflow-hidden"
      )}>
      {children}
    </div>
  );

  if (isMobilePreview) {
    return (
      <div
        ref={ContentRef}
        data-testid="mobile-preview-container"
        className={`relative h-[90%] w-full overflow-hidden rounded-[3rem] border-[6px] border-slate-400 lg:w-[75%] ${getFilterStyle()}`}>
        {/* below element is use to create notch for the mobile device mockup   */}
        <div className="absolute top-2 right-1/2 left-1/2 z-20 h-4 w-1/3 -translate-x-1/2 transform rounded-full bg-slate-400"></div>
        {surveyType === "link" && renderBackground()}
        {renderContent()}
      </div>
    );
  } else if (isEditorView) {
    return (
      <div
        ref={ContentRef}
        className={cn("flex flex-col rounded-b-lg", useNaturalHeight ? "min-h-0 flex-1" : "grow")}>
        <div
          className={cn(
            "relative flex w-full flex-col",
            useNaturalHeight
              ? "min-h-0 flex-1 items-stretch overflow-hidden pt-0 pb-4"
              : "grow items-center justify-center p-4 py-6"
          )}>
          {renderBackground()}
          <div
            className={cn(
              "flex w-full",
              useNaturalHeight
                ? "h-full min-h-0 flex-1 flex-col items-stretch overflow-hidden"
                : "h-full items-center justify-center"
            )}>
            {children}
          </div>
        </div>
      </div>
    );
  } else {
    return (
      <div
        className={cn(
          "relative flex flex-col overflow-hidden",
          useNaturalHeight ? "h-dvh items-stretch" : "min-h-dvh items-center justify-center"
        )}>
        {renderBackground()}
        <div className={cn("relative w-full", useNaturalHeight && "flex min-h-0 flex-1 flex-col")}>
          {children}
        </div>
      </div>
    );
  }
};
