'use client';

import dynamic from 'next/dynamic';

import { Button } from '@spoon/ui';

import { extractFileDiff } from './diff-utils';

const MonacoEditor = dynamic(async () => await import('@monaco-editor/react'), {
  ssr: false,
});

const diffStats = (diff: string) => {
  const files = new Set<string>();
  let additions = 0;
  let removals = 0;
  for (const line of diff.split('\n')) {
    if (line.startsWith('diff --git ')) files.add(line);
    if (line.startsWith('+') && !line.startsWith('+++')) additions += 1;
    if (line.startsWith('-') && !line.startsWith('---')) removals += 1;
  }
  return { files: files.size, additions, removals };
};

export const DiffViewer = ({
  diff,
  focusedPath,
  onRefresh,
  onClearFocusedPath,
}: {
  diff: string;
  focusedPath?: string;
  onRefresh: () => Promise<void>;
  onClearFocusedPath?: () => void;
}) => {
  const focusedDiff = focusedPath ? extractFileDiff(diff, focusedPath) : '';
  const visibleDiff = focusedPath ? focusedDiff : diff;
  const stats = diffStats(visibleDiff);
  return (
    <div className='flex h-full min-h-0 flex-col'>
      <div className='border-border flex h-12 items-center justify-between gap-3 border-b px-3'>
        <div className='min-w-0'>
          <p className='truncate text-sm font-medium'>
            {focusedPath ? `Diff viewer: ${focusedPath}` : 'Diff viewer'}
          </p>
          <p className='text-muted-foreground truncate text-xs'>
            {visibleDiff.trim()
              ? `${stats.files} files, +${stats.additions} -${stats.removals}`
              : focusedPath
                ? 'No diff for this file'
                : 'Current git diff'}
          </p>
        </div>
        <div className='flex flex-none items-center gap-2'>
          {focusedPath ? (
            <Button
              type='button'
              variant='ghost'
              size='sm'
              onClick={onClearFocusedPath}
            >
              Show all
            </Button>
          ) : null}
          <Button type='button' variant='outline' size='sm' onClick={onRefresh}>
            Refresh
          </Button>
        </div>
      </div>
      {visibleDiff.trim() ? (
        <MonacoEditor
          height='100%'
          width='100%'
          language='diff'
          theme='vs-dark'
          value={visibleDiff}
          options={{
            readOnly: true,
            minimap: { enabled: false },
            fontSize: 13,
            scrollBeyondLastLine: false,
            automaticLayout: true,
            scrollbar: { alwaysConsumeMouseWheel: false },
          }}
        />
      ) : (
        <div className='text-muted-foreground flex flex-1 items-center justify-center text-sm'>
          {focusedPath
            ? 'No diff is recorded for this file yet.'
            : 'No workspace diff yet.'}
        </div>
      )}
    </div>
  );
};
