import { useCallback, useEffect, useRef, useState } from 'react';
import type {
  Dispatch,
  MutableRefObject,
  SetStateAction,
} from 'react';

type DocumentId = string | number;
type FolderId = DocumentId | 'root';

type DocumentLike = {
  id?: DocumentId;
  folder_id?: FolderId | null;
  filename?: string | null;
  current_version?: Record<string, unknown>;
  [key: string]: unknown;
};

type PreviewEntry = {
  url?: string;
  contentType?: string | null;
  filename?: string | null;
  expiresAt?: number;
  canGoPrev?: boolean;
  canGoNext?: boolean;
  goPrev?: () => void;
  goNext?: () => void;
} | null;

interface AssetManagerLike {
  hydrateDetail: (payload: unknown) => { document?: DocumentLike } | null | undefined;
  hydrateDocument: (payload: unknown) => DocumentLike | null | undefined;
}

interface ApiClient {
  get: <T = unknown>(path: string) => Promise<{ data: T }>;
}

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

interface UseDocumentPreviewArgs {
  routeDocumentId?: DocumentId | null;
  documents: DocumentLike[];
  searchResults: DocumentLike[] | null;
  selectedFolder?: FolderId | null;
  assetManager: AssetManagerLike;
  api: ApiClient;
  resolveApiPath?: (path: string) => string;
  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 {
  previewEntries: Map<DocumentId, PreviewEntry>;
  previewDocuments: Map<DocumentId, DocumentLike>;
  ensurePreviewUrl: (documentId: DocumentId | null, options?: { force?: boolean }) => Promise<PreviewEntry | null>;
  ensurePreviewData: (documentId: DocumentId | null) => Promise<DocumentLike | null>;
  openDocumentPreview: (documentId: DocumentId | null, options?: { replace?: boolean }) => void;
  closeDocumentPreview: (folderId?: FolderId | null) => void;
  resetPreviewState: () => void;
  removePreviewEntries: (ids: DocumentId[]) => void;
}

const useDocumentPreview = ({
  routeDocumentId,
  documents,
  searchResults,
  selectedFolder,
  assetManager,
  api,
  resolveApiPath,
  notifyApiError,
  navigate,
  locationPathname,
  locationSearch,
  detailPanelControlRef,
  setActivePreviewId,
}: UseDocumentPreviewArgs): UseDocumentPreviewResult => {
  const [previewEntries, setPreviewEntries] = useState<Map<DocumentId, PreviewEntry>>(() => new Map());
  const [previewDocuments, setPreviewDocuments] = useState<Map<DocumentId, DocumentLike>>(() => new Map());
  const previewInflightRef = useRef<Map<DocumentId, Promise<PreviewEntry | null>>>(new Map());
  const previewReturnPathRef = useRef<string | null>(null);

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

  const removePreviewEntries = useCallback((ids: DocumentId[]) => {
    if (!Array.isArray(ids) || ids.length === 0) {
      return;
    }
    setPreviewEntries((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 cachePreviewDocument = useCallback((doc: DocumentLike | null | undefined) => {
    if (!doc?.id) {
      return;
    }
    setPreviewDocuments((prev) => {
      const existing = prev.get(doc.id);
      if (existing === doc) {
        return prev;
      }
      const next = new Map(prev);
      next.set(doc.id, doc);
      return next;
    });
  }, []);

  const removeCachedPreviewDocument = useCallback((documentId?: DocumentId | null) => {
    if (!documentId) {
      return;
    }
    setPreviewDocuments((prev) => {
      if (!prev.has(documentId)) {
        return prev;
      }
      const next = new Map(prev);
      next.delete(documentId);
      return next;
    });
  }, []);

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

      const existing = previewEntries.get(documentId) || null;
      const now = Date.now();
      const expiresAt = typeof existing?.expiresAt === 'number' ? 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<PreviewEntry | null> = (async () => {
        try {
          const docResponse = await api.get<{ document?: Record<string, any> }>(`/documents/${documentId}`);
          const downloadPath = docResponse.data?.document?.current_version?.download_path;
          if (!downloadPath || !resolveApiPath) {
            throw new Error('Document missing download path');
          }

          const href = resolveApiPath(downloadPath);
          const entry: PreviewEntry = {
            url: href,
            contentType: docResponse.data?.document?.current_version?.version?.content_type || null,
            filename: docResponse.data?.document?.filename,
            expiresAt: Date.now() + 5 * 60 * 1000,
          };
          setPreviewEntries((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;
    },
    [previewEntries, api, resolveApiPath, notifyApiError],
  );

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

      const findInCache = () => {
        const pool = searchResults ?? documents;
        return pool.find((item) => item.id === documentId) || null;
      };

      let doc = findInCache();

      if (!doc) {
        const { data } = await api.get(`/documents/${documentId}`);
        const hydratedDetail = assetManager.hydrateDetail(data);
        const fetched = hydratedDetail?.document || (data as { document?: DocumentLike })?.document || data;
        doc = fetched ? assetManager.hydrateDocument(fetched) || null : null;
        if (!doc) {
          throw new Error('Document metadata unavailable.');
        }

        const existsInDocuments = documents.some((item) => item.id === doc?.id);
        const existsInSearch = Array.isArray(searchResults)
          ? searchResults.some((item) => item.id === doc?.id)
          : false;

        if (doc?.id && (existsInDocuments || existsInSearch)) {
          removeCachedPreviewDocument(doc.id);
        } else {
          cachePreviewDocument(doc);
        }
      }

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

      await ensurePreviewUrl(documentId, { force: false });
      setActivePreviewId(documentId);
      return doc;
    },
    [
      searchResults,
      documents,
      assetManager,
      ensurePreviewUrl,
      setActivePreviewId,
      api,
      cachePreviewDocument,
      removeCachedPreviewDocument,
    ],
  );

  const openDocumentPreview = useCallback(
    (documentId: DocumentId | null, { 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 | null = null) => {
      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;
    }

    const handleKeyDown = (event: KeyboardEvent) => {
      if (event.key === 'Escape') {
        closeDocumentPreview();
      }
    };

    window.addEventListener('keydown', handleKeyDown);
    return () => window.removeEventListener('keydown', handleKeyDown);
  }, [routeDocumentId, closeDocumentPreview]);

  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]);

  useEffect(() => {
    setPreviewDocuments((prev) => {
      if (!prev.size) {
        return prev;
      }
      const next = new Map(prev);
      let changed = false;
      const prune = (list?: DocumentLike[] | null) => {
        if (!Array.isArray(list)) {
          return;
        }
        list.forEach((doc) => {
          if (doc?.id && next.has(doc.id)) {
            next.delete(doc.id);
            changed = true;
          }
        });
      };
      prune(documents);
      prune(searchResults);
      return changed ? next : prev;
    });
  }, [documents, searchResults]);

  return {
    previewEntries,
    previewDocuments,
    ensurePreviewUrl,
    ensurePreviewData,
    openDocumentPreview,
    closeDocumentPreview,
    resetPreviewState,
    removePreviewEntries,
  };
};

export default useDocumentPreview;
