'use client';

/**
 * Card hub — último deploy e URL preview (TASK-PWP-051 / WP-OP-018).
 */

import { ExternalLink, Globe, Rocket } from 'lucide-react';
import { Button, Divider, Empty, Space, Tag, Typography } from 'antd';
import Link from 'next/link';

import { ICON_SIZE_MD } from '@/components/icons';
import ContentCard from '@/components/layouts/ContentCard';
import { formatDate } from '@/lib/utils/export';
import { projetosProjetoCanonical } from '@/lib/routes/projetosProjetoCanonical';
import scStyles from '@/features/projetos/sistema-customizado-prontidao/ScProntidaoHubBlock.module.scss';

import {
    deployStatusLabel,
    deployStatusTagColor,
} from './pickLatestProjetoDeploy';
import type { UseWebsiteDeployPreviewHubResult } from './useWebsiteDeployPreviewHub';
import { isAplicacaoReactTipologia } from '@/features/projetos/lib/resolveAplicacaoReactTipologiaCopy';
import { useProjetoLayoutContextOptional } from '@/components/layouts/ProjetoLayout/ProjetoLayoutContext';

const { Text, Link: TypographyLink } = Typography;

export type WebsiteDeployPreviewCardProps = {
    projetoId: string;
    state: UseWebsiteDeployPreviewHubResult;
};

/**
 * Exibe último deploy registrado ou empty honesto; link preview quando `ftp_host` existe.
 */
export function WebsiteDeployPreviewCard({ projetoId, state }: WebsiteDeployPreviewCardProps) {
    const {
        latestDeploy,
        previewUrl,
        isLoading,
        deployError,
        infraError,
    } = state;
    const layoutCtx = useProjetoLayoutContextOptional();
    const isAplicacaoReact = isAplicacaoReactTipologia(
        layoutCtx?.projeto?.categoria_projeto?.codigo,
    );
    const subtitlePublicacao = isAplicacaoReact
        ? 'Status de publicação e link da aplicação quando configurado em Hospedagem'
        : 'Status de publicação e link do site quando configurado em Hospedagem';

    const hospedagemHref = `/projetos/${projetoId}/software/hospedagem`;
    const pipelinesHref = projetosProjetoCanonical.integracoesPipelines(projetoId);

    const deployWhen = latestDeploy
        ? formatDate(
              latestDeploy.concluido_em ??
                  latestDeploy.iniciado_em ??
                  latestDeploy.planejado_para,
              true,
          )
        : null;

    return (
        <div data-testid="website-deploy-preview-card">
            <ContentCard
                title="Deploy e preview"
                icon={<Rocket size={ICON_SIZE_MD} aria-hidden />}
                loading={isLoading}
            >
                <Text type="secondary" className={scStyles.cardSubtitle}>
                    {subtitlePublicacao}
                </Text>

                <Space direction="vertical" size={8} style={{ width: '100%' }}>
                    <Text strong style={{ fontSize: 13 }}>
                        Último deploy
                    </Text>

                    {deployError ? (
                        <Text type="secondary" data-testid="website-deploy-error">
                            Não foi possível carregar deploys deste projeto. Consulte Pipelines ou
                            registre deploys na API quando disponível.
                        </Text>
                    ) : latestDeploy ? (
                        <Space direction="vertical" size={4} style={{ width: '100%' }}>
                            <Space wrap size={8} align="center">
                                <Tag color={deployStatusTagColor(latestDeploy.status)}>
                                    {deployStatusLabel(latestDeploy.status)}
                                </Tag>
                                {latestDeploy.ambiente ? (
                                    <Text type="secondary" style={{ fontSize: 12 }}>
                                        {latestDeploy.ambiente}
                                    </Text>
                                ) : null}
                            </Space>
                            <Text data-testid="website-deploy-title">
                                {latestDeploy.titulo?.trim() ||
                                    latestDeploy.codigo?.trim() ||
                                    `Deploy #${latestDeploy.id}`}
                            </Text>
                            {deployWhen ? (
                                <Text type="secondary" style={{ fontSize: 12 }}>
                                    {deployWhen}
                                </Text>
                            ) : null}
                            {latestDeploy.branch ? (
                                <Text type="secondary" style={{ fontSize: 12 }}>
                                    Branch: {latestDeploy.branch}
                                </Text>
                            ) : null}
                        </Space>
                    ) : (
                        <Empty
                            image={Empty.PRESENTED_IMAGE_SIMPLE}
                            description="Nenhum deploy registrado para este projeto."
                            data-testid="website-deploy-empty"
                        >
                            <Link href={pipelinesHref}>
                                <Button type="link" size="small" style={{ padding: 0 }}>
                                    Ver pipelines CI/CD
                                </Button>
                            </Link>
                        </Empty>
                    )}
                </Space>

                <Divider style={{ margin: '16px 0' }} />

                <Space direction="vertical" size={8} style={{ width: '100%' }}>
                    <Space wrap size={6} align="center">
                        <Globe size={16} aria-hidden />
                        <Text strong style={{ fontSize: 13 }}>
                            URL preview
                        </Text>
                    </Space>

                    {infraError ? (
                        <Text type="secondary" data-testid="website-preview-error">
                            Não foi possível ler Hospedagem. Abra a seção Hospedagem para confirmar o
                            host de publicação.
                        </Text>
                    ) : previewUrl ? (
                        <TypographyLink
                            href={previewUrl}
                            target="_blank"
                            rel="noopener noreferrer"
                            data-testid="website-preview-link"
                        >
                            <Space size={4}>
                                {previewUrl}
                                <ExternalLink size={14} aria-hidden />
                            </Space>
                        </TypographyLink>
                    ) : (
                        <Empty
                            image={Empty.PRESENTED_IMAGE_SIMPLE}
                            description="Sem URL de preview configurada. Defina o host em Hospedagem (hospedagem externa) ou use o painel do fornecedor até integração nativa."
                            data-testid="website-preview-empty"
                        >
                            <Link href={hospedagemHref}>
                                <Button type="link" size="small" style={{ padding: 0 }}>
                                    Abrir Hospedagem
                                </Button>
                            </Link>
                        </Empty>
                    )}
                </Space>
            </ContentCard>
        </div>
    );
}
