'use client';

/**
 * Contexto do Cursor Pack sincronizado no ERP (ADR-0083 / CP-053).
 * @route /projetos/[id]/desenvolvimento/contexto
 */

import React, { useMemo } from 'react';
import { Alert, Empty, Table, Tag, Typography, Button, Space } from 'antd';
import { useParams } from 'next/navigation';
import ProjetoLayout from '@/components/layouts/ProjetoLayout';
import ContentCard from '@/components/layouts/ContentCard';
import MetricsGrid from '@/components/layouts/MetricsGrid';
import MetricCard from '@/components/layouts/MetricCard';
import { useQueryCache } from '@/hooks/useQueryCache';
import { API_ENDPOINTS } from '@/lib/api/endpoints';
import { FileCode2, Hash, Package, Clock, RefreshCw, Download } from 'lucide-react';
import { ICON_SIZE_MD } from '@/components/icons';
import {
    CURSOR_PACK_DOWNLOAD_URL,
    CURSOR_PACK_RELEASE_VERSION,
} from '@/features/projetos/ide-vscode/cursorPackRelease';
import { EntendimentoCompletudeChip } from '@/features/projetos/entendimento-completude';
import { queryKeys } from '@/lib/cache/queryKeys';

const PROJETOS_LIST_PATH = '/projetos';

type ContextoFile = {
    path: string;
    content_hash: string;
    content_bytes: number;
    pack_version?: string | null;
    synced_at?: string | null;
};

type ContextoData = {
    pack_version: string | null;
    sync_id: string | null;
    synced_at: string | null;
    total_files: number;
    files: ContextoFile[];
};

export function ProjetoContextoScreen() {
    const params = useParams();
    const projetoId =
        typeof params?.id === 'string' ? params.id : Array.isArray(params?.id) ? params.id[0] : '';

    const endpoint = projetoId ? API_ENDPOINTS.projetos.cursorContexto(projetoId) : '';
    const { data, isLoading, error, refetch, isFetching } = useQueryCache<ContextoData>({
        queryKey: queryKeys.projetos.cursorContexto(projetoId),
        endpoint,
        enabled: Boolean(projetoId),
        unwrapApiEnvelope: true,
    });

    const columns = useMemo(
        () => [
            { title: 'Path', dataIndex: 'path', key: 'path', ellipsis: true },
            {
                title: 'Hash',
                dataIndex: 'content_hash',
                key: 'hash',
                width: 120,
                render: (h: string) => (h ? `${h.slice(0, 8)}…` : '—'),
            },
            {
                title: 'Bytes',
                dataIndex: 'content_bytes',
                key: 'bytes',
                width: 100,
                align: 'right' as const,
            },
            {
                title: 'Sync',
                dataIndex: 'synced_at',
                key: 'synced_at',
                width: 200,
                render: (v: string | null) => v || '—',
            },
        ],
        [],
    );

    return (
        <ProjetoLayout
            projetoId={projetoId}
            pageTitle="Contexto do projeto"
            pageIcon="book"
            titleSection="Contexto do projeto"
            breadcrumbItems={[
                { title: 'PROJETO', path: PROJETOS_LIST_PATH },
                { title: 'Projeto', path: projetoId ? `${PROJETOS_LIST_PATH}/${projetoId}` : undefined },
                { title: 'Código' },
                { title: 'Contexto do projeto' },
            ]}
            headerAction={
                <Space wrap>
                    <Button
                        icon={<Download size={ICON_SIZE_MD} />}
                        href={CURSOR_PACK_DOWNLOAD_URL}
                        target="_blank"
                        rel="noopener noreferrer"
                    >
                        Baixar kit Cursor ({CURSOR_PACK_RELEASE_VERSION})
                    </Button>
                    <Button icon={<RefreshCw size={ICON_SIZE_MD} />} loading={isFetching} onClick={() => refetch()}>
                        Atualizar
                    </Button>
                </Space>
            }
        >
            <Typography.Paragraph type="secondary" style={{ marginTop: 0, marginBottom: 12 }}>
                Handbook sincronizado pelo Cursor Pack (allowlist).
            </Typography.Paragraph>

            {projetoId ? (
                <div style={{ marginBottom: 16 }}>
                    <EntendimentoCompletudeChip projetoId={projetoId} />
                </div>
            ) : null}

            {error ? (
                <Alert
                    type="error"
                    showIcon
                    style={{ marginBottom: 16 }}
                    message="Não foi possível carregar o contexto"
                    description="Confirme o addon VS Code/Cursor e a permissão de visualização do projeto."
                />
            ) : null}

            <MetricsGrid>
                <MetricCard
                    label="Pack"
                    value={data?.pack_version || '—'}
                    icon={<Package size={ICON_SIZE_MD} />}
                    loading={isLoading}
                />
                <MetricCard
                    label="Arquivos"
                    value={data?.total_files ?? 0}
                    icon={<FileCode2 size={ICON_SIZE_MD} />}
                    loading={isLoading}
                />
                <MetricCard
                    label="Último sync"
                    value={data?.synced_at ? new Date(data.synced_at).toLocaleString('pt-BR') : '—'}
                    icon={<Clock size={ICON_SIZE_MD} />}
                    loading={isLoading}
                />
                <MetricCard
                    label="Sync ID"
                    value={data?.sync_id ? `${data.sync_id.slice(0, 8)}…` : '—'}
                    icon={<Hash size={ICON_SIZE_MD} />}
                    loading={isLoading}
                />
            </MetricsGrid>

            <ContentCard title="Arquivos" style={{ marginTop: 16 }}>
                {!isLoading && (!data || data.total_files === 0) ? (
                    <Empty
                        description={
                            <Typography.Text type="secondary">
                                Ainda sem sync. No repo cliente use <Tag>sync.ps1</Tag> (pack ≥ 0.6.0).
                            </Typography.Text>
                        }
                    />
                ) : (
                    <Table
                        rowKey="path"
                        loading={isLoading}
                        columns={columns}
                        dataSource={data?.files || []}
                        pagination={{ pageSize: 20, showSizeChanger: true }}
                        size="middle"
                    />
                )}
            </ContentCard>
        </ProjetoLayout>
    );
}
