'use client';

import React from 'react';
import { Modal, Spin, Typography } from 'antd';
import { FileCode2 } from 'lucide-react';
import { useQueryCache } from '@/hooks/useQueryCache';
import { API_ENDPOINTS } from '@/lib/api/endpoints';
import { useResponsiveModalProps } from '@/hooks/useResponsiveModalProps';
import { RepositorioGitCodeViewer } from './RepositorioGitCodeViewer';
import { inferCodeLanguageFromPath, formatFileSize } from './repositorioGitTreeHelpers';
import type { RepositoryFileResponse } from './types';
import styles from './ModalVisualizarArquivoGit.module.scss';
import { queryKeys } from '@/lib/cache/queryKeys';

export interface ModalVisualizarArquivoGitProps {
    open: boolean;
    projetoId: string;
    filePath: string | null;
    /** Branch ou commit GitLab (não usar prop `ref` — conflita com React string refs). */
    branchRef: string;
    onClose: () => void;
}

export function ModalVisualizarArquivoGit({
    open,
    projetoId,
    filePath,
    branchRef,
    onClose,
}: ModalVisualizarArquivoGitProps) {
    const responsiveModalProps = useResponsiveModalProps();

    const { data, isLoading, isError } = useQueryCache<RepositoryFileResponse>({
        queryKey: queryKeys.projetos.gitlabFileLegacy(projetoId, filePath ?? '', branchRef),
        endpoint: API_ENDPOINTS.projetos.gitlab.repositoryFile(projetoId),
        params: { path: filePath ?? '', ref: branchRef },
        enabled: open && !!filePath,
        staleTime: 30 * 1000,
        retry: 1,
    });

    const content = data?.file?.content ?? '';
    const size = data?.file?.size ?? 0;
    const language = filePath ? inferCodeLanguageFromPath(filePath) : 'plain';

    return (
        <Modal
            open={open}
            onCancel={onClose}
            footer={null}
            width={responsiveModalProps.width ?? Math.min(typeof window !== 'undefined' ? window.innerWidth - 48 : 1200, 1200)}
            centered={responsiveModalProps.centered ?? true}
            styles={responsiveModalProps.styles}
            destroyOnClose
            className={styles.modal}
            title={
                <div className={styles.titleRow}>
                    <FileCode2 size={18} aria-hidden />
                    <span className={styles.titleText}>{filePath ?? 'Arquivo'}</span>
                </div>
            }
        >
            <div className={styles.meta}>
                <Typography.Text type="secondary">Branch: {branchRef}</Typography.Text>
                {size > 0 ? (
                    <Typography.Text type="secondary">{formatFileSize(size)}</Typography.Text>
                ) : null}
            </div>
            <div className={styles.viewerWrap}>
                {isLoading ? (
                    <div className={styles.loading}>
                        <Spin size="large" />
                    </div>
                ) : isError ? (
                    <Typography.Text type="danger">
                        Não foi possível carregar o conteúdo do arquivo. Verifique permissões no GitLab.
                    </Typography.Text>
                ) : (
                    <RepositorioGitCodeViewer value={content} language={language} fillHeight />
                )}
            </div>
        </Modal>
    );
}
