'use client';

/**
 * Preview actividade + comentários no hub Visão Geral website (TASK-PWP-061).
 */

import { History, MessageSquare } from 'lucide-react';
import { Alert, Button, Empty, Space, 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 scStyles from '@/features/projetos/sistema-customizado-prontidao/ScProntidaoHubBlock.module.scss';

import { stripHtmlPreview } from './stripHtmlPreview';
import type { UseWebsiteHubActivityResult } from './useWebsiteHubActivity';

const { Text } = Typography;

export type WebsiteHubActivityCardProps = {
    projetoId: string;
    state: UseWebsiteHubActivityResult;
};

/**
 * Card denso ERP com preview (não feed tempo-real) e links para as tabs completas.
 */
export function WebsiteHubActivityCard({ projetoId, state }: WebsiteHubActivityCardProps) {
    const {
        activities,
        comments,
        isLoading,
        activityError,
        commentsError,
        refetch,
    } = state;

    const atividadesHref = `/projetos/${projetoId}?tab=atividades`;
    const comentariosHref = `/projetos/${projetoId}?tab=comentarios`;
    const bothEmpty =
        !isLoading &&
        !activityError &&
        !commentsError &&
        activities.length === 0 &&
        comments.length === 0;
    const bothError = activityError && commentsError;

    return (
        <div data-testid="website-hub-activity-card">
            <ContentCard
                title="Atividade recente"
                icon={<History size={ICON_SIZE_MD} aria-hidden />}
                loading={isLoading}
                headerActions={
                    !isLoading ? (
                        <Space size={4} wrap>
                            <Link href={atividadesHref}>
                                <Button type="link" size="small" data-testid="website-hub-activity-ver-todas">
                                    Ver todas
                                </Button>
                            </Link>
                        </Space>
                    ) : undefined
                }
            >
                <Text type="secondary" className={scStyles.cardSubtitle}>
                    Resumo do histórico e comentários do projeto — atualiza ao abrir a página (não é chat
                    em tempo real)
                </Text>

                {bothError ? (
                    <Alert
                        type="error"
                        showIcon
                        message="Não foi possível carregar a atividade"
                        description="Tente novamente ou abra as tabs Atividades e Comentários."
                        action={
                            <Button size="small" onClick={refetch} data-testid="website-hub-activity-retry">
                                Tentar novamente
                            </Button>
                        }
                        style={{ marginBottom: 8 }}
                    />
                ) : null}

                {bothEmpty ? (
                    <Empty
                        image={Empty.PRESENTED_IMAGE_SIMPLE}
                        description="Ainda não há atividades nem comentários neste projeto."
                        style={{ margin: '8px 0 12px' }}
                    />
                ) : null}

                {!bothEmpty && !bothError ? (
                    <Space direction="vertical" size={16} style={{ width: '100%' }}>
                        <section data-testid="website-hub-activity-timeline">
                            <Space
                                align="center"
                                style={{ width: '100%', justifyContent: 'space-between', marginBottom: 8 }}
                            >
                                <Text strong style={{ fontSize: 13 }}>
                                    <History size={14} aria-hidden style={{ marginRight: 6 }} />
                                    Timeline
                                </Text>
                                {activityError ? (
                                    <Text type="secondary" style={{ fontSize: 12 }}>
                                        Falha ao carregar
                                    </Text>
                                ) : null}
                            </Space>
                            {!activityError && activities.length === 0 ? (
                                <Text type="secondary" style={{ fontSize: 12 }}>
                                    Sem entradas recentes na timeline.
                                </Text>
                            ) : null}
                            <ul className={scStyles.checklistList}>
                                {activities.map((item, idx) => (
                                    <li
                                        key={`${item.tipo}-${item.data}-${idx}`}
                                        className={scStyles.checklistItem}
                                    >
                                        <div className={scStyles.checklistBody}>
                                            <span className={scStyles.checklistLabel}>
                                                {item.descricao || 'Atividade'}
                                            </span>
                                            <span className={scStyles.checklistDetail}>
                                                {[
                                                    item.usuario?.nome,
                                                    item.data ? formatDate(item.data, true) : null,
                                                ]
                                                    .filter(Boolean)
                                                    .join(' · ')}
                                            </span>
                                        </div>
                                    </li>
                                ))}
                            </ul>
                        </section>

                        <section data-testid="website-hub-activity-comments">
                            <Space
                                align="center"
                                style={{ width: '100%', justifyContent: 'space-between', marginBottom: 8 }}
                            >
                                <Text strong style={{ fontSize: 13 }}>
                                    <MessageSquare size={14} aria-hidden style={{ marginRight: 6 }} />
                                    Comentários
                                </Text>
                                <Link href={comentariosHref}>
                                    <Button type="link" size="small" style={{ paddingInline: 0 }}>
                                        Ver comentários
                                    </Button>
                                </Link>
                            </Space>
                            {commentsError ? (
                                <Text type="secondary" style={{ fontSize: 12 }}>
                                    Não foi possível carregar comentários.
                                </Text>
                            ) : null}
                            {!commentsError && comments.length === 0 ? (
                                <Text type="secondary" style={{ fontSize: 12 }}>
                                    Nenhum comentário ainda.
                                </Text>
                            ) : null}
                            <ul className={scStyles.checklistList}>
                                {comments.map((c) => (
                                    <li key={c.id} className={scStyles.checklistItem}>
                                        <div className={scStyles.checklistBody}>
                                            <span className={scStyles.checklistLabel}>
                                                {c.usuario?.nome?.trim() || 'Usuário'}
                                            </span>
                                            <span className={scStyles.checklistDetail}>
                                                {stripHtmlPreview(c.conteudo) || '—'}
                                                {c.created_at
                                                    ? ` · ${formatDate(c.created_at, true)}`
                                                    : ''}
                                            </span>
                                        </div>
                                    </li>
                                ))}
                            </ul>
                        </section>
                    </Space>
                ) : null}
            </ContentCard>
        </div>
    );
}
