'use client';

import { confirmDialog } from '@/lib/feedback/confirmDialog';

/**
 * Tecnologias vinculadas a um projeto (`/projetos/[id]/tecnologias`).
 * FRONT-S2-02 — extraído de `app/(dashboard)/projetos/[id]/tecnologias/page.tsx`.
 */
import { Code, Menu as MenuIcon, Plus, CheckCircle2 } from 'lucide-react';
import { ICON_SIZE_MD } from '@/components/icons';
import React, { useMemo, useState } from 'react';
import { Button, Space, Tag, Form, Input, Select, Descriptions, Row, Col, Rate, Alert, Statistic, Tooltip, Modal } from 'antd';
import { message } from '@/lib/feedback/message';
import { notifyApiError } from '@/lib/feedback/notifyApiError';
import { LazyExportButton } from '@/components/lazy';
import { LazyDataTable } from '@/components/lazy';
import type { ColumnsType } from 'antd/es/table';
import { PermissionGuard } from '@/components/permissions';
import { useQueryCache } from '@/hooks/useQueryCache';
import { useMutationCache } from '@/hooks/useMutationCache';
import { useWaygestFormModalProps } from '@/hooks/useWaygestFormModalProps';
import { queryKeys } from '@/lib/cache/queryKeys';
import apiClient from '@/lib/api/client';
import { API_ENDPOINTS } from '@/lib/api/endpoints';
import { formatDate } from '@/lib/utils/export';
import { listingTableVirtualScrollProps } from '@/lib/listings/listingTableVirtualScrollProps';
import dayjs from 'dayjs';
import { FormTextarea } from '@/components/form';
import ProjetoLayout from '@/components/layouts/ProjetoLayout';
import { ListPageCreateFloatButton } from '@/components/listings';
import btnHeaderStyles from '@/components/ui/buttons/ButtonHeaderIcon/ButtonHeaderIcon.module.scss';
import { EmptyState } from '@/components/empty';
import Link from 'next/link';
import { projetosProjetoCanonical } from '@/lib/routes/projetosProjetoCanonical';
import {
    ProjetoTipologicoSyncCtas,
    STACK_VS_TECNOLOGIAS_ALERT,
} from '@/features/projetos/projeto-tipologico-empty-state';
import { ModalOpcoesTecnologia } from './ModalOpcoesTecnologia';
import type { TecnologiaProjeto } from './types';
import { getProjetoTecnologiaStatusColor, getProjetoTecnologiaTipoColor } from './projetoTecnologiasDisplay';

function tecnologiaPendenteConfirmacao(t: TecnologiaProjeto): boolean {
    if (t.pivot?.confirmado_manual) return false;
    const conf = String(t.pivot?.confianca || '').toLowerCase();
    return conf === 'baixa' || conf === 'media' || conf === '';
}

export interface ProjetoTecnologiasScreenProps {
    projetoId: string;
}

export function ProjetoTecnologiasScreen({ projetoId: id }: ProjetoTecnologiasScreenProps) {
    const [modalVisible, setModalVisible] = useState(false);
    const [viewModalVisible, setViewModalVisible] = useState(false);
    const [selectedTecnologia, setSelectedTecnologia] = useState<TecnologiaProjeto | null>(null);
    const [editingTecnologia, setEditingTecnologia] = useState<TecnologiaProjeto | null>(null);
    const [form] = Form.useForm();
    const [opcoesItem, setOpcoesItem] = useState<TecnologiaProjeto | null>(null);
    const modalLayout = useWaygestFormModalProps();

    const {
        data: tecnologiasData,
        isLoading,
        refetch} = useQueryCache<{ data: TecnologiaProjeto[] }>({
        queryKey: queryKeys.projetos.tecnologias(id),
        endpoint: API_ENDPOINTS.projetos.tecnologias.index(id),
        enabled: !!id,
        staleTime: 1 * 60 * 1000,
        gcTime: 5 * 60 * 1000});

    const tecnologias = tecnologiasData?.data || [];

    const metricasStack = useMemo(() => {
        const ativos = tecnologias.filter((t) => t.status === 'ativo').length;
        const deprecados = tecnologias.filter((t) => t.status === 'deprecado').length;
        const emAval = tecnologias.filter((t) => t.status === 'em_avaliacao').length;
        const pendentesConfirmacao = tecnologias.filter(tecnologiaPendenteConfirmacao).length;
        return { ativos, deprecados, emAval, total: tecnologias.length, pendentesConfirmacao };
    }, [tecnologias]);

    const confirmLoteMutation = useMutationCache<{ confirmadas?: number }, Record<string, never>>({
        endpoint: API_ENDPOINTS.projetos.tecnologias.confirmarLote(id),
        method: 'POST',
        buildBody: () => ({}),
        invalidateQueries: [
            queryKeys.projetos.tecnologias(id),
            queryKeys.projetos.documentacaoHealth(id),
        ],
        onSuccess: (res) => {
            message.success(
                res?.confirmadas
                    ? `${res.confirmadas} tecnologia(s) confirmada(s).`
                    : 'Tecnologias confirmadas.',
            );
            void refetch();
        },
        onError: (err) => notifyApiError(err, 'Não foi possível confirmar as tecnologias'),
    });

    const saveMutation = useMutationCache({
        endpoint: editingTecnologia
            ? API_ENDPOINTS.projetos.tecnologias.update(id, editingTecnologia.id)
            : API_ENDPOINTS.projetos.tecnologias.store(id),
        method: editingTecnologia ? 'PUT' : 'POST',
        invalidateQueries: [queryKeys.projetos.tecnologias(id)],
        onSuccess: () => {
            message.success(
                editingTecnologia
                    ? 'Tecnologia atualizada com sucesso!'
                    : 'Tecnologia adicionada com sucesso!'
            );
            setModalVisible(false);
            form.resetFields();
            refetch();
        },
        onError: (error: unknown) => {
            const errorMessage =
                (error as { response?: { data?: { message?: string } } })?.response?.data?.message ||
                'Erro ao salvar tecnologia';
            message.error(errorMessage);
        }});

    const handleCreate = () => {
        setEditingTecnologia(null);
        form.resetFields();
        setModalVisible(true);
    };

    const handleEdit = (tecnologia: TecnologiaProjeto) => {
        setEditingTecnologia(tecnologia);
        form.setFieldsValue(tecnologia);
        setModalVisible(true);
    };

    const handleDelete = async (tecnologiaId: number) => {
        try {
            const endpoint = API_ENDPOINTS.projetos.tecnologias.destroy(id, tecnologiaId);
            await apiClient.delete(endpoint);
            message.success('Tecnologia excluída com sucesso!');
            refetch();
        } catch (error: unknown) {
            const errorMessage =
                (error as { response?: { data?: { message?: string } } })?.response?.data?.message ||
                'Erro ao excluir tecnologia';
            message.error(errorMessage);
        }
    };

    const handleSubmit = (values: Record<string, unknown>) => {
        saveMutation.mutate(values);
    };

    const columns: ColumnsType<TecnologiaProjeto> = [
        {
            title: 'Nome',
            dataIndex: 'nome',
            key: 'nome',
            sorter: (a, b) => {
                const byNome = String(a.nome ?? '').localeCompare(String(b.nome ?? ''), 'pt');
                if (byNome !== 0) return byNome;
                const byVersao = String(a.versao ?? '').localeCompare(String(b.versao ?? ''), 'pt');
                if (byVersao !== 0) return byVersao;
                return String(a.tipo).localeCompare(String(b.tipo), 'pt');
            },
            render: (text: string, record: TecnologiaProjeto) => (
                <Space wrap size={4}>
                    <Code size={ICON_SIZE_MD} aria-hidden />
                    <span style={{ fontWeight: 600, color: '#2c3e50' }}>{text}</span>
                    {(record.pivot?.versao_usada || record.versao) && (
                        <Tag color="blue">v{record.pivot?.versao_usada || record.versao}</Tag>
                    )}
                    <Tag color={getProjetoTecnologiaTipoColor(record.tipo)}>{record.tipo}</Tag>
                    {record.pivot?.confirmado_manual ? (
                        <Tag color="success">Confirmada</Tag>
                    ) : record.pivot?.confianca ? (
                        <Tag color={record.pivot.confianca === 'alta' ? 'processing' : 'warning'}>
                            {record.pivot.confianca}
                        </Tag>
                    ) : null}
                </Space>
            )},
        {
            title: 'Categoria',
            dataIndex: 'categoria',
            key: 'categoria',
            sorter: (a, b) =>
                String(a.categoria ?? '').localeCompare(String(b.categoria ?? ''), 'pt')},
        {
            title: 'Nível de Proficiência',
            dataIndex: 'nivel_proficiencia',
            key: 'nivel_proficiencia',
            sorter: (a, b) => (a.nivel_proficiencia ?? 0) - (b.nivel_proficiencia ?? 0),
            render: (nivel: number) => (
                <Rate disabled value={nivel} count={5} style={{ fontSize: 14 }} />
            )},
        {
            title: 'Status',
            dataIndex: 'status',
            key: 'status',
            sorter: (a, b) => String(a.status ?? '').localeCompare(String(b.status ?? ''), 'pt'),
            render: (status: string) => (
                <Tag color={getProjetoTecnologiaStatusColor(status)}>
                    {status.charAt(0).toUpperCase() + status.slice(1).replace('_', ' ')}
                </Tag>
            )},
        {
            title: 'Atualizado em',
            dataIndex: 'updated_at',
            key: 'updated_at',
            sorter: (a, b) => dayjs(a.updated_at).valueOf() - dayjs(b.updated_at).valueOf(),
            render: (date: string) => formatDate(date, true)},
        {
            title: '',
            key: 'menu',
            width: 56,
            align: 'center',
            onCell: () => ({ onClick: (e: React.MouseEvent) => e.stopPropagation() }),
            render: (_: unknown, record: TecnologiaProjeto) => (
                <Button
                    type="text"
                    size="small"
                    icon={<MenuIcon size={ICON_SIZE_MD} aria-hidden />}
                    onClick={() => setOpcoesItem(record)}
                    aria-label="Opções"
                />
            )},
    ];

    return (
        <ProjetoLayout
            projetoId={id}
            pageTitle="Tecnologias do Projeto"
            pageIcon="code"
            titleSection="Tecnologias"
            breadcrumbItems={[{ title: 'PROJETO' }, { title: 'Projeto' }, { title: 'Tecnologias' }]}
            headerAction={
                <Space wrap size={8} align="center">
                    {metricasStack.pendentesConfirmacao > 0 && (
                        <PermissionGuard
                            permission="projetos.update"
                            module="projetos"
                            action="update"
                        >
                            <Button
                                icon={<CheckCircle2 size={ICON_SIZE_MD} aria-hidden />}
                                loading={confirmLoteMutation.isPending}
                                onClick={() => {
                                    confirmDialog({
                                        title: 'Confirmar tecnologias detectadas?',
                                        content: `Marca ${metricasStack.pendentesConfirmacao} tecnologia(s) com confiança baixa/média como confirmadas manualmente. O inventário do pack não sobrescreve esses vínculos.`,
                                        okText: 'Confirmar',
                                        cancelText: 'Cancelar',
                                        onOk: () => confirmLoteMutation.mutateAsync({}),
                                    });
                                }}
                                data-testid="projeto-tecnologias-confirmar-lote"
                            >
                                Confirmar detectadas ({metricasStack.pendentesConfirmacao})
                            </Button>
                        </PermissionGuard>
                    )}
                    <Tooltip title="Exportar stack visível (Excel, PDF, CSV ou JSON)">
                        <span style={{ display: 'inline-block' }}>
                            <LazyExportButton
                                data={tecnologias as unknown as Record<string, unknown>[]}
                                columns={[
                                    { key: 'nome', label: 'Nome' },
                                    { key: 'versao', label: 'Versão' },
                                    { key: 'tipo', label: 'Tipo' },
                                    { key: 'categoria', label: 'Categoria' },
                                ]}
                                filename={`tecnologias_projeto_${id}`}
                                iconOnly
                                title="Exportar tecnologias do projeto"
                                size="large"
                                exportMenuMode="modal"
                                className={btnHeaderStyles.btnHeaderIcon}
                            />
                        </span>
                    </Tooltip>
                </Space>
            }
        >
            
            <Alert
                type="info"
                showIcon
                style={{ marginBottom: 16 }}
                data-testid="projeto-tecnologias-vs-stack-alert"
                message={STACK_VS_TECNOLOGIAS_ALERT.message}
                description={
                    <span>
                        Esta tela é o inventário sincronizado do repositório. A stack do catálogo ERP
                        (stack_id) fica em{' '}
                        <Link href={projetosProjetoCanonical.softwareStack(id)}>Software → Stack</Link>
                        ; a sync não sobrescreve o stack_id.
                    </span>
                }
            />
            {tecnologias.length > 0 && (
                <>
                    <Alert
                        type="info"
                        showIcon
                        style={{ marginBottom: 16 }}
                        message="Maturidade, dependência e evolução"
                        description="Mantenha versão e estado atualizados. Tecnologias depreciadas ou em avaliação devem ter plano de substituição acordado com o time."
                    />
                    <Row gutter={[16, 16]} style={{ marginBottom: 16 }}>
                        <Col xs={12} sm={6}>
                            <Statistic title="Total no stack" value={metricasStack.total} />
                        </Col>
                        <Col xs={12} sm={6}>
                            <Statistic title="Ativas" value={metricasStack.ativos} />
                        </Col>
                        <Col xs={12} sm={6}>
                            <Statistic title="Depreciadas" value={metricasStack.deprecados} />
                        </Col>
                        <Col xs={12} sm={6}>
                            <Statistic title="Em avaliação" value={metricasStack.emAval} />
                        </Col>
                    </Row>
                </>
            )}
            {tecnologias.length === 0 ? (
                <EmptyState
                    title="Nenhuma tecnologia encontrada"
                    description="Comece adicionando tecnologias ou sincronize o Cursor Pack para preencher o inventário a partir do repositório. Isto não altera a stack do catálogo (stack_id)."
                    icon={<Code size={ICON_SIZE_MD} aria-hidden />}
                    action={
                        <Space wrap direction="vertical" align="center" size={12}>
                            <PermissionGuard
                                permission="projetos.tecnologias.create"
                                module="projetos"
                                action="create"
                            >
                                <Button
                                    type="primary"
                                    icon={<Plus size={ICON_SIZE_MD} aria-hidden />}
                                    onClick={handleCreate}
                                >
                                    Adicionar primeira tecnologia
                                </Button>
                            </PermissionGuard>
                            <ProjetoTipologicoSyncCtas projetoId={id} size="small" />
                        </Space>
                    }
                />
            ) : (
                <LazyDataTable
                    columns={columns}
                    data={tecnologias}
                    loading={isLoading}
                    onRefresh={refetch}
                    {...listingTableVirtualScrollProps(tecnologias.length)}
                    onRow={(record: unknown) => ({
                        onClick: () => setOpcoesItem(record as TecnologiaProjeto),
                        style: { cursor: 'pointer' }})}
                />
            )}
            

            <ModalOpcoesTecnologia
                open={opcoesItem !== null}
                onClose={() => setOpcoesItem(null)}
                item={opcoesItem}
                onVerDetalhes={(item) => {
                    setSelectedTecnologia(item);
                    setViewModalVisible(true);
                }}
                onEditar={(item) => handleEdit(item)}
                onExcluir={(item) => handleDelete(item.id)}
            />

            <Modal
                title={editingTecnologia ? 'Editar Tecnologia' : 'Adicionar Tecnologia'}
                open={modalVisible}
                onCancel={() => {
                    setModalVisible(false);
                    form.resetFields();
                }}
                onOk={() => form.submit()}
                width={modalLayout.width ?? 700}
                centered={modalLayout.centered ?? true}
                className={modalLayout.className}

                styles={modalLayout.styles ?? {}}
                destroyOnHidden
                keyboard
                focusTriggerAfterClose
                data-testid="projeto-tecnologias-form-modal"
            >
                <Form form={form} onFinish={handleSubmit} layout="vertical">
                    <Form.Item
                        name="nome"
                        label="Nome"
                        rules={[{ required: true, message: 'Nome é obrigatório' }]}
                    >
                        <Input placeholder="Ex: React, Node.js, PostgreSQL" />
                    </Form.Item>

                    <Row gutter={16}>
                        <Col xs={24} sm={12}>
                            <Form.Item name="versao" label="Versão">
                                <Input placeholder="Ex: 18.2.0" />
                            </Form.Item>
                        </Col>
                        <Col xs={24} sm={12}>
                            <Form.Item
                                name="tipo"
                                label="Tipo"
                                rules={[{ required: true, message: 'Tipo é obrigatório' }]}
                            >
                                <Select placeholder="Selecione o tipo">
                                    <Select.Option value="linguagem">Linguagem</Select.Option>
                                    <Select.Option value="framework">Framework</Select.Option>
                                    <Select.Option value="biblioteca">Biblioteca</Select.Option>
                                    <Select.Option value="ferramenta">Ferramenta</Select.Option>
                                    <Select.Option value="banco_dados">Banco de Dados</Select.Option>
                                    <Select.Option value="servico">Serviço</Select.Option>
                                </Select>
                            </Form.Item>
                        </Col>
                    </Row>

                    <Form.Item
                        name="categoria"
                        label="Categoria"
                        rules={[{ required: true, message: 'Categoria é obrigatória' }]}
                    >
                        <Input placeholder="Ex: Frontend, Backend, Database" />
                    </Form.Item>

                    <Form.Item name="descricao" label="Descrição">
                        <FormTextarea
                            name="descricao"
                            label="Descrição"
                            rows={3}
                            placeholder="Descrição da tecnologia..."
                        />
                    </Form.Item>

                    <Form.Item name="documentacao_url" label="URL da Documentação">
                        <Input placeholder="https://..." type="url" />
                    </Form.Item>

                    <Form.Item
                        name="nivel_proficiencia"
                        label="Nível de Proficiência"
                        rules={[{ required: true, message: 'Nível de proficiência é obrigatório' }]}
                    >
                        <Rate count={5} />
                    </Form.Item>

                    <Form.Item
                        name="status"
                        label="Status"
                        rules={[{ required: true, message: 'Status é obrigatório' }]}
                    >
                        <Select placeholder="Selecione o status">
                            <Select.Option value="ativo">Ativo</Select.Option>
                            <Select.Option value="deprecado">Deprecado</Select.Option>
                            <Select.Option value="em_avaliacao">Em Avaliação</Select.Option>
                        </Select>
                    </Form.Item>
                </Form>
            </Modal>

            <Modal
                title={selectedTecnologia?.nome}
                open={viewModalVisible}
                onCancel={() => setViewModalVisible(false)}
                footer={[
                    selectedTecnologia?.documentacao_url && (
                        <Button
                            key="docs"
                            type="primary"
                            href={selectedTecnologia.documentacao_url}
                            target="_blank"
                        >
                            Ver Documentação
                        </Button>
                    ),
                    <Button key="close" onClick={() => setViewModalVisible(false)}>
                        Fechar
                    </Button>,
                ]}
                width={modalLayout.width ?? 700}
                centered={modalLayout.centered ?? true}
                className={modalLayout.className}

                styles={modalLayout.styles ?? {}}
                destroyOnHidden
                keyboard
                focusTriggerAfterClose
                data-testid="projeto-tecnologias-detalhes-modal"
            >
                {selectedTecnologia && (
                    <Descriptions bordered column={1}>
                        <Descriptions.Item label="Nome">{selectedTecnologia.nome}</Descriptions.Item>
                        {selectedTecnologia.versao && (
                            <Descriptions.Item label="Versão">
                                <Tag color="blue">v{selectedTecnologia.versao}</Tag>
                            </Descriptions.Item>
                        )}
                        <Descriptions.Item label="Tipo">
                            <Tag color={getProjetoTecnologiaTipoColor(selectedTecnologia.tipo)}>
                                {selectedTecnologia.tipo}
                            </Tag>
                        </Descriptions.Item>
                        <Descriptions.Item label="Categoria">
                            {selectedTecnologia.categoria}
                        </Descriptions.Item>
                        {selectedTecnologia.descricao && (
                            <Descriptions.Item label="Descrição">
                                {selectedTecnologia.descricao}
                            </Descriptions.Item>
                        )}
                        {selectedTecnologia.documentacao_url && (
                            <Descriptions.Item label="Documentação">
                                <a
                                    href={selectedTecnologia.documentacao_url}
                                    target="_blank"
                                    rel="noopener noreferrer"
                                >
                                    {selectedTecnologia.documentacao_url}
                                </a>
                            </Descriptions.Item>
                        )}
                        <Descriptions.Item label="Nível de Proficiência">
                            <Rate
                                disabled
                                value={selectedTecnologia.nivel_proficiencia}
                                count={5}
                            />
                        </Descriptions.Item>
                        <Descriptions.Item label="Status">
                            <Tag color={getProjetoTecnologiaStatusColor(selectedTecnologia.status)}>
                                {selectedTecnologia.status.charAt(0).toUpperCase() +
                                    selectedTecnologia.status.slice(1).replace('_', ' ')}
                            </Tag>
                        </Descriptions.Item>
                        <Descriptions.Item label="Adicionado em">
                            {formatDate(selectedTecnologia.created_at, true)}
                        </Descriptions.Item>
                    </Descriptions>
                )}
            </Modal>

            <PermissionGuard permission="projetos.tecnologias.create" module="projetos" action="create">
                <ListPageCreateFloatButton
                data-testid="projeto-tecnologias-fab-novo"
                tooltip={{ title: 'Adicionar tecnologia' }}
                    onClick={handleCreate}
/>
            </PermissionGuard>
        </ProjetoLayout>
    );
}
