'use client';

/**
 * Sugestões Cursor Pack — aprovação PO (ADR-0084 / CP-071).
 * @route /projetos/[id]/desenvolvimento/sugestoes-cursor
 */

import React, { useMemo, useState } from 'react';
import { Alert, Button, Space, Switch, Tag, Typography } from 'antd';
import { message } from '@/lib/feedback/message';
import type { ColumnsType } from 'antd/es/table';
import { useParams } from 'next/navigation';
import ProjetoLayout from '@/components/layouts/ProjetoLayout';
import MetricsGrid from '@/components/layouts/MetricsGrid';
import MetricCard from '@/components/layouts/MetricCard';
import { LazyDataTable } from '@/components/lazy';
import { ListagemEmptyState } from '@/components/listings';
import { useQueryCache } from '@/hooks/useQueryCache';
import { API_ENDPOINTS } from '@/lib/api/endpoints';
import apiClient from '@/lib/api/client';
import { Lightbulb, RefreshCw, CheckCheck, X, Sparkles } from 'lucide-react';
import { ICON_SIZE_MD } from '@/components/icons';
import { SyncComparacaoVertical } from '@/features/projetos/projeto-conectar/SyncComparacaoVertical';
import { useIsMobile } from '@/hooks/useIsMobile';
import { queryKeys } from '@/lib/cache/queryKeys';

type Sugestao = {
    id: number;
    titulo: string;
    descricao?: string | null;
    tipo_heuristica: string;
    prioridade_sugerida: string;
    status: string;
    origem: string;
    tarefa_id?: number | null;
    updated_at?: string | null;
};

type Metricas = {
    syncs_7d: number;
    sugestoes_pendentes: number;
    sugestoes_aprovadas: number;
    sugestoes_rejeitadas: number;
    tarefas_de_sugestao: number;
    taxa_aprovacao: number | null;
    auto_aprovar: boolean;
};

type SugestoesData = {
    items: Sugestao[];
    metricas: Metricas;
};

const HEURISTICA_LABEL: Record<string, string> = {
    modulo_sem_testes: 'Módulo sem testes',
    pagina_orfa: 'Página órfã',
    stack_sem_tech: 'Stack sem tech',
    modulo_novo_contexto: 'Módulo novo no handbook',
    escopo_vazio: 'Escopo (CONTEXT.md)',
    publico_alvo_vazio: 'Público-alvo / tom',
    stack_sugerida: 'Stack do catálogo',
    requisito_proposto: 'Requisito',
    risco_proposto: 'Risco',
    caso_uso_proposto: 'Caso de uso',
    acl_checklist: 'Checklist ACL',
    dominio_proposto: 'Domínio',
    email_auth_proposto: 'E-mails de autenticação',
    rt_proposto: 'Responsável técnico',
};

const TIPOS_TIPOLOGICOS = new Set([
    'escopo_vazio',
    'publico_alvo_vazio',
    'stack_sugerida',
    'requisito_proposto',
    'risco_proposto',
    'caso_uso_proposto',
    'acl_checklist',
    'dominio_proposto',
    'email_auth_proposto',
    'rt_proposto',
]);

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

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

    const [selected, setSelected] = useState<number[]>([]);
    const [busy, setBusy] = useState(false);
    const [autoLocal, setAutoLocal] = useState<boolean | null>(null);

    const metricas = data?.metricas;
    const autoAprovar = autoLocal ?? metricas?.auto_aprovar ?? false;

    const columns: ColumnsType<Sugestao> = useMemo(
        () => [
            {
                title: 'Sugestão',
                dataIndex: 'titulo',
                key: 'titulo',
                render: (t: string, row) => (
                    <Space direction="vertical" size={0}>
                        <Typography.Text strong>{t}</Typography.Text>
                        <Typography.Text type="secondary" style={{ fontSize: 12 }}>
                            {HEURISTICA_LABEL[row.tipo_heuristica] || row.tipo_heuristica}
                        </Typography.Text>
                    </Space>
                ),
            },
            {
                title: 'Prioridade',
                dataIndex: 'prioridade_sugerida',
                key: 'prio',
                width: 110,
            },
            {
                title: 'Status',
                dataIndex: 'status',
                key: 'status',
                width: 130,
                render: (s: string) => {
                    const color =
                        s === 'pendente' ? 'gold' : s === 'rejeitada' ? 'default' : 'green';
                    return <Tag color={color}>{s}</Tag>;
                },
            },
            {
                title: 'Origem',
                dataIndex: 'origem',
                key: 'origem',
                width: 120,
                render: () => <Tag color="blue">sync pack</Tag>,
            },
            {
                title: 'Tarefa',
                dataIndex: 'tarefa_id',
                key: 'tarefa',
                width: 110,
                render: (id: number | null | undefined, row) => {
                    if (id) return id;
                    if (TIPOS_TIPOLOGICOS.has(row.tipo_heuristica) && row.status !== 'pendente') {
                        return <Tag color="cyan">Aplicado no ERP</Tag>;
                    }
                    return '—';
                },
            },
        ],
        [],
    );

    const pendentes = (data?.items || []).filter((i) => i.status === 'pendente');

    async function analisar() {
        if (!projetoId) return;
        setBusy(true);
        try {
            await apiClient.post(API_ENDPOINTS.projetos.cursorSugestoesAnalisar(projetoId));
            message.success('Análise concluída');
            await refetch();
        } catch {
            message.error('Falha ao analisar contexto');
        } finally {
            setBusy(false);
        }
    }

    async function lote(acao: 'aprovar' | 'rejeitar') {
        if (!projetoId || selected.length === 0) return;
        setBusy(true);
        try {
            await apiClient.post(API_ENDPOINTS.projetos.cursorSugestoesLote(projetoId), {
                acao,
                ids: selected,
            });
            message.success(
                acao === 'aprovar'
                    ? 'Sugestões aprovadas (tipológicas aplicadas no ERP; clássicas geram tarefa)'
                    : 'Sugestões rejeitadas',
            );
            setSelected([]);
            await refetch();
        } catch {
            message.error('Falha ao processar lote');
        } finally {
            setBusy(false);
        }
    }

    async function toggleAuto(checked: boolean) {
        if (!projetoId) return;
        setBusy(true);
        try {
            await apiClient.patch(API_ENDPOINTS.projetos.cursorSugestoesAutoAprovar(projetoId), {
                cursor_sugestoes_auto_aprovar: checked,
            });
            setAutoLocal(checked);
            message.success(checked ? 'Auto-aprovação ativada neste projeto' : 'Auto-aprovação desligada');
            await refetch();
        } catch {
            message.error('Não foi possível atualizar a política');
        } finally {
            setBusy(false);
        }
    }

    return (
        <ProjetoLayout
            projetoId={projetoId}
            pageTitle="Sugestões Cursor Pack"
            showPageTitleIcon={false}
            titleSection="Sugestões Cursor Pack"
            headerAction={
                <Space wrap>
                    <Button icon={<Sparkles size={ICON_SIZE_MD} />} loading={busy} onClick={analisar}>
                        Analisar agora
                    </Button>
                    <Button
                        type="primary"
                        icon={<CheckCheck size={ICON_SIZE_MD} />}
                        disabled={selected.length === 0}
                        loading={busy}
                        onClick={() => lote('aprovar')}
                    >
                        Aprovar lote
                    </Button>
                    <Button
                        danger
                        icon={<X size={ICON_SIZE_MD} />}
                        disabled={selected.length === 0}
                        loading={busy}
                        onClick={() => lote('rejeitar')}
                    >
                        Rejeitar lote
                    </Button>
                    <Button icon={<RefreshCw size={ICON_SIZE_MD} />} loading={isFetching} onClick={() => refetch()}>
                        Atualizar
                    </Button>
                </Space>
            }
        >
            <Typography.Paragraph type="secondary" style={{ marginTop: 0, marginBottom: 12 }}>
                Heurísticas sobre o handbook sincronizado — aprovação antes de criar tarefas
            </Typography.Paragraph>

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

            <Alert
                type="info"
                showIcon
                style={{ marginBottom: 16 }}
                message="O scan nunca cria tarefa de produção sem aprovação (padrão)."
                description={
                    <Space>
                        <span>Auto-aprovar neste projeto (CP-073):</span>
                        <Switch checked={autoAprovar} loading={busy} onChange={toggleAuto} />
                    </Space>
                }
            />

            <MetricsGrid>
                <MetricCard
                    label="Syncs (7d)"
                    value={metricas?.syncs_7d ?? 0}
                    icon={<RefreshCw size={ICON_SIZE_MD} />}
                    loading={isLoading}
                />
                <MetricCard
                    label="Pendentes"
                    value={metricas?.sugestoes_pendentes ?? 0}
                    icon={<Lightbulb size={ICON_SIZE_MD} />}
                    loading={isLoading}
                />
                <MetricCard
                    label="Aprovadas"
                    value={metricas?.sugestoes_aprovadas ?? 0}
                    icon={<CheckCheck size={ICON_SIZE_MD} />}
                    loading={isLoading}
                />
                <MetricCard
                    label="Tarefas de sugestão"
                    value={metricas?.tarefas_de_sugestao ?? 0}
                    icon={<Sparkles size={ICON_SIZE_MD} />}
                    loading={isLoading}
                    subvalue={
                        metricas?.taxa_aprovacao != null
                            ? `Taxa aprovação ${(metricas.taxa_aprovacao * 100).toFixed(0)}%`
                            : undefined
                    }
                />
            </MetricsGrid>

            <div style={{ marginTop: 16 }}>

            {!isLoading && pendentes.length === 0 && (data?.items?.length ?? 0) === 0 ? (
                <ListagemEmptyState
                    message="Nenhuma sugestão"
                    description='Nenhuma sugestão. Rode o sync do pack e depois "Analisar agora".'
                />
            ) : (
                <LazyDataTable
                    rowKey="id"
                    loading={isLoading || busy}
                    columns={columns}
                    data={data?.items || []}
                    rowSelection={{
                        selectedRowKeys: selected,
                        onChange: (keys) => setSelected(keys.map((k) => Number(k))),
                        getCheckboxProps: (record: any) => ({
                            disabled: record.status !== 'pendente',
                        }),
                    }}
                    pagination={{ pageSize: 20, showSizeChanger: true }}
                    expandable={
                        isMobile
                            ? undefined
                            : {
                                  expandedRowRender: (row) => (
                                      <SyncComparacaoVertical
                                          forceStack
                                          esquerda={{
                                              titulo: 'Heurística',
                                              corpo:
                                                  HEURISTICA_LABEL[row.tipo_heuristica] ||
                                                  row.tipo_heuristica,
                                          }}
                                          direita={{
                                              titulo: 'Descrição',
                                              corpo: row.descricao || 'Sem descrição.',
                                          }}
                                      />
                                  ),
                              }
                    }
                    ariaRegionLabel="Sugestões Cursor Pack"
                    autoMobileFromColumns={{
                        testIdPrefix: 'sugestoes-cursor',
                        listHeading: 'Lista de sugestões',
                        getFallbackTitle: (r) =>
                            r.titulo?.trim() || `Sugestão ${r.id}`,
                    }}
                />
            )}
            
</div>
        </ProjetoLayout>
    );
}
