'use client';

/**
 * Painel de subprojetos do programa (`GET …/projetos/{id}/subprojetos`) — ADR-0040.
 */

import { FolderTree, Plus } from 'lucide-react';
import Link from 'next/link';
import { useRouter } from 'next/navigation';
import React, { useMemo } from 'react';
import { Alert, Button, Empty, Table, Tag, Tooltip, Typography } from 'antd';
import { useQueryCache } from '@/hooks/useQueryCache';
import { API_ENDPOINTS } from '@/lib/api/endpoints';
import ContentCard from '@/components/layouts/ContentCard';
import type { Projeto } from '@/types/projeto';
import { useProjetoWriteGates } from '@/features/projetos/hooks/useProjetoWriteGates';
import { projetoDetalhesStatusColor } from '../projeto-detalhes/projetoDetalhesUtils';

const { Text } = Typography;

export type ProjetoSubprojetoRow = Projeto & {
    gitlab_repository_url?: string | null;
    gitlab_default_branch?: string | null;
};

type SubprojetosApiResponse = {
    data: ProjetoSubprojetoRow[];
    meta: { total: number };
};

export function projetoSubprojetosQueryKey(projetoId: string) {
    return ['projetos', 'subprojetos', projetoId] as const;
}

type ProjetoSubprojetosPanelProps = {
    projetoId: string;
    programaNome?: string;
    readOnly?: boolean;
};

export function ProjetoSubprojetosPanel({
    projetoId,
    programaNome,
    readOnly = false,
}: ProjetoSubprojetosPanelProps) {
    const router = useRouter();
    const { canCriar, permsLoading, tooltipSemPermissao } = useProjetoWriteGates();
    const podeAdicionar = !readOnly && (permsLoading || canCriar);
    const queryKey = projetoSubprojetosQueryKey(projetoId);

    const { data, isLoading, isError, refetch } = useQueryCache<SubprojetosApiResponse>({
        queryKey,
        endpoint: API_ENDPOINTS.projetos.subprojetos.index(projetoId),
        enabled: Boolean(projetoId),
        staleTime: 2 * 60 * 1000,
    });

    const subprojetos = useMemo(() => data?.data ?? [], [data?.data]);

    const columns = useMemo(
        () => [
            {
                title: 'Código',
                dataIndex: 'codigo_superficie',
                key: 'codigo_superficie',
                width: 120,
                render: (codigo: string | null) =>
                    codigo ? <Tag>{codigo}</Tag> : <Text type="secondary">—</Text>,
            },
            {
                title: 'Nome',
                dataIndex: 'nome',
                key: 'nome',
                render: (nome: string, row: ProjetoSubprojetoRow) => (
                    <Link href={`/projetos/${row.id}`}>{nome}</Link>
                ),
            },
            {
                title: 'Tipo',
                key: 'tipo',
                render: (_: unknown, row: ProjetoSubprojetoRow) =>
                    row.categoria_projeto?.nome ?? <Text type="secondary">—</Text>,
            },
            {
                title: 'Status',
                dataIndex: 'status',
                key: 'status',
                width: 140,
                render: (status: string | undefined) =>
                    status ? <Tag color={projetoDetalhesStatusColor(status)}>{status}</Tag> : '—',
            },
            {
                title: 'Repositório',
                key: 'repo',
                ellipsis: true,
                render: (_: unknown, row: ProjetoSubprojetoRow) => {
                    const url = row.gitlab_repository_url;
                    if (!url) {
                        return <Text type="secondary">Não configurado</Text>;
                    }
                    return (
                        <a href={url} target="_blank" rel="noopener noreferrer">
                            {url.replace(/^https?:\/\//, '')}
                        </a>
                    );
                },
            },
        ],
        [],
    );

    const abrirWizardSubprojeto = () => {
        router.push(`/projetos/create?projeto_pai_id=${encodeURIComponent(projetoId)}`);
    };

    const addButton =
        readOnly ? null : podeAdicionar ? (
            <Button
                type="primary"
                icon={<Plus size={16} aria-hidden />}
                onClick={abrirWizardSubprojeto}
                loading={permsLoading}
                data-testid="projeto-subprojetos-adicionar"
            >
                Adicionar subprojeto
            </Button>
        ) : (
            <Tooltip title={tooltipSemPermissao('criar subprojetos')}>
                <span>
                    <Button
                        type="primary"
                        icon={<Plus size={16} aria-hidden />}
                        disabled
                        data-testid="projeto-subprojetos-adicionar-disabled"
                    >
                        Adicionar subprojeto
                    </Button>
                </span>
            </Tooltip>
        );

    return (
        <ContentCard
            title="Subprojetos"
            icon={<FolderTree size={18} aria-hidden />}
            extra={addButton}
        >
            {programaNome ? (
                <Typography.Paragraph type="secondary" style={{ marginBottom: 16 }}>
                    Subprojetos vinculados ao programa <strong>{programaNome}</strong>. Cada um é um
                    projeto completo (tipo, sprint, backlog, GitLab). Adicione quantos precisar, quando
                    precisar.
                </Typography.Paragraph>
            ) : null}

            {isError ? (
                <Alert
                    type="error"
                    showIcon
                    message="Não foi possível carregar subprojetos"
                    action={
                        <Button size="small" onClick={() => void refetch()}>
                            Tentar novamente
                        </Button>
                    }
                />
            ) : (
                <Table<ProjetoSubprojetoRow>
                    rowKey="id"
                    loading={isLoading}
                    columns={columns}
                    dataSource={subprojetos}
                    pagination={false}
                    locale={{
                        emptyText: (
                            <Empty
                                image={Empty.PRESENTED_IMAGE_SIMPLE}
                                description={
                                    podeAdicionar
                                        ? 'Nenhum subprojeto vinculado a este programa.'
                                        : 'Nenhum subprojeto vinculado. Quem tiver permissão de criar projetos pode adicionar o primeiro.'
                                }
                            >
                                {podeAdicionar ? (
                                    <Button
                                        type="primary"
                                        onClick={abrirWizardSubprojeto}
                                        data-testid="projeto-subprojetos-empty-cta"
                                    >
                                        Adicionar primeiro subprojeto
                                    </Button>
                                ) : null}
                            </Empty>
                        ),
                    }}
                />
            )}
        </ContentCard>
    );
}
