import React from "react";

type FileData = {
  url: string;
  format: string; // bisa ".pdf" atau "mp4" atau "image/jpeg"
  fileName?: string;
  type?: string; // optional dari API (misal: video/mp4)
};

interface FilePreviewProps {
  file: FileData;
}

const FileTextPreview: React.FC<FilePreviewProps> = ({ file }) => {
  const format = (file.format || "").toLowerCase();
  const type = (file.type || "").toLowerCase();

  // 🖼️ Gambar
  if (
    [".jpg", ".jpeg", ".png", ".webp", ".gif"].some((ext) =>
      format.includes(ext)
    ) ||
    type.includes("image")
  ) {
    return (
      <img
        className="object-contain h-[500px] w-full rounded-md bg-black"
        src={file.url}
        alt={file.fileName || "Image File"}
      />
    );
  }

  // 🎬 Video
  if (
    ["mp4", "mov", "avi", ".mp4", ".mov", ".avi"].some((ext) =>
      format.includes(ext)
    ) ||
    type.includes("video")
  ) {
    return (
      <video
        className="object-contain h-[500px] w-full rounded-md bg-black"
        controls
      >
        <source src={file.url} type={type || "video/mp4"} />
        Browser Anda tidak mendukung video tag.
      </video>
    );
  }

  // 🎧 Audio
  if (
    ["mp3", "wav", "ogg", ".mp3", ".wav", ".ogg"].some((ext) =>
      format.includes(ext)
    ) ||
    type.includes("audio")
  ) {
    return (
      <div className="flex flex-col items-center justify-center h-[200px] bg-gray-100 rounded-md">
        <audio controls className="w-full max-w-[90%]">
          <source src={file.url} type={type || "audio/mpeg"} />
          Browser Anda tidak mendukung audio tag.
        </audio>
      </div>
    );
  }

  // 📄 PDF
  if (format.includes(".pdf") || type.includes("pdf")) {
    return (
      <iframe
        className="w-full h-[600px] rounded-md"
        src={`https://drive.google.com/viewerng/viewer?embedded=true&url=${encodeURIComponent(
          file.url
        )}`}
        title={file.fileName || "PDF File"}
      />
    );
  }

  // 🧾 Dokumen Office
  if (
    [".doc", ".docx", ".ppt", ".pptx", ".xls", ".xlsx"].some((ext) =>
      format.includes(ext)
    )
  ) {
    return (
      <iframe
        className="w-full h-[600px] rounded-md"
        src={`https://view.officeapps.live.com/op/embed.aspx?src=${encodeURIComponent(
          file.url
        )}`}
        title={file.fileName || "Office Document"}
      />
    );
  }

  // 🔗 Default fallback → link download
  return (
    <div className="text-center py-20">
      <a
        href={file.url}
        target="_blank"
        rel="noopener noreferrer"
        className="text-blue-500 underline"
      >
        Lihat {file.fileName || "File"}
      </a>
    </div>
  );
};

export default FileTextPreview;
