import { useEffect, useState } from 'react';
import { fileViewUrl } from '../lib/apiClient';

export function useFileArrayBuffer(fileId: string | null) {
  const [buffer, setBuffer] = useState<ArrayBuffer | null>(null);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    if (!fileId) {
      setBuffer(null);
      setError(null);
      setLoading(false);
      return;
    }

    let cancelled = false;
    setLoading(true);
    setError(null);
    setBuffer(null);

    fetch(fileViewUrl(fileId))
      .then((res) => {
        if (!res.ok) throw new Error('파일을 불러올 수 없습니다.');
        return res.arrayBuffer();
      })
      .then((data) => {
        if (!cancelled) {
          setBuffer(data);
          setLoading(false);
        }
      })
      .catch((e) => {
        if (!cancelled) {
          setError(e instanceof Error ? e.message : '미리보기 실패');
          setLoading(false);
        }
      });

    return () => {
      cancelled = true;
    };
  }, [fileId]);

  return { buffer, loading, error };
}

export function useFileBlobUrl(fileId: string | null, mime: string) {
  const [blobUrl, setBlobUrl] = useState<string | null>(null);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    if (!fileId) {
      setBlobUrl(null);
      setError(null);
      setLoading(false);
      return;
    }

    let cancelled = false;
    let objectUrl: string | null = null;
    setLoading(true);
    setError(null);
    setBlobUrl(null);

    fetch(fileViewUrl(fileId))
      .then((res) => {
        if (!res.ok) throw new Error('파일을 불러올 수 없습니다.');
        return res.arrayBuffer();
      })
      .then((data) => {
        if (cancelled) return;
        objectUrl = URL.createObjectURL(new Blob([data], { type: mime }));
        setBlobUrl(objectUrl);
        setLoading(false);
      })
      .catch((e) => {
        if (!cancelled) {
          setError(e instanceof Error ? e.message : '미리보기 실패');
          setLoading(false);
        }
      });

    return () => {
      cancelled = true;
      if (objectUrl) URL.revokeObjectURL(objectUrl);
    };
  }, [fileId, mime]);

  return { blobUrl, loading, error };
}
