'use client';

import { Activity } from 'lucide-react';
import { Alert, Button, Spin, Tag, Typography } from 'antd';
import { useRouter } from 'next/navigation';

import { ICON_SIZE_MD } from '@/components/icons';
import ContentCard from '@/components/layouts/ContentCard';

import type { ScHealthAggregated, ScHealthStatus, ScTipologicoCheck } from './types';
import styles from './ScProntidaoHubBlock.module.scss';

const { Text } = Typography;

const STATUS_TAG: Record<
    ScHealthStatus,
    { color: string; label: string }
> = {
    ok: { color: 'success', label: 'OK' },
    aviso: { color: 'warning', label: 'Atenção' },
    erro: { color: 'error', label: 'Erro' },
    nao_verificado: { color: 'default', label: 'Não verificado' },
};

export type ScSaudeSistemaCardProps = {
    checks: ScTipologicoCheck[];
    message: string;
    aggregated: ScHealthAggregated;
    addonInactive?: boolean;
    healthError?: boolean;
    loading?: boolean;
};

/**
 * Card "Saúde do sistema" (prontidão tipológica A5) — distinto de "Saúde do projeto" comercial.
 */
export function ScSaudeSistemaCard({
    checks,
    message,
    aggregated,
    addonInactive = false,
    healthError = false,
    loading = false,
}: ScSaudeSistemaCardProps) {
    const router = useRouter();

    return (
        <div data-testid="sc-saude-sistema">
            <ContentCard
                title="Saúde do sistema"
                icon={<Activity size={ICON_SIZE_MD} aria-hidden />}
                loading={loading && aggregated === 'loading'}
            >
                <Text type="secondary" className={styles.cardSubtitle}>
                    Prontidão tipológica (implantação)
                </Text>

                {addonInactive ? (
                    <Alert
                        type="warning"
                        showIcon
                        style={{ marginBottom: 12 }}
                        message="Addon Desenvolvimento de software inativo"
                        description="Tipos e telas de implantação podem estar ocultos até ativar o addon."
                        action={
                            <Button size="small" onClick={() => router.push('/configuracoes/addons')}>
                                Abrir addons
                            </Button>
                        }
                    />
                ) : null}

                {healthError ? (
                    <Alert
                        type="error"
                        showIcon
                        style={{ marginBottom: 12 }}
                        message="Não foi possível carregar o diagnóstico núcleo"
                        description={'Os checks mapeados ficam como "Não verificado" até o health responder.'}
                    />
                ) : null}

                {aggregated === 'loading' ? (
                    <div style={{ textAlign: 'center', padding: 16 }} role="status" aria-busy="true">
                        <Spin size="small" />
                        <div style={{ marginTop: 8 }}>
                            <Text type="secondary">{message}</Text>
                        </div>
                    </div>
                ) : (
                    <>
                        <Alert
                            type={
                                aggregated === 'erro'
                                    ? 'error'
                                    : aggregated === 'degraded'
                                      ? 'warning'
                                      : aggregated === 'ok'
                                        ? 'success'
                                        : 'info'
                            }
                            showIcon
                            style={{ marginBottom: 12 }}
                            message={message}
                        />

                        <div className={styles.legend} aria-label="Legenda de estados">
                            <Tag color="success">OK</Tag>
                            <Tag color="warning">Atenção</Tag>
                            <Tag color="error">Erro</Tag>
                            <Tag>Não verificado</Tag>
                        </div>

                        <ul className={styles.healthList}>
                            {checks.map((check) => {
                                const tag = STATUS_TAG[check.status];
                                return (
                                    <li key={check.id} className={styles.healthItem}>
                                        <Tag color={tag.color} style={{ marginInlineEnd: 0 }}>
                                            {tag.label}
                                        </Tag>
                                        <div className={styles.healthText}>
                                            <span className={styles.healthId}>{check.id}</span>
                                            <Text style={{ fontSize: 13 }}>{check.label}</Text>
                                            <span className={styles.healthSummary}>{check.summary}</span>
                                            {check.mappedFrom ? (
                                                <span className={styles.mappedNote}>
                                                    Fonte: {check.mappedFrom}
                                                </span>
                                            ) : null}
                                        </div>
                                    </li>
                                );
                            })}
                        </ul>
                    </>
                )}
            </ContentCard>
        </div>
    );
}
