"use client";
import { useTranslations } from "next-intl";
import React from "react";

interface MediaPreviewModalProps {
  mediaUrl: string;
  mediaType: "image" | "video";
  onClose: () => void;
}

const MediaPreviewModal: React.FC<MediaPreviewModalProps> = ({
  mediaUrl,
  mediaType,
  onClose,
}) => {
  if (!mediaUrl) return null;

  const downloadFile = async (url: string) => {
    try {
      const response = await fetch(url);
      if (!response.ok) throw new Error("Media not accessible");

      const blob = await response.blob();
      const fileName = url.substring(url.lastIndexOf("/") + 1);
      const blobUrl = URL.createObjectURL(blob);

      const a = document.createElement("a");
      a.href = blobUrl;
      a.download = fileName;
      document.body.appendChild(a);
      a.click();
      document.body.removeChild(a);
      URL.revokeObjectURL(blobUrl);
    } catch (error) {
      alert("Unable to download the media. Please try again later.");
      console.error("Download error:", error);
    }
  };
  const t = useTranslations();
  return (
    <div
      className="!fixed inset-0 top-0 !m-0 bg-black/60 z-50 flex items-center justify-center p-4"
      onClick={onClose}
    >
      <div
        className="relative flex items-center justify-center w-full max-w-[800px] p-5 min-h-[300px] bg-white dark:bg-background rounded-lg overflow-hidden"
        onClick={(e) => e.stopPropagation()}
      >
        {/* Close Button */}
        <button
          onClick={onClose}
          className="absolute top-2 right-2 text-white bg-black/50 rounded-full p-1 px-2 text-sm hover:bg-black/70 transition"
        >
          ✕
        </button>

        {/* Media Preview */}
        {mediaType === "image" ? (
          <img
            src={mediaUrl}
            alt="Preview"
            className="w-auto h-auto max-h-[80vh] object-contain"
          />
        ) : (
          <video
            controls
            className="w-auto h-auto max-h-[80vh] object-contain rounded-md"
          >
            <source src={mediaUrl} type="video/mp4" />
            {t("doesnot_support_video")}
          </video>
        )}

        {/* Download Button */}
        <button
          onClick={() => downloadFile(mediaUrl)}
          className="absolute bottom-4 right-4 bg-primary500 text-white rounded-md px-3 py-1.5 text-sm hover:bg-primary600 transition"
        >
          {t("download")}
        </button>
      </div>
    </div>
  );
};

export default MediaPreviewModal;
