'use client';

/**
 * Matriz de sprints coordenadas por superfície.
 *
 * @route /projetos/[id]/produto/sprints
 */

import { CirclePlay, Rocket } from 'lucide-react';
import Link from 'next/link';
import React, { useMemo } from 'react';
import { useParams } from 'next/navigation';
import { Alert, Button, Progress, Table, Tag, Typography } from 'antd';
import ProjetoLayout from '@/components/layouts/ProjetoLayout';
import ContentCard from '@/components/layouts/ContentCard';
import { useQueryCache } from '@/hooks/useQueryCache';
import { API_ENDPOINTS } from '@/lib/api/endpoints';
import { queryKeys } from '@/lib/cache/queryKeys';

type SprintRow = {
    id: number;
    nome: string;
    status?: string;
    data_inicio?: string;
    data_fim?: string;
    tarefas_total?: number;
    tarefas_concluidas?: number;
};

type MatrizRow = {
    projeto_id: number;
    nome: string;
    codigo_superficie?: string | null;
    sprint_ativa?: SprintRow | null;
    sprints: SprintRow[];
};

type SprintsApiResponse = {
    data: {
        matriz: MatrizRow[];
        meta: { superficies_visiveis: number; superficies_total: number; sprints_ativas: number };
    };
};

export function ProjetoProdutoSprintsScreen() {
    const params = useParams();
    const projetoId = params?.id as string;

    const { data, isLoading, isError, refetch } = useQueryCache<SprintsApiResponse>({
        queryKey: queryKeys.projetos.portfolioSprintsLegacy(projetoId),
        endpoint: API_ENDPOINTS.projetos.portfolioSprints(projetoId),
        enabled: Boolean(projetoId),
    });

    const matriz = data?.data?.matriz ?? [];
    const meta = data?.data?.meta;

    const columns = useMemo(
        () => [
            {
                title: 'Superfície',
                dataIndex: 'codigo_superficie',
                key: 'codigo_superficie',
                width: 110,
                render: (c: string | null) => (c ? <Tag>{c}</Tag> : '—'),
            },
            {
                title: 'Subprojeto',
                dataIndex: 'nome',
                key: 'nome',
                render: (nome: string, row: MatrizRow) => (
                    <Link href={`/projetos/${row.projeto_id}`}>{nome}</Link>
                ),
            },
            {
                title: 'Sprint ativa',
                key: 'sprint_ativa',
                render: (_: unknown, row: MatrizRow) =>
                    row.sprint_ativa ? (
                        <Link href={`/projetos/${row.projeto_id}/planejamento/sprints`}>
                            {row.sprint_ativa.nome}
                        </Link>
                    ) : (
                        <Typography.Text type="secondary">—</Typography.Text>
                    ),
            },
            {
                title: 'Período',
                key: 'periodo',
                width: 200,
                render: (_: unknown, row: MatrizRow) => {
                    const s = row.sprint_ativa;
                    if (!s?.data_inicio) return '—';
                    return `${s.data_inicio} → ${s.data_fim ?? '?'}`;
                },
            },
            {
                title: 'Tarefas (sprint ativa)',
                key: 'tarefas',
                width: 160,
                render: (_: unknown, row: MatrizRow) => {
                    const s = row.sprint_ativa;
                    if (!s) return '—';
                    const total = s.tarefas_total ?? 0;
                    const done = s.tarefas_concluidas ?? 0;
                    const pct = total > 0 ? Math.round((done / total) * 100) : 0;
                    return <Progress percent={pct} size="small" format={() => `${done}/${total}`} />;
                },
            },
            {
                title: 'Total sprints',
                dataIndex: 'sprints',
                key: 'count',
                width: 100,
                render: (sprints: SprintRow[]) => sprints.length,
            },
        ],
        [],
    );

    return (
        <ProjetoLayout
            projetoId={projetoId}
            pageTitle="Sprints coordenadas"
            titleSection="Sprints coordenadas"
            headerAction={
                <Link href={`/projetos/${projetoId}/produto/sprints/calendario`}>
                    <Button icon={<CirclePlay size={16} aria-hidden />}>Calendário</Button>
                </Link>
            }
        >
            {meta && meta.superficies_visiveis < meta.superficies_total ? (
                <Alert
                    type="warning"
                    showIcon
                    style={{ marginBottom: 16 }}
                    message="Visão parcial"
                    description={`${meta.superficies_visiveis} de ${meta.superficies_total} superfícies visíveis.`}
                />
            ) : null}

            {isError ? (
                <Alert
                    type="error"
                    showIcon
                    message="Erro ao carregar sprints"
                    action={<Button onClick={() => void refetch()}>Tentar novamente</Button>}
                />
            ) : (
                <ContentCard title="Matriz por superfície" icon={<Rocket size={18} aria-hidden />}>
                    <Table<MatrizRow>
                        rowKey="projeto_id"
                        loading={isLoading}
                        columns={columns}
                        dataSource={matriz}
                        pagination={false}
                        locale={{
                            emptyText: 'Sem superfícies — configure subprojetos no onboarding.',
                        }}
                    />
                </ContentCard>
            )}
        </ProjetoLayout>
    );
}
