import React, { useEffect, useState } from "react";

type PreviewImageProps = {
  file: File | null;
  lang?: string;
};

const PreviewImage = ({ file, lang = "ar" }: PreviewImageProps) => {
  const [previewUrl, setPreviewUrl] = useState("");
  const safeLang = typeof lang === "string" ? lang : "ar";
  const isImage = Boolean(file?.type?.startsWith("image/"));
  const isPdf = file?.type === "application/pdf";

  useEffect(() => {
    if (!file || (!isImage && !isPdf)) {
      setPreviewUrl("");
      return undefined;
    }

    const objectUrl = URL.createObjectURL(file);
    setPreviewUrl(objectUrl);
    return () => URL.revokeObjectURL(objectUrl);
  }, [file, isImage, isPdf]);

  if (!file) return null;

  const headerText =
    safeLang === "ar" ? "معاينة الملف المرفوع" : "Uploaded file preview";
  const imageAlt = safeLang === "ar" ? "معاينة الإيصال" : "Receipt preview";
  const pdfTitle = safeLang === "ar" ? "معاينة ملف PDF" : "PDF preview";
  const fallbackText =
    safeLang === "ar"
      ? "تم إرفاق الملف. لا تتوفر معاينة مباشرة لهذا النوع."
      : "File attached. Preview is not available for this file type.";

  return React.createElement(
    "div",
    {
      style: {
        marginTop: "10px",
        borderRadius: "12px",
        border: "1px solid #dbeafe",
        background: "#f8fbff",
        padding: "12px",
      },
    },
    React.createElement(
      "p",
      {
        style: {
          margin: 0,
          marginBottom: "8px",
          fontSize: "0.9rem",
          color: "#1e293b",
          fontWeight: 600,
        },
      },
      headerText,
    ),
    previewUrl && isImage
      ? React.createElement("img", {
          src: previewUrl,
          alt: imageAlt,
          style: {
            width: "100%",
            maxHeight: "220px",
            objectFit: "contain",
            borderRadius: "10px",
            border: "1px solid #e2e8f0",
            background: "#fff",
          },
        })
      : previewUrl && isPdf
        ? React.createElement("iframe", {
            src: previewUrl,
            title: pdfTitle,
            style: {
              width: "100%",
              height: "320px",
              borderRadius: "10px",
              border: "1px solid #e2e8f0",
              background: "#fff",
            },
          })
      : React.createElement(
          "div",
          {
            style: {
              display: "flex",
              alignItems: "center",
              justifyContent: "center",
              minHeight: "90px",
              borderRadius: "10px",
              border: "1px dashed #cbd5e1",
              background: "#fff",
              color: "#475569",
              fontSize: "0.9rem",
              padding: "10px",
              textAlign: "center",
            },
          },
          fallbackText,
        ),
  );
};

export default PreviewImage;