"use client";

import { useState } from "react";
import { FileText } from "lucide-react";
import { cn } from "@/lib/utils";
import { getFileKind, isPreviewableFile } from "@/lib/file-utils";

interface FileThumbnailProps {
  fileName: string;
  publicUrl: string;
  mimeType: string | null;
  className?: string;
}

export function FileThumbnail({
  fileName,
  publicUrl,
  mimeType,
  className,
}: FileThumbnailProps) {
  const [failed, setFailed] = useState(false);
  const fileKind = getFileKind(mimeType, fileName);
  const previewable = isPreviewableFile(mimeType, fileName) && !failed;

  return (
    <div
      className={cn(
        "relative overflow-hidden rounded-xl border border-border bg-muted/20",
        className
      )}
    >
      {previewable ? (
        fileKind === "image" ? (
          <>
            {/* eslint-disable-next-line @next/next/no-img-element */}
            <img
              src={publicUrl}
              alt={fileName}
              loading="lazy"
              onError={() => setFailed(true)}
              className="h-full w-full object-cover"
            />
            <div className="pointer-events-none absolute inset-x-0 bottom-0 bg-gradient-to-t from-black/55 to-transparent px-2 py-1 text-[10px] font-medium uppercase tracking-[0.12em] text-white/90">
              Image
            </div>
          </>
        ) : (
          <>
            <iframe
              src={`${publicUrl}#toolbar=0&navpanes=0&scrollbar=0`}
              title={fileName}
              className="pointer-events-none h-full w-full bg-white"
              onError={() => setFailed(true)}
            />
            <div className="pointer-events-none absolute left-2 top-2 rounded-full bg-background/90 px-2 py-0.5 text-[10px] font-medium uppercase tracking-[0.12em] text-foreground shadow-sm">
              PDF
            </div>
          </>
        )
      ) : (
        <div className="flex h-full w-full flex-col items-center justify-center gap-2 bg-muted/10 p-4 text-center">
          <div className="flex h-10 w-10 items-center justify-center rounded-full bg-background">
            <FileText className="h-4 w-4 text-muted-foreground" />
          </div>
          <span className="text-[10px] font-medium uppercase tracking-[0.12em] text-muted-foreground">
            {fileKind}
          </span>
        </div>
      )}
    </div>
  );
}
