import { useState, useCallback } from 'react';
import { useTranslation } from 'react-i18next';
import {
  fetchLocalFileContent,
  fetchSubtaskFileContent,
  getLocalFileRawUrl,
  getTrustedLocalHtmlUrl,
  subtaskFileRawUrl,
} from '../api';
import { isImagePreviewable, isPdfPreviewable, isTextPreviewable, isHtmlPreviewable } from '../lib/utils';

export interface PreviewState {
  name: string;
  content: string;
  imageSrc: string;
  markdownImageBaseUrl?: string;
  taskId?: number;
  section?: string;
  filePath?: string;
  editable?: boolean;
  trustedHtmlUrl?: string;
}

export function useFilePreview(onError: (msg: string) => void) {
  const { t } = useTranslation('files');
  const [previewState, setPreviewState] = useState<PreviewState | null>(null);

  const previewLocalFile = useCallback(async (
    taskId: number,
    section: 'workspace' | 'input' | 'output' | 'logs',
    filePath: string,
    name: string,
  ) => {
    try {
      const canEdit = section === 'output' && isTextPreviewable(name);
      if (isImagePreviewable(name) || isPdfPreviewable(name) || isHtmlPreviewable(name)) {
        const imageSrc = getLocalFileRawUrl(taskId, section, filePath);
        const trustedHtmlUrl = isHtmlPreviewable(name)
          ? getTrustedLocalHtmlUrl(taskId, section, filePath)
          : undefined;
        setPreviewState({ name, content: '', imageSrc, trustedHtmlUrl, taskId, section, filePath, editable: false });
        return;
      }
      const content = await fetchLocalFileContent(taskId, section, filePath);
      let markdownImageBaseUrl: string | undefined;
      if (/\.(md|markdown)$/i.test(name)) {
        const dir = filePath.includes('/') ? filePath.substring(0, filePath.lastIndexOf('/') + 1) : '';
        markdownImageBaseUrl = `/api/local/tasks/${taskId}/files/raw?section=${section}&path=${dir}`;
      }
      setPreviewState({ name, content, imageSrc: '', markdownImageBaseUrl, taskId, section, filePath, editable: canEdit });
    } catch {
      onError(t('loadError'));
    }
  }, [onError, t]);

  const previewSubtaskFile = useCallback(async (
    taskId: number,
    jobId: string,
    category: string,
    filePath: string,
  ) => {
    try {
      const fullPath = `${category}/${filePath}`;
      const name = filePath.split('/').pop() ?? filePath;
      const rawUrl = subtaskFileRawUrl(taskId, jobId, fullPath);
      if (isImagePreviewable(name) || isPdfPreviewable(name)) {
        setPreviewState({ name, content: '', imageSrc: rawUrl, editable: false });
        return;
      }
      const content = await fetchSubtaskFileContent(taskId, jobId, fullPath);
      let markdownImageBaseUrl: string | undefined;
      if (/\.(md|markdown)$/i.test(name)) {
        const dir = fullPath.includes('/') ? fullPath.substring(0, fullPath.lastIndexOf('/') + 1) : '';
        markdownImageBaseUrl = subtaskFileRawUrl(taskId, jobId, dir);
      }
      setPreviewState({ name, content, imageSrc: '', markdownImageBaseUrl, editable: false });
    } catch {
      onError(t('subtaskLoadError'));
    }
  }, [onError, t]);

  const closePreview = useCallback(() => setPreviewState(null), []);

  return { previewState, previewLocalFile, previewSubtaskFile, closePreview };
}
