'use client';

import React, { useMemo } from 'react';
import dynamic from 'next/dynamic';
import { html } from '@codemirror/lang-html';
import { css } from '@codemirror/lang-css';
import { javascript } from '@codemirror/lang-javascript';
import { oneDark } from '@codemirror/theme-one-dark';
import { EditorView, lineNumbers } from '@codemirror/view';
import { useTheme } from '@/contexts/ThemeContext';
import styles from './RepositorioGitCodeViewer.module.scss';
import type { inferCodeLanguageFromPath } from './repositorioGitTreeHelpers';

const CodeMirror = dynamic(() => import('@uiw/react-codemirror'), { ssr: false });

type CodeLanguage = ReturnType<typeof inferCodeLanguageFromPath>;

export interface RepositorioGitCodeViewerProps {
    value: string;
    language?: CodeLanguage;
    minHeight?: number;
    fillHeight?: boolean;
}

export function RepositorioGitCodeViewer({
    value,
    language = 'plain',
    minHeight = 420,
    fillHeight = true,
}: RepositorioGitCodeViewerProps) {
    const { theme } = useTheme();
    const isDark = theme === 'dark';

    const extensions = useMemo(() => {
        const langExt =
            language === 'html'
                ? html()
                : language === 'css'
                  ? css()
                  : language === 'javascript'
                    ? javascript({ jsx: true, typescript: true })
                    : null;

        return [
            ...(langExt ? [langExt] : []),
            lineNumbers(),
            EditorView.lineWrapping,
            EditorView.editable.of(false),
            EditorView.theme({
                '&': { backgroundColor: 'transparent' },
                '.cm-content': { padding: '12px 0' },
                '.cm-gutters': {
                    borderRight: '1px solid var(--border-light, #f0f0f0)',
                    backgroundColor: isDark ? '#1f1f1f' : 'var(--background-secondary, #fafafa)',
                },
            }),
        ];
    }, [isDark, language]);

    return (
        <div
            className={`${styles.root} ${fillHeight ? styles.rootFill : ''}`}
            style={{ ['--repo-code-min-height' as string]: `${minHeight}px` }}
        >
            <CodeMirror
                className={`${styles.surface} ${fillHeight ? styles.surfaceFill : ''}`}
                value={value}
                height={fillHeight ? '100%' : `${minHeight}px`}
                width="100%"
                theme={isDark ? oneDark : 'light'}
                extensions={extensions}
                readOnly
                editable={false}
                basicSetup={{
                    foldGutter: true,
                    highlightSelectionMatches: false,
                    autocompletion: false,
                }}
            />
        </div>
    );
}
