import { useCallback, useEffect, useRef, useState } from 'react';
import type {
  Dispatch,
  MutableRefObject,
  SetStateAction,
} from 'react';
import { fetchDocument } from '../lib/apiClient';
import type { DocumentId } from '../types/identifiers';

type FolderId = DocumentId | 'root';

import type { Document } from '../types/documents';

type DocumentLink = {
  url?: string;
  mimeType?: string | null;
  filename?: string | null;
  expiresAt?: number;
};

type NavigateHandler = (path: string, options?: { replace?: boolean }) => void;

interface UseDocumentPreviewArgs {
  routeDocumentId?: DocumentId | null;
  documentsManager: {
    getById: (id: DocumentId) => Document | null;
    ensure: (id: DocumentId) => Promise<Document | null>;
    getMany: (ids: DocumentId[]) => Document[];
    subscribe: (listener: () => void) => () => void;
    ingest: (docs: unknown[]) => { canonical: Document[]; changed: boolean };
  };
  selectedFolder?: FolderId | null;
  notifyApiError: (error: unknown, message: string) => void;
  navigate: NavigateHandler;
  locationPathname: string;
  locationSearch: string;
  detailPanelControlRef: MutableRefObject<{
    open?: (args?: { documentIds?: DocumentId[] }) => void;
    close?: () => void;
  } | null>;
  setActivePreviewId: Dispatch<SetStateAction<DocumentId | null>>;
}

interface UseDocumentPreviewResult {
  documentLinks: Map<DocumentId, DocumentLink>;
  ensureDownloadUrl: (documentId: DocumentId, options?: { force?: boolean }) => Promise<DocumentLink | null>;
  ensurePreviewData: (documentId: DocumentId) => Promise<Document | null>;
  openDocumentPreview: (documentId: DocumentId, options?: { replace?: boolean }) => void;
  closeDocumentPreview: (folderId?: FolderId) => void;
  resetPreviewState: () => void;
  removeDocumentLinks: (ids: DocumentId[]) => void;
}

const useDocumentPreview = ({
  routeDocumentId,
  documentsManager,
  selectedFolder,
  notifyApiError,
  navigate,
  locationPathname,
  locationSearch,
  detailPanelControlRef,
  setActivePreviewId,
}: UseDocumentPreviewArgs): UseDocumentPreviewResult => {
  const [documentLinks, setDocumentLinks] = useState<Map<DocumentId, DocumentLink>>(() => new Map());
  const previewInflightRef = useRef<Map<DocumentId, Promise<DocumentLink | null>>>(new Map());
  const previewReturnPathRef = useRef<string | null>(null);

  const resetPreviewState = useCallback(() => {
    setDocumentLinks(() => new Map());
    previewInflightRef.current = new Map();
    previewReturnPathRef.current = null;
  }, []);

  const removeDocumentLinks = useCallback((ids: DocumentId[]) => {
    if (!Array.isArray(ids) || ids.length === 0) {
      return;
    }
    setDocumentLinks((prev) => {
      if (!prev.size) {
        return prev;
      }
      let changed = false;
      const next = new Map(prev);
      ids.forEach((id) => {
        if (next.delete(id)) {
          changed = true;
        }
        previewInflightRef.current.delete(id);
      });
      return changed ? next : prev;
    });
  }, []);

  const ensureDownloadUrl = useCallback(
    async (documentId: DocumentId, { force = false }: { force?: boolean } = {}): Promise<DocumentLink | null> => {
      if (!documentId) return null;

      const existing = documentLinks.get(documentId);
      const now = Date.now();
      const expiresAt = existing?.expiresAt ?? null;
      if (!force && existing && (!expiresAt || expiresAt > now)) {
        return existing;
      }

      if (!force && previewInflightRef.current.has(documentId)) {
        return previewInflightRef.current.get(documentId) || null;
      }

      const request: Promise<DocumentLink | null> = (async () => {
        try {
          const docResponse = await fetchDocument(documentId);
          const download = docResponse?.current_version?.download || null;
          const downloadUrl = download?.url;
          if (!downloadUrl) {
            throw new Error('Document missing download url');
          }

          const entry: DocumentLink = {
            url: downloadUrl,
            mimeType: docResponse?.mime_type || null,
            filename: docResponse?.filename,
            expiresAt: download?.expires_at,
          };
          setDocumentLinks((prev) => {
            const next = new Map(prev);
            next.set(documentId, entry);
            return next;
          });
          return entry;
        } catch (error) {
          notifyApiError(error, 'Unable to fetch document preview.');
          throw error;
        } finally {
          previewInflightRef.current.delete(documentId);
        }
      })();

      previewInflightRef.current.set(documentId, request);
      return request;
    },
    [documentLinks, notifyApiError],
  );

  const ensurePreviewData = useCallback(
    async (documentId: DocumentId): Promise<Document | null> => {
      if (!documentId) return null;

      const findInCache = () => documentsManager.getById(documentId);

      let doc = findInCache();

      if (!doc) {
        doc = await documentsManager.ensure(documentId);
      }

      if (!doc) {
        const fetched = await fetchDocument(documentId);
        const { canonical } = documentsManager.ingest([fetched as unknown]);
        doc = (canonical[0] as Document | undefined) || null;
        if (!doc) {
          throw new Error('Document metadata unavailable.');
        }
      }

      if (!previewReturnPathRef.current) {
        const fallbackFolderId = doc?.folder_id || 'root';
        previewReturnPathRef.current =
          fallbackFolderId === 'root' ? '/documents' : `/documents/folder/${fallbackFolderId}`;
      }

      await ensureDownloadUrl(documentId, { force: false });
      setActivePreviewId(documentId);
      return doc;
    },
    [
      documentsManager,
      ensureDownloadUrl,
      setActivePreviewId,
    ],
  );

  const openDocumentPreview = useCallback(
    (documentId: DocumentId, { replace = false }: { replace?: boolean } = {}) => {
      if (!documentId) return;
      detailPanelControlRef.current?.close?.();
      previewReturnPathRef.current = `${locationPathname}${locationSearch}`;
      navigate(`/documents/${documentId}`, { replace });
    },
    [navigate, locationPathname, locationSearch, detailPanelControlRef],
  );

  const closeDocumentPreview = useCallback(
    (folderId?: FolderId) => {
      const fallbackPath = previewReturnPathRef.current;
      previewReturnPathRef.current = null;

      if (fallbackPath) {
        navigate(fallbackPath, { replace: false });
        return;
      }

      const targetId = folderId || selectedFolder || 'root';
      const path = targetId === 'root' ? '/documents' : `/documents/folder/${targetId}`;
      navigate(path, { replace: false });
    },
    [navigate, selectedFolder],
  );

  useEffect(() => {
    if (!routeDocumentId) {
      return undefined;
    }

    let cancelled = false;

    ensurePreviewData(routeDocumentId).catch((error) => {
      if (cancelled) {
        return;
      }
      notifyApiError(error, 'Failed to open document preview.');
      closeDocumentPreview();
    });

    return () => {
      cancelled = true;
    };
  }, [routeDocumentId, ensurePreviewData, notifyApiError, closeDocumentPreview]);

  return {
    documentLinks,
    ensureDownloadUrl,
    ensurePreviewData,
    openDocumentPreview,
    closeDocumentPreview,
    resetPreviewState,
    removeDocumentLinks,
  };
};

export default useDocumentPreview;
