import { useState } from 'react';
import { Download, ImageOff } from 'lucide-react';
import { authFetch } from '../../lib/auth';
import { useAuthedFileUrl } from '../../lib/authedFile';

interface Props {
  src: string;
  alt?: string;
}

function getFilename(src: string): string {
  const parts = src.split('/');
  return parts[parts.length - 1] || 'bloby-image';
}

export default function BlobyImageCard({ src, alt }: Props) {
  const [failed, setFailed] = useState(false);
  // `src` may be a same-origin /api/files/* path (needs the auth token, which a native
  // <img> can't send) or an external URL — useAuthedFileUrl only fetches+authes the
  // former and passes external URLs through untouched (so the token never leaves origin).
  const { url: resolvedSrc, status } = useAuthedFileUrl(src);

  const handleDownload = async () => {
    try {
      const res = src.startsWith('/api/files/') ? await authFetch(src) : await fetch(src);
      const blob = await res.blob();
      const url = URL.createObjectURL(blob);
      const a = document.createElement('a');
      a.href = url;
      a.download = getFilename(src);
      document.body.appendChild(a);
      a.click();
      document.body.removeChild(a);
      URL.revokeObjectURL(url);
    } catch {
      window.open(src, '_blank');
    }
  };

  if (failed || status === 'error') {
    return (
      <div className="my-2 flex items-center gap-2.5 px-3.5 py-2.5 rounded-xl border border-border/30 bg-black/10 text-muted-foreground/50 text-xs">
        <ImageOff className="h-4 w-4 shrink-0" />
        <span className="truncate">{alt || 'Image not found'}</span>
      </div>
    );
  }

  return (
    <div className="relative group/img my-2 rounded-xl overflow-hidden border border-border/30 bg-black/20 w-fit max-w-full">
      {resolvedSrc ? (
        <img
          src={resolvedSrc}
          alt={alt || 'Generated image'}
          className="max-w-full max-h-80 object-contain"
          loading="lazy"
          onError={() => setFailed(true)}
        />
      ) : (
        <div className="h-40 w-40 bg-white/10 animate-pulse" />
      )}
      <div className="absolute top-2 right-2 flex gap-1.5 opacity-0 group-hover/img:opacity-100 transition-opacity">
        <button
          onClick={handleDownload}
          className="p-1.5 rounded-lg bg-black/60 hover:bg-black/80 text-white/80 hover:text-white transition-colors backdrop-blur-sm"
          title="Download original"
        >
          <Download className="h-4 w-4" />
        </button>
      </div>
      {alt && (
        <div className="px-3 py-1.5 text-xs text-muted-foreground/70 truncate">{alt}</div>
      )}
    </div>
  );
}
