'use client';

/**
 * CTA para aplicar template de projecto existente (TASK-PWP-033).
 * Resolve "Site institucional" na listagem global; AuthZ `projetos.editar`.
 */

import { LayoutTemplate } from 'lucide-react';
import React, { useCallback, useMemo } from 'react';
import { Button, Tooltip } from 'antd';
import type { ButtonProps } from 'antd';
import { confirmDialog } from '@/lib/feedback/confirmDialog';
import { PermissionGuard } from '@/components/permissions';
import { useQueryCache } from '@/hooks/useQueryCache';
import { API_ENDPOINTS } from '@/lib/api/endpoints';
import { ICON_SIZE_MD } from '@/components/icons';
import { useProjetoWriteGates } from '@/features/projetos/hooks/useProjetoWriteGates';

import type { TemplateProjeto } from './types';
import { PROJETO_TEMPLATE_SITE_INSTITUCIONAL_NOME } from './projetosTemplateConstants';
import { resolveSiteInstitucionalTemplate } from './resolveSiteInstitucionalTemplate';
import { useAplicarProjetoTemplate } from './useAplicarProjetoTemplate';
import { queryKeys } from '@/lib/cache/queryKeys';

export type AplicarProjetoTemplateActionProps = {
    projetoId: string | number;
    /** Template explícito; omitido = resolver "Site institucional". */
    template?: TemplateProjeto | null;
    incluirPaginas?: boolean;
    buttonProps?: ButtonProps;
    /** Rótulo do botão; default orientado ao seed website. */
    label?: string;
    /** Ocultar quando o template alvo não existir no tenant. */
    hideWhenUnavailable?: boolean;
    'data-testid'?: string;
};

export function AplicarProjetoTemplateAction({
    projetoId,
    template: templateProp,
    incluirPaginas = true,
    buttonProps,
    label = `Aplicar template "${PROJETO_TEMPLATE_SITE_INSTITUCIONAL_NOME}"`,
    hideWhenUnavailable = true,
    'data-testid': dataTestId = 'projetos-aplicar-template-site-institucional',
}: AplicarProjetoTemplateActionProps) {
    const { canEditar, permsLoading, tooltipSemPermissao } = useProjetoWriteGates();
    const { aplicarTemplate, isApplying } = useAplicarProjetoTemplate(projetoId);

    const { data: templatesData, isLoading: loadingTemplates } = useQueryCache<{ data: TemplateProjeto[] }>({
        queryKey: queryKeys.projetos.templatesList(),
        endpoint: API_ENDPOINTS.projetos.templates.index,
        staleTime: 5 * 60 * 1000,
        enabled: templateProp == null,
    });

    const resolvedTemplate = useMemo(
        () => templateProp ?? resolveSiteInstitucionalTemplate(templatesData?.data),
        [templateProp, templatesData?.data],
    );

    const handleApply = useCallback(() => {
        if (!resolvedTemplate) return;

        confirmDialog({
            title: 'Aplicar template ao projeto?',
            content: incluirPaginas
                ? `O template "${resolvedTemplate.nome}" vai preencher o briefing e criar as páginas típicas que ainda não existirem. Páginas já cadastradas não serão duplicadas.`
                : `O template "${resolvedTemplate.nome}" vai preencher o briefing do projeto.`,
            okText: 'Aplicar template',
            cancelText: 'Cancelar',
            onOk: async () => {
                await aplicarTemplate({
                    template_id: resolvedTemplate.id,
                    projeto_id: Number(projetoId),
                    incluir_paginas: incluirPaginas,
                });
            },
        });
    }, [aplicarTemplate, incluirPaginas, projetoId, resolvedTemplate]);

    if (hideWhenUnavailable && !loadingTemplates && !resolvedTemplate) {
        return null;
    }

    const loading = loadingTemplates || permsLoading;
    const disabled = loading || isApplying || !resolvedTemplate || !canEditar;

    const button = (
        <Button
            type="default"
            icon={<LayoutTemplate size={ICON_SIZE_MD} aria-hidden />}
            loading={isApplying}
            disabled={disabled}
            onClick={handleApply}
            data-testid={dataTestId}
            {...buttonProps}
        >
            {label}
        </Button>
    );

    return (
        <PermissionGuard permission="projetos.editar" module="projetos" action="update">
            {!canEditar && !permsLoading ? (
                <Tooltip title={tooltipSemPermissao('aplicar templates neste projeto')}>
                    <span style={{ display: 'inline-block' }}>{button}</span>
                </Tooltip>
            ) : (
                button
            )}
        </PermissionGuard>
    );
}
