'use client';

import { DiffModeEnum, DiffView } from '@git-diff-view/react';
import { useTheme } from 'next-themes';

import '@git-diff-view/react/styles/diff-view.css';

import type { ParsedDiffFile } from './diff-utils';

export type DiffMode = 'unified' | 'split';

/** Resolves the git-diff-view theme from next-themes, defaulting to dark. */
export const useDiffTheme = (): 'light' | 'dark' => {
  const { resolvedTheme } = useTheme();
  return resolvedTheme === 'light' ? 'light' : 'dark';
};

/**
 * Renders one file's diff with syntax highlighting. Falls back to a short note
 * for binary files and metadata-only changes (pure renames / mode changes) that
 * have no hunks to display.
 */
export const DiffFileView = ({
  file,
  mode,
  theme,
  fontSize = 12,
  wrap = false,
}: {
  file: ParsedDiffFile;
  mode: DiffMode;
  theme: 'light' | 'dark';
  fontSize?: number;
  wrap?: boolean;
}) => {
  if (file.isBinary) {
    return (
      <div className='text-muted-foreground px-3 py-2 text-xs'>
        Binary file not shown.
      </div>
    );
  }
  if (!file.hunkText.includes('@@')) {
    return (
      <div className='text-muted-foreground px-3 py-2 text-xs'>
        {file.status === 'renamed'
          ? 'Renamed with no content changes.'
          : 'No content changes.'}
      </div>
    );
  }
  return (
    <DiffView
      data={{
        oldFile: { fileName: file.oldPath || file.displayPath },
        newFile: { fileName: file.newPath || file.displayPath },
        hunks: [file.hunkText],
      }}
      diffViewMode={
        mode === 'split' ? DiffModeEnum.Split : DiffModeEnum.Unified
      }
      diffViewTheme={theme}
      diffViewHighlight
      diffViewWrap={wrap}
      diffViewFontSize={fontSize}
    />
  );
};
