import { useEffect, useState } from "react";
import { useAuth } from "@/store/auth";

interface Props {
  /** Path relative to /api/v1/mechanic, e.g. "photos/123/thumb". */
  src: string;
  alt?: string;
  className?: string;
  /** Optional placeholder while loading. */
  fallback?: React.ReactNode;
}

/**
 * <img> wrapper that fetches the resource with the current Bearer token,
 * turns it into a blob: URL, and renders an <img> pointing at the blob.
 *
 * Necessary because the mechanic photo endpoints are auth-guarded — plain
 * <img src="/api/v1/mechanic/photos/123"> doesn't send the Authorization header.
 *
 * Cleans up the blob URL on unmount or when src changes.
 */
export function AuthImg({ src, alt = "", className, fallback }: Props) {
  const token = useAuth((s) => s.token);
  const [blobUrl, setBlobUrl] = useState<string | null>(null);
  const [error, setError] = useState<boolean>(false);

  useEffect(() => {
    let cancelled = false;
    let createdUrl: string | null = null;
    setError(false);
    setBlobUrl(null);

    async function load() {
      if (!token) {
        setError(true);
        return;
      }
      try {
        const fullUrl = `/api/v1/mechanic/${src}`;
        const res = await fetch(fullUrl, {
          headers: { Authorization: `Bearer ${token}` },
          redirect: "follow",
        });
        if (!res.ok) throw new Error(`${res.status}`);
        const blob = await res.blob();
        createdUrl = URL.createObjectURL(blob);
        if (!cancelled) setBlobUrl(createdUrl);
      } catch {
        if (!cancelled) setError(true);
      }
    }

    load();
    return () => {
      cancelled = true;
      if (createdUrl) URL.revokeObjectURL(createdUrl);
    };
  }, [src, token]);

  if (error) {
    return (
      <div className={className}>
        {fallback ?? (
          <span className="text-xs text-muted-foreground">нет фото</span>
        )}
      </div>
    );
  }
  if (!blobUrl) {
    return (
      <div className={className}>
        {fallback ?? (
          <div className="bg-muted animate-pulse h-full w-full" />
        )}
      </div>
    );
  }
  return <img src={blobUrl} alt={alt} className={className} />;
}
