import React, { useEffect, useRef, useState } from "react";
import api from "../../services/api.js";
import { sniffBlobMediaKind } from "../../utils/mediaKindHelpers.js";

function resolveRequestPath(url, answersId, occurrence) {
  if (answersId != null && occurrence != null) {
    return `/ptw_answers_media/${answersId}/${occurrence}/file`;
  }
  if (url != null && String(url).trim() !== "") {
    const raw = String(url).trim();
    const base = (import.meta.env.VITE_API_BASE_URL || "/api/ptw").replace(/\/$/, "");
    if (raw.startsWith(base)) {
      return raw.slice(base.length) || "/";
    }
    if (raw.startsWith("/api/ptw/")) {
      return raw.slice("/api/ptw".length);
    }
    return raw.startsWith("/") ? raw : `/${raw}`;
  }
  return "";
}

function normalizeVideoMimeType(contentType = "") {
  const type = String(contentType || "").split(";")[0].trim().toLowerCase();
  if (type.startsWith("video/")) return type;
  return "video/mp4";
}

function toPlayableBlob(blob, { kind, contentType }) {
  if (!(blob instanceof Blob)) return blob;
  const targetType =
    kind === "video" ? normalizeVideoMimeType(contentType) : String(contentType || blob.type || "");
  if (!targetType || blob.type === targetType) return blob;
  return new Blob([blob], { type: targetType });
}

async function isErrorPayload(blob) {
  if (!(blob instanceof Blob) || blob.size <= 0) return true;
  const type = String(blob.type || "").toLowerCase();
  if (type.includes("json") || type.includes("text/html")) {
    return true;
  }
  if (blob.size < 48) {
    try {
      const text = await blob.slice(0, 200).text();
      const trimmed = text.trim();
      if (trimmed.startsWith("{") || trimmed.startsWith("<!DOCTYPE") || trimmed.startsWith("<html")) {
        return true;
      }
    } catch {
      return false;
    }
  }
  return false;
}

export default function AuthenticatedMedia({
  url,
  answersId,
  occurrence,
  alt = "",
  className = "",
  videoClassName = "",
  preferredKind = ""
}) {
  const [objectUrl, setObjectUrl] = useState("");
  const [mediaKind, setMediaKind] = useState(preferredKind || "image");
  const [failed, setFailed] = useState(false);
  const blobUrlRef = useRef("");

  useEffect(() => {
    let active = true;
    const path = resolveRequestPath(url, answersId, occurrence);

    async function load() {
      setFailed(false);
      setObjectUrl("");

      if (!path) {
        setFailed(true);
        return;
      }

      try {
        const res = await api.get(path, { responseType: "blob" });
        if (!active) return;

        const blob = res.data;
        const contentType = res.headers?.["content-type"] || blob?.type || "";

        if (await isErrorPayload(blob)) {
          setFailed(true);
          return;
        }

        const kind =
          preferredKind || (await sniffBlobMediaKind(blob, { path, contentType }));
        const playableBlob = toPlayableBlob(blob, { kind, contentType });

        if (blobUrlRef.current) {
          URL.revokeObjectURL(blobUrlRef.current);
          blobUrlRef.current = "";
        }

        const nextUrl = URL.createObjectURL(playableBlob);
        blobUrlRef.current = nextUrl;
        setMediaKind(kind);
        setObjectUrl(nextUrl);
      } catch {
        if (active) setFailed(true);
      }
    }

    load();

    return () => {
      active = false;
      if (blobUrlRef.current) {
        URL.revokeObjectURL(blobUrlRef.current);
        blobUrlRef.current = "";
      }
    };
  }, [url, answersId, occurrence, preferredKind]);

  if (failed) {
    return <span className="ptw-preview-media__missing">Media unavailable</span>;
  }

  if (!objectUrl) {
    return <span className="ptw-preview-media__loading">Loading…</span>;
  }

  if (mediaKind === "video") {
    return (
      <video
        className={`ptw-preview-media-interactive ptw-print-exclude ${videoClassName || className || "ptw-preview-media"}`}
        src={objectUrl}
        controls
        playsInline
        preload="metadata"
        onError={() => setFailed(true)}
      />
    );
  }

  return (
    <img
      className={`${className || "ptw-preview-media"} ptw-print-media`}
      src={objectUrl}
      alt={alt}
      onError={() => setFailed(true)}
    />
  );
}
