'use client';

/**
 * Checklist tipológico de onboarding do programa Produto de software.
 *
 * @route /projetos/[id]/produto/onboarding
 */

import React, { useMemo } from 'react';
import { useParams } from 'next/navigation';
import { Alert, Col, Row } from 'antd';
import ProjetoLayout from '@/components/layouts/ProjetoLayout';
import { useQueryCache } from '@/hooks/useQueryCache';
import { API_ENDPOINTS } from '@/lib/api/endpoints';
import { queryKeys } from '@/lib/cache/queryKeys';
import type { Projeto } from '@/types';
import { ProdutoSoftwareTipoFetchErrorAlert } from '@/features/projetos/components/ProdutoSoftwareTipoFetchErrorAlert';
import { isProdutoSoftwareTipoDisabledError } from '@/features/projetos/utils/produtoSoftwareTipoKillSwitch';
import {
    normalizarProjetoResponse,
    type ProjetoShowApiResponse,
} from '@/features/projetos/utils/normalizeProjetoShowResponse';
import type { ProdutoReleaseResumo } from '@/features/projetos/projeto-produto-releases/types';
import {
    projetoProdutoMetaQueryKey,
    projetoProdutoReleasesQueryKey,
} from '@/features/projetos/projeto-produto-releases/utils/produtoQueryKeys';
import { buildProdutoOnboardingChecklist } from '@/features/projetos/projeto-produto-onboarding/buildProdutoOnboardingChecklist';
import { useProjetoWriteGates } from '@/features/projetos/hooks/useProjetoWriteGates';
import { ProdutoOnboardingChecklistCard } from './ProdutoOnboardingChecklistCard';

type ProdutoApiResponse = {
    data: {
        visao_produto?: string | null;
        ciclo_vida?: string;
        subprojetos_count?: number;
    };
};

type ReleasesApiResponse = {
    data: ProdutoReleaseResumo[];
    meta?: { total: number };
};

type ProjetoComEquipa = Projeto & {
    equipe_id?: number | null;
    equipe?: { id?: number; nome?: string } | null;
    responsavel_id?: number | null;
};

export function ProjetoProdutoOnboardingScreen() {
    const params = useParams();
    const projetoId = params?.id as string;
    const { canCriar } = useProjetoWriteGates();

    const {
        data: projetoRaw,
        isLoading: loadingProjeto,
        isError: errorProjeto,
        error: projetoError,
        refetch: refetchProjeto,
    } = useQueryCache<ProjetoShowApiResponse>({
        queryKey: queryKeys.projetos.detail(projetoId),
        endpoint: API_ENDPOINTS.projetos.show(projetoId),
        enabled: Boolean(projetoId),
        staleTime: 2 * 60 * 1000,
    });

    const {
        data: produtoRaw,
        isLoading: loadingProduto,
        isError: errorProduto,
        error: produtoError,
        refetch: refetchProduto,
    } = useQueryCache<ProdutoApiResponse>({
        queryKey: projetoProdutoMetaQueryKey(projetoId),
        endpoint: API_ENDPOINTS.projetos.produto.show(projetoId),
        enabled: Boolean(projetoId),
        staleTime: 2 * 60 * 1000,
    });

    const {
        data: releasesRaw,
        isLoading: loadingReleases,
        isError: errorReleases,
        error: releasesError,
        refetch: refetchReleases,
    } = useQueryCache<ReleasesApiResponse>({
        queryKey: projetoProdutoReleasesQueryKey(projetoId),
        endpoint: API_ENDPOINTS.projetos.releases.index(projetoId),
        enabled: Boolean(projetoId),
        staleTime: 2 * 60 * 1000,
    });

    const projeto = useMemo(
        () => normalizarProjetoResponse(projetoRaw) as ProjetoComEquipa | null,
        [projetoRaw],
    );
    const loading = loadingProjeto || loadingProduto || loadingReleases;

    const fetchError =
        (errorProduto && produtoError) ||
        (errorProjeto && projetoError) ||
        (errorReleases && releasesError) ||
        null;

    const tipoDisabled = isProdutoSoftwareTipoDisabledError(produtoError);
    const hasTipoAddon =
        !tipoDisabled &&
        Boolean(produtoRaw?.data) &&
        (projeto?.categoria_projeto?.codigo === 'produto_software' || Boolean(produtoRaw?.data));

    const hasEquipa = Boolean(
        projeto?.responsavel ||
            projeto?.responsavel_id ||
            projeto?.equipe_id ||
            projeto?.equipe?.id,
    );

    const superficiesCount =
        produtoRaw?.data?.subprojetos_count ?? projeto?.subprojetos_count ?? 0;
    const releasesCount = releasesRaw?.meta?.total ?? releasesRaw?.data?.length ?? 0;
    const hasConfiguracao = Boolean(
        (produtoRaw?.data?.ciclo_vida && produtoRaw.data.ciclo_vida !== 'discovery') ||
            (typeof produtoRaw?.data?.visao_produto === 'string' &&
                produtoRaw.data.visao_produto.trim() !== ''),
    );

    const checklist = useMemo(
        () =>
            buildProdutoOnboardingChecklist({
                projetoId,
                hasTipoAddon,
                hasEquipa,
                superficiesCount,
                releasesCount,
                hasConfiguracao,
                canCriarSuperficie: canCriar,
            }),
        [
            projetoId,
            hasTipoAddon,
            hasEquipa,
            superficiesCount,
            releasesCount,
            hasConfiguracao,
            canCriar,
        ],
    );

    const handleRetry = () => {
        void refetchProjeto();
        void refetchProduto();
        void refetchReleases();
    };

    return (
        <ProjetoLayout
            projetoId={projetoId}
            pageTitle="Onboarding do produto"
            titleSection="Onboarding"
        >
            {fetchError ? (
                <div style={{ marginBottom: 16 }}>
                    <ProdutoSoftwareTipoFetchErrorAlert
                        error={fetchError}
                        fallbackMessage="Não foi possível carregar o progresso de onboarding"
                        onRetry={handleRetry}
                    />
                </div>
            ) : null}

            <Alert
                type="info"
                showIcon
                style={{ marginBottom: 16 }}
                message="Ative o programa em poucos passos"
                description="Confirme tipo/addon e equipe, adicione a primeira superfície e a primeira release. Pode pular para superfícies ou dashboard quando quiser."
            />

            <Row gutter={[16, 16]}>
                <Col xs={24} lg={16} xl={14}>
                    <ProdutoOnboardingChecklistCard
                        projetoId={projetoId}
                        checklist={checklist}
                        loading={loading && !fetchError}
                        canCriarSuperficie={canCriar}
                    />
                </Col>
            </Row>
        </ProjetoLayout>
    );
}
