'use client';

/**
 * Card hub — Performance / Core Web Vitals (TASK-PWP-062 / APR-008).
 * Estados honestos alinhados a SEO/Performance "Em breve" e opt-in PSI.
 * Em `pilot_psi_off` (Aplicação React) não sugere automação nem opt-in ativo.
 */

import { Activity, ExternalLink } from 'lucide-react';
import { Alert, Button, 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 type { UseWebsiteHubPerformanceResult } from './useWebsiteHubPerformance';

const { Text } = Typography;

export type WebsiteHubPerformanceCardProps = {
    projetoId: string;
    state: UseWebsiteHubPerformanceResult;
};

function formatScore(score: number | null): string {
    if (score == null) return '—';
    return Number.isInteger(score) ? String(score) : score.toFixed(0);
}

/**
 * Exibe opt-in, última medição PSI ou empty/CTA — sem prometer Lighthouse CI.
 * Piloto APR-008: estado `pilot_psi_off` sem CTAs de análise/automação.
 */
export function WebsiteHubPerformanceCard({
    projetoId,
    state,
}: WebsiteHubPerformanceCardProps) {
    const { kind, measurement, honestyNote, isLoading, refetch } = state;
    const partilhasHref = projetosProjetoCanonical.integracoesPartilhasDados(projetoId);
    const utilPsiHref = '/utilitarios/pagespeed';
    const performanceMenuHref = `/projetos/${projetoId}/desenvolvimento/performance`;
    const isPilotPsiOff = kind === 'pilot_psi_off';

    return (
        <div data-testid="website-hub-performance-card">
            <ContentCard
                title="Performance / Core Web Vitals"
                icon={<Activity size={ICON_SIZE_MD} aria-hidden />}
                loading={isLoading}
                headerActions={
                    !isLoading ? (
                        <Link href={performanceMenuHref}>
                            <Button type="link" size="small" data-testid="website-hub-performance-menu">
                                Menu Performance
                            </Button>
                        </Link>
                    ) : undefined
                }
            >
                <Text type="secondary" className={scStyles.cardSubtitle}>
                    {honestyNote}
                </Text>

                {isPilotPsiOff ? (
                    <Empty
                        image={Empty.PRESENTED_IMAGE_SIMPLE}
                        description="PageSpeed Insights OFF no piloto Aplicação React — sem automação ativa."
                        data-testid="website-hub-performance-pilot-psi-off"
                    >
                        <Tag color="default">PSI desligado</Tag>
                    </Empty>
                ) : null}

                {kind === 'opt_in_off' || kind === 'opt_in_unknown' ? (
                    <Empty
                        image={Empty.PRESENTED_IMAGE_SIMPLE}
                        description={
                            kind === 'opt_in_off'
                                ? 'Compartilha PageSpeed Insights desativada neste projeto.'
                                : 'Não foi possível confirmar o opt-in PageSpeed deste projeto.'
                        }
                        data-testid="website-hub-performance-empty-opt-in"
                    >
                        <Space direction="vertical" size={4} align="center">
                            <Link href={partilhasHref}>
                                <Button
                                    type="primary"
                                    size="small"
                                    data-testid="website-hub-performance-cta-partilhas"
                                >
                                    Abrir Integrações → Partilhas / PSI
                                </Button>
                            </Link>
                            {kind === 'opt_in_unknown' ? (
                                <Button size="small" onClick={refetch}>
                                    Tentar novamente
                                </Button>
                            ) : null}
                        </Space>
                    </Empty>
                ) : null}

                {kind === 'history_error' ? (
                    <Alert
                        type="warning"
                        showIcon
                        message="Não foi possível carregar medições recentes"
                        description="O opt-in PSI está ativo, mas o histórico PageSpeed falhou. Tente de novo ou execute uma análise em Utilitários — não há score automático no hub."
                        action={
                            <Button size="small" onClick={refetch} data-testid="website-hub-performance-retry">
                                Tentar novamente
                            </Button>
                        }
                        style={{ marginBottom: 8 }}
                        data-testid="website-hub-performance-history-error"
                    />
                ) : null}

                {kind === 'history_error' ? (
                    <Space wrap size={8} style={{ marginTop: 8 }}>
                        <Link href={utilPsiHref}>
                            <Button type="default" size="small" icon={<ExternalLink size={14} />}>
                                Analisar em PageSpeed
                            </Button>
                        </Link>
                        <Link href={partilhasHref}>
                            <Button type="link" size="small" style={{ paddingInline: 0 }}>
                                Gerir opt-in PSI
                            </Button>
                        </Link>
                    </Space>
                ) : null}

                {kind === 'opt_in_on_no_measurement' ? (
                    <Empty
                        image={Empty.PRESENTED_IMAGE_SIMPLE}
                        description="Sem medição recente para este projeto."
                        data-testid="website-hub-performance-empty-measurement"
                    >
                        <Space wrap size={8}>
                            <Link href={utilPsiHref}>
                                <Button type="default" size="small" icon={<ExternalLink size={14} />}>
                                    Analisar em PageSpeed
                                </Button>
                            </Link>
                            <Link href={partilhasHref}>
                                <Button type="link" size="small" style={{ paddingInline: 0 }}>
                                    Gerir opt-in PSI
                                </Button>
                            </Link>
                        </Space>
                    </Empty>
                ) : null}

                {kind === 'opt_in_on_with_score' && measurement ? (
                    <Space
                        direction="vertical"
                        size={8}
                        style={{ width: '100%' }}
                        data-testid="website-hub-performance-score"
                    >
                        <Space wrap size={8} align="center">
                            <Tag color="blue">Opt-in PSI ativo</Tag>
                            {measurement.strategy ? (
                                <Text type="secondary" style={{ fontSize: 12 }}>
                                    Estratégia: {measurement.strategy}
                                </Text>
                            ) : null}
                        </Space>
                        <Text strong style={{ fontSize: 22 }} data-testid="website-hub-performance-score-value">
                            Score {formatScore(measurement.score)}
                        </Text>
                        <Space wrap size={12}>
                            {measurement.lcpMs != null ? (
                                <Text type="secondary" style={{ fontSize: 12 }}>
                                    LCP {measurement.lcpMs} ms
                                </Text>
                            ) : null}
                            {measurement.cls != null ? (
                                <Text type="secondary" style={{ fontSize: 12 }}>
                                    CLS {measurement.cls}
                                </Text>
                            ) : null}
                            {measurement.inpMs != null ? (
                                <Text type="secondary" style={{ fontSize: 12 }}>
                                    INP {measurement.inpMs} ms
                                </Text>
                            ) : null}
                        </Space>
                        {measurement.url ? (
                            <Text
                                type="secondary"
                                style={{ fontSize: 12 }}
                                ellipsis={{ tooltip: measurement.url }}
                            >
                                URL: {measurement.url}
                            </Text>
                        ) : null}
                        {measurement.analyzedAt ? (
                            <Text type="secondary" style={{ fontSize: 12 }}>
                                Última medição: {formatDate(measurement.analyzedAt, true)}
                            </Text>
                        ) : null}
                        <Space wrap size={8}>
                            <Link href={utilPsiHref}>
                                <Button type="link" size="small" style={{ paddingInline: 0 }}>
                                    Nova análise (Utilitários)
                                </Button>
                            </Link>
                            <Link href={partilhasHref}>
                                <Button type="link" size="small" style={{ paddingInline: 0 }}>
                                    Opt-in em Partilhas
                                </Button>
                            </Link>
                        </Space>
                    </Space>
                ) : null}
            </ContentCard>
        </div>
    );
}
