'use client';

/**
 * Detalhe de log por ID — `DetailPageLayout` + `fetchState` + `DetailHeaderActions` (rollout §3).
 * @route /suporte/logs/[id]
 */
import { FileText, ListChecks } from 'lucide-react';
import { queryKeys } from '@/lib/cache/queryKeys';
import { ICON_SIZE_MD } from '@/components/icons';
import React, { useCallback, useMemo, useState } from 'react';
import Link from 'next/link';
import { useRouter } from 'next/navigation';
import { Button, Descriptions, Tag, Typography, Card, Alert, Timeline, Modal, Space, Collapse, List } from 'antd';
import { message } from '@/lib/feedback/message';
import { useQueryCache } from '@/hooks/useQueryCache';
import { usePermissions } from '@/contexts/PermissionsContext';
import { API_ENDPOINTS } from '@/lib/api/endpoints';
import PageWrapper from '@/components/layouts/PageWrapper';
import { DetailPageLayout } from '@/components/layouts/DetailPageLayout';
import { DetailHeaderActions } from '@/components/layouts/DetailHeader';
import ContentCard from '@/components/layouts/ContentCard';
import type { DetailPageFetchState } from '@/components/layouts/DetailPageLayout';
import { ModalOpcoesLog } from './components/ModalOpcoesLog';
import { ModalGerarTarefaCorrecaoLog } from './components/ModalGerarTarefaCorrecaoLog';
import type { LogEntry } from './types';
import { getLogLevelColor } from './logsLevelUtils';
import { buildSanitizedLogJson, buildTechnicalPromptMarkdown, sanitizeLogForPrompt } from './logTechnicalPrompt';

const SUPORTE_HUB_PATH = '/suporte';
const SUPORTE_LOGS_LIST_PATH = '/suporte/logs';

async function copyTextToClipboard(text: string): Promise<boolean> {
    try {
        await navigator.clipboard.writeText(text);
        return true;
    } catch {
        try {
            const ta = document.createElement('textarea');
            ta.value = text;
            ta.style.position = 'fixed';
            ta.style.left = '-9999px';
            document.body.appendChild(ta);
            ta.select();
            document.execCommand('copy');
            document.body.removeChild(ta);
            return true;
        } catch {
            return false;
        }
    }
}

export interface SuporteLogDetalheByIdScreenProps {
    logId: string;
}

export function SuporteLogDetalheByIdScreen({ logId: rawId }: SuporteLogDetalheByIdScreenProps) {
    const router = useRouter();
    const id = rawId.trim();
    const idValid = Boolean(id);
    const { hasPermission } = usePermissions();
    const podeGerenciarLogs = hasPermission('projetos.logs.gerenciar');

    const {
        data: log,
        isLoading,
        isError,
        isFetched,
        error: queryError,
        refetch} = useQueryCache<LogEntry>({
        queryKey: queryKeys.projetos.logs.show(id),
        endpoint: idValid ? API_ENDPOINTS.projetos.logs.show(id) : '',
        enabled: idValid,
        staleTime: 2 * 60 * 1000});

    const errStatus = (queryError as { response?: { status?: number } } | null)?.response?.status;

    const fetchState: DetailPageFetchState = useMemo(() => {
        if (!idValid) return 'not_found';
        if (isLoading) return 'loading';
        if (isError) return errStatus === 404 ? 'not_found' : 'error';
        if (isFetched && !log) return 'not_found';
        return 'ready';
    }, [idValid, isLoading, isError, isFetched, log, errStatus]);

    const queryErr =
        queryError instanceof Error ? queryError : queryError ? new Error(String(queryError)) : null;

    const [modalOpcoesOpen, setModalOpcoesOpen] = useState(false);
    const [modalTarefaOpen, setModalTarefaOpen] = useState(false);
    const [modalPromptOpen, setModalPromptOpen] = useState(false);

    const textoPromptTecnico = useMemo(() => (log ? buildTechnicalPromptMarkdown(log) : ''), [log]);

    const logExibicao = useMemo(() => (log ? sanitizeLogForPrompt(log).sanitized : null), [log]);

    const handleVoltar = () => router.push(SUPORTE_LOGS_LIST_PATH);

    const handleCopiarPrompt = useCallback(async () => {
        const ok = await copyTextToClipboard(textoPromptTecnico);
        if (ok) message.success('Prompt copiado.');
        else message.error('Não foi possível copiar.');
    }, [textoPromptTecnico]);

    const handleCopiarId = useCallback(async () => {
        if (!log) return;
        const ok = await copyTextToClipboard(String(log.id));
        if (ok) message.success('ID copiado.');
        else message.error('Não foi possível copiar.');
    }, [log]);

    const handleCopiarUrlPagina = useCallback(async () => {
        if (typeof window === 'undefined') return;
        const ok = await copyTextToClipboard(window.location.href);
        if (ok) message.success('URL copiada.');
        else message.error('Não foi possível copiar.');
    }, []);

    const handleExportarJsonRedigido = useCallback(async () => {
        if (!log) return;
        const ok = await copyTextToClipboard(buildSanitizedLogJson(log));
        if (ok) message.success('JSON redigido copiado.');
        else message.error('Não foi possível copiar.');
    }, [log]);

    const handleExcluido = () => {
        router.push(SUPORTE_LOGS_LIST_PATH);
    };

    if (!idValid) {
        return (
            <PageWrapper
                breadcrumbItems={[
                    { title: 'Suporte', path: SUPORTE_HUB_PATH },
                    { title: 'Logs', path: SUPORTE_LOGS_LIST_PATH },
                    { title: 'Detalhe' },
                ]}
            >
                <Alert
                    message="Log inválido"
                    description="Identificador em falta na rota."
                    type="error"
                    showIcon
                    action={
                        <Button type="primary" size="small" onClick={handleVoltar}>
                            Voltar à lista
                        </Button>
                    }
                />
            </PageWrapper>
        );
    }

    const headerTitle =
        log != null
            ? `Detalhe do log #${log.id}`
            : fetchState === 'loading'
              ? 'Carregando…'
              : 'Detalhe do log';

    return (
        <DetailPageLayout
            breadcrumbItems={[
                { title: 'Suporte', path: SUPORTE_HUB_PATH },
                { title: 'Logs', path: SUPORTE_LOGS_LIST_PATH },
                { title: log ? `#${log.id}` : 'Detalhe' },
            ]}
            fetchState={fetchState}
            error={queryErr}
            onRetry={() => void refetch()}
            errorTitle="Não foi possível carregar o log"
            wrapChildrenInCard={false}
            header={{
                title: headerTitle,
                description: 'Consulte o registro completo e o contexto abaixo.',
                icon: <FileText size={ICON_SIZE_MD} aria-hidden />,
                actions:
                    log && fetchState === 'ready' ? (
                        <DetailHeaderActions
                            primary={
                                podeGerenciarLogs ? (
                                    <Button
                                        type="primary"
                                        icon={<ListChecks size={ICON_SIZE_MD} style={{ marginRight: 8 }} aria-hidden />}
                                        onClick={() => setModalTarefaOpen(true)}
                                    >
                                        Gerar tarefa de correção
                                    </Button>
                                ) : undefined
                            }
                            secondary={[
                                <Button key="prompt" onClick={() => setModalPromptOpen(true)}>
                                    Prompt técnico
                                </Button>,
                                <Button key="voltar" onClick={handleVoltar}>
                                    Voltar à lista
                                </Button>,
                            ]}
                            moreMenuItems={[
                                {
                                    key: 'copiar-id',
                                    label: 'Copiar ID do log',
                                    onClick: () => void handleCopiarId()},
                                {
                                    key: 'copiar-url',
                                    label: 'Copiar URL desta página',
                                    onClick: () => void handleCopiarUrlPagina()},
                                {
                                    key: 'copiar-json',
                                    label: 'Copiar JSON redigido',
                                    onClick: () => void handleExportarJsonRedigido()},
                                ...(podeGerenciarLogs
                                    ? ([
                                          { type: 'divider' as const, key: 'd1' },
                                          {
                                              key: 'acoes',
                                              label: 'Marcar realizado / excluir…',
                                              onClick: () => setModalOpcoesOpen(true),
                                          },
                                      ] as const)
                                    : []),
                            ]}
                        />
                    ) : undefined}}
        >
            {log && fetchState === 'ready' ? (
                    <>
                        <ModalOpcoesLog
                            open={modalOpcoesOpen}
                            onClose={() => setModalOpcoesOpen(false)}
                            log={log}
                            onVerDetalhes={() => {}}
                            onExcluido={handleExcluido}
                            somenteExcluir
                            podeGerenciar={podeGerenciarLogs}
                        />
                        {podeGerenciarLogs ? (
                            <ModalGerarTarefaCorrecaoLog
                                open={modalTarefaOpen}
                                onClose={() => setModalTarefaOpen(false)}
                                log={log}
                                logId={id}
                                onSuccessNavigate={(tarefaId) => router.push(`/minhas-tarefas/tarefas/${tarefaId}`)}
                            />
                        ) : null}
                        <Modal
                            title="Prompt técnico"
                            open={modalPromptOpen}
                            onCancel={() => setModalPromptOpen(false)}
                            footer={[
                                <Button key="fechar" onClick={() => setModalPromptOpen(false)}>
                                    Fechar
                                </Button>,
                                <Button key="copiar" type="primary" onClick={() => void handleCopiarPrompt()}>
                                    Copiar
                                </Button>,
                            ]}
                            width={720}
                            destroyOnClose
                        >
                            <Typography.Paragraph type="secondary" style={{ marginBottom: 12 }}>
                                Texto pronto para colar num assistente ou ticket interno. Dados sensíveis são
                                reduzidos automaticamente no modelo abaixo.
                            </Typography.Paragraph>
                            <div
                                style={{
                                    maxHeight: 420,
                                    overflow: 'auto',
                                    background: '#fafafa',
                                    padding: 12,
                                    borderRadius: 8,
                                    fontSize: 12,
                                    fontFamily: 'monospace',
                                    whiteSpace: 'pre-wrap',
                                    wordBreak: 'break-word'}}
                            >
                                {textoPromptTecnico}
                            </div>
                        </Modal>

                        <ContentCard className="log-detalhe-card">
                            <Alert
                                type="info"
                                showIcon
                                style={{ marginBottom: 16 }}
                                message="Guia rápido de diagnóstico"
                                description="Siga a ordem: confirmar ambiente → reproduzir URL → cruzar contexto JSON → rever stack. Use copiar/colar seguro para tickets internos."
                            />
                            <Timeline
                                style={{ marginBottom: 20 }}
                                items={[
                                    { color: 'blue', children: 'Confirmar ambiente e projeto — descartar ruído de desenvolvimento.' },
                                    { color: 'blue', children: 'Reproduzir o pedido (método + URL) em janela anónima ou outro usuário.' },
                                    { color: 'green', children: 'Inspecionar contexto JSON por IDs de recurso e payloads incompletos.' },
                                    {
                                        color: log?.stack ? 'red' : 'gray',
                                        children: log?.stack
                                            ? 'Analisar stack: foco nas primeiras linhas da aplicação (não em vendor).'
                                            : 'Sem stack — tratar como evento de negócio ou log de aplicação.'},
                                ]}
                            />
                            <Descriptions
                                title="Informações do log"
                                bordered
                                column={1}
                                size="small"
                                labelStyle={{ fontWeight: 600, width: 140 }}
                            >
                                <Descriptions.Item label="ID">
                                    <Space wrap>
                                        <Typography.Text code>{log.id}</Typography.Text>
                                        <Button size="small" type="link" onClick={() => void handleCopiarId()}>
                                            Copiar ID
                                        </Button>
                                        <Button size="small" type="link" onClick={() => void handleCopiarUrlPagina()}>
                                            Copiar URL
                                        </Button>
                                        <Button size="small" type="link" onClick={() => void handleExportarJsonRedigido()}>
                                            JSON redigido
                                        </Button>
                                    </Space>
                                </Descriptions.Item>
                                <Descriptions.Item label="Data/hora">
                                    <Typography.Text code>{log.logged_at}</Typography.Text>
                                </Descriptions.Item>
                                <Descriptions.Item label="Tipo">
                                    <Tag color={getLogLevelColor(log.level)}>
                                        {(log.level || '').toUpperCase()}
                                    </Tag>
                                </Descriptions.Item>
                                <Descriptions.Item label="Ambiente">{log.environment || 'local'}</Descriptions.Item>
                                <Descriptions.Item label="Mensagem">
                                    <Typography.Text>{log.message}</Typography.Text>
                                </Descriptions.Item>
                                {log.header ? (
                                    <Descriptions.Item label="Cabeçalho">
                                        <Typography.Text>{log.header}</Typography.Text>
                                    </Descriptions.Item>
                                ) : null}
                                {log.url ? (
                                    <Descriptions.Item label="URL">
                                        <Typography.Text code>
                                            {log.method} {log.url}
                                        </Typography.Text>
                                    </Descriptions.Item>
                                ) : null}
                                {log.projeto ? (
                                    <Descriptions.Item label="Projeto">
                                        <Link href={`/projetos/${log.projeto.id}`}>
                                            {log.projeto.nome ?? `#${log.projeto.id}`}
                                        </Link>
                                    </Descriptions.Item>
                                ) : null}
                                {log.usuario ? (
                                    <Descriptions.Item label="Usuário">
                                        {log.usuario.nome ?? `#${log.usuario.id}`}
                                    </Descriptions.Item>
                                ) : null}
                                {log.ip_address ? (
                                    <Descriptions.Item label="IP">{log.ip_address}</Descriptions.Item>
                                ) : null}
                                {log.resolved_at ? (
                                    <Descriptions.Item label="Resolução">
                                        <Typography.Text>
                                            Resolvido em {log.resolved_at}
                                            {log.resolution_note ? ` — ${log.resolution_note}` : ''}
                                        </Typography.Text>
                                    </Descriptions.Item>
                                ) : (
                                    <Descriptions.Item label="Resolução">
                                        <Tag>Pendente</Tag>
                                    </Descriptions.Item>
                                )}
                            </Descriptions>

                            {log.tarefas_correcao && log.tarefas_correcao.length > 0 ? (
                                <Card title="Tarefas ligadas" size="small" style={{ marginTop: 20 }}>
                                    <List
                                        size="small"
                                        dataSource={log.tarefas_correcao}
                                        renderItem={(tarefa) => (
                                            <List.Item>
                                                <Link href={`/minhas-tarefas/tarefas/${tarefa.id}`}>
                                                    #{tarefa.id} — {tarefa.titulo}
                                                </Link>
                                                {tarefa.status ? (
                                                    <Tag style={{ marginLeft: 8 }}>{tarefa.status}</Tag>
                                                ) : null}
                                            </List.Item>
                                        )}
                                    />
                                </Card>
                            ) : null}

                            {logExibicao?.context && Object.keys(logExibicao.context).length > 0 && (
                                <Collapse
                                    style={{ marginTop: 20 }}
                                    defaultActiveKey={[]}
                                    items={[
                                        {
                                            key: 'context',
                                            label: 'Contexto (JSON)',
                                            children: (
                                                <pre
                                                    style={{
                                                        margin: 0,
                                                        whiteSpace: 'pre-wrap',
                                                        wordBreak: 'break-all',
                                                        fontSize: 12,
                                                        background: '#fafafa',
                                                        padding: 12,
                                                        borderRadius: 8,
                                                        maxHeight: 280,
                                                        overflow: 'auto'}}
                                                >
                                                    {JSON.stringify(logExibicao.context, null, 2)}
                                                </pre>
                                            ),
                                        },
                                    ]}
                                />
                            )}

                            {logExibicao?.stack ? (
                                <Collapse
                                    style={{ marginTop: 20 }}
                                    defaultActiveKey={[]}
                                    items={[
                                        {
                                            key: 'stack',
                                            label: 'Stack trace',
                                            children: (
                                                <pre
                                                    style={{
                                                        margin: 0,
                                                        whiteSpace: 'pre-wrap',
                                                        wordBreak: 'break-all',
                                                        fontSize: 12,
                                                        background: '#fff5f5',
                                                        padding: 12,
                                                        borderRadius: 8,
                                                        maxHeight: 280,
                                                        overflow: 'auto'}}
                                                >
                                                    {logExibicao.stack}
                                                </pre>
                                            ),
                                        },
                                    ]}
                                />
                            ) : null}
                        </ContentCard>
                    </>
                ) : null}
        </DetailPageLayout>
    );
}
