'use client' import { CalendarDaysIcon, CalendarXIcon, CheckIcon, CircleAlertIcon, InstagramIcon, SearchIcon, TriangleAlertIcon, } from 'lucide-react' import Link from 'next/link' import { useRouter } from 'next/navigation' import { useRef, useState, type KeyboardEvent } from 'react' import type { ContentPieceProfileImportCandidatesResponse, ContentPieceProfileImportCreateResponse, } from '@/app/(campaign)/campanha/(app)/comunicacao/conteudos/types' import { Alert, AlertDescription } from '@/components/ui/Alert' import { Badge } from '@/components/ui/Badge' import { Button } from '@/components/ui/button' import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle, DialogTrigger, } from '@/components/ui/dialog' import { Input } from '@/components/ui/input' import { Progress } from '@/components/ui/Progress' import { Spinner } from '@/components/ui/Spinner' import { postCampaignJson } from '@/lib/campaignJsonRequest' import { CAMPAIGN_CONTENT_PIECE_PROFILE_IMPORT_CREATE_HREF, CAMPAIGN_CONTENT_PIECE_PROFILE_IMPORT_HREF, } from '@/lib/campaignPaths' import { formatBahiaCivilDate, formatCivilDateLabel, subtractBahiaCivilDays, subtractBahiaCivilMonths, } from '@/lib/campaignTime' import type { ContentPieceProfileLinkOnlyReason } from '@/lib/contentPiece' import { CONTENT_PIECE_PROFILE_IMPORT_LARGE_WINDOW_THRESHOLD, contentPieceProfilePeriodError, contentPieceProfileWindowLabel, type ContentPieceProfileWindow, } from '@/lib/contentPieceProfileWindow' import { cn } from '@/lib/utils' import { buildContentPieceListHref } from '@/utilities/content/contentPieceListUrl' const GENERIC_ERROR_MESSAGE = 'Não foi possível concluir a importação. Tente novamente.' const PROFILE_HANDLE = '@depjorgesolla' type ImportPhase = 'window' | 'confirm' | 'running' | 'done' | 'empty' | 'error' type WindowMode = 'recent' | 'period' type ImportResult = { created: number existing: number failed: number /** The created peças-link, one entry per publication, with the honest reason. */ linkOnly: ContentPieceProfileLinkOnlyReason[] /** First non-generic failure message of the loop, shown in the receipt. */ failureMessage: string | null /** The official API did not reach the window start (design scene 06d). */ truncated: boolean /** "Período · 01/08/2026 → hoje" in period mode; null for the recency slice. */ windowLabel: string | null } type ImportListing = Extract const IMPORT_STATUS: Record< ContentPieceProfileLinkOnlyReason, { title: string; description: string } > = { carrossel: { title: 'carrossel', description: 'A API oficial não ofereceu um arquivo único. A publicação entrou pelo link, com este motivo na ficha.', }, indisponivel: { title: 'sem arquivo extraível', description: 'O arquivo não pôde ser extraído pela via oficial. A publicação não foi descartada.', }, } /** Counts the created peças-link per reason, in first-seen order. */ const countByReason = ( reasons: readonly ContentPieceProfileLinkOnlyReason[], ): [ContentPieceProfileLinkOnlyReason, number][] => { const counts = new Map() for (const reason of reasons) counts.set(reason, (counts.get(reason) ?? 0) + 1) return [...counts] } const plural = (count: number, singular: string, pluralForm: string): string => count === 1 ? singular : pluralForm /** * C230/C235 — "Importar do perfil": the assessoria brings the publications of * the official profile into the Central. The dialog drives the two phases for * real — the listing (Graph API, own profile only, dedupe by post identity) * and one creation per novelty through the C220 pipeline. C235 adds the window * choice: Recents stays the default single-click gesture; a period is an * explicit gesture that shows the honest size (new · already there · total) * before creating. Nothing is published: every novelty lands as Rascunho. */ export const ImportContentPieceProfileDialog = ({ configured, triggerClassName, }: { /** False hides the action behind the design's fail-closed caption/disabled button. */ configured: boolean triggerClassName?: string }) => { const router = useRouter() const [open, setOpen] = useState(false) const [phase, setPhase] = useState('window') const [mode, setMode] = useState('recent') const [since, setSince] = useState('') const [until, setUntil] = useState('') const [windowError, setWindowError] = useState(null) const [searching, setSearching] = useState(false) const [listing, setListing] = useState(null) const [progress, setProgress] = useState({ done: 0, total: 0 }) const [result, setResult] = useState(null) const [error, setError] = useState(null) const recentRadioRef = useRef(null) const periodRadioRef = useRef(null) const today = formatBahiaCivilDate(new Date()) const selectWindowMode = (next: WindowMode) => { setMode(next) setWindowError(null) } // WAI-ARIA radiogroup: arrows move the selection and the focus (roving // tabindex), so the two window options behave like one control. const handleWindowChoiceKeyDown = (event: KeyboardEvent) => { if (!['ArrowDown', 'ArrowRight', 'ArrowUp', 'ArrowLeft'].includes(event.key)) return event.preventDefault() const next = mode === 'recent' ? 'period' : 'recent' selectWindowMode(next) ;(next === 'recent' ? recentRadioRef : periodRadioRef).current?.focus() } const reset = () => { setPhase('window') setMode('recent') setSince('') setUntil('') setWindowError(null) setSearching(false) setListing(null) setProgress({ done: 0, total: 0 }) setResult(null) setError(null) } const periodWindow = (): ContentPieceProfileWindow => ({ mode: 'period', since, until: until || undefined, }) const requestWindow = (): ContentPieceProfileWindow => mode === 'recent' ? { mode: 'recent' } : periodWindow() const requestLabel = (request: ContentPieceProfileWindow): string | null => request.mode === 'period' ? `Período · ${contentPieceProfileWindowLabel(request)}` : null const runCreationLoop = async (window: ContentPieceProfileWindow, listed: ImportListing) => { setPhase('running') setProgress({ done: 0, total: listed.candidates.length }) let created = 0 let existing = listed.existingCount let failed = 0 let failureMessage: string | null = null const linkOnly: ContentPieceProfileLinkOnlyReason[] = [] for (const [index, candidate] of listed.candidates.entries()) { try { const { ok, payload } = await postCampaignJson( CAMPAIGN_CONTENT_PIECE_PROFILE_IMPORT_CREATE_HREF, { url: candidate.url }, ) if (ok && payload.status === 'success') { if (payload.outcome === 'created') { created += 1 if (candidate.linkOnlyReason) linkOnly.push(candidate.linkOnlyReason) } else { existing += 1 } } else { failed += 1 // A safe domain message (e.g. expired session) is more honest than // the generic network copy; the first one names the whole receipt. if (payload.status === 'error') failureMessage ??= payload.message } } catch { failed += 1 } setProgress({ done: index + 1, total: listed.candidates.length }) } setResult({ created, existing, failed, linkOnly, failureMessage, truncated: listed.truncated, windowLabel: requestLabel(window), }) setPhase('done') router.refresh() } const runSearch = async () => { const request = requestWindow() if (request.mode === 'period') { const message = contentPieceProfilePeriodError({ since: request.since, until: request.until ?? null, today, }) if (message) { setWindowError(message) return } } setWindowError(null) setError(null) setListing(null) setPhase('running') setSearching(true) setProgress({ done: 0, total: 0 }) let found: ImportListing try { const { ok, payload } = await postCampaignJson( CAMPAIGN_CONTENT_PIECE_PROFILE_IMPORT_HREF, request, ) if (!ok || payload.status !== 'success') { setError(payload.status === 'error' ? payload.message : GENERIC_ERROR_MESSAGE) setPhase('error') return } found = payload } catch { setError(GENERIC_ERROR_MESSAGE) setPhase('error') return } setListing(found) setSearching(false) if (request.mode === 'recent') { await runCreationLoop(request, found) return } if (found.found === 0) { setPhase('empty') return } if (found.candidates.length === 0) { setResult({ created: 0, existing: found.existingCount, failed: 0, linkOnly: [], failureMessage: null, truncated: found.truncated, windowLabel: requestLabel(request), }) setPhase('done') return } setPhase('confirm') } const linkOnlyRows = result ? countByReason(result.linkOnly) : [] const progressPercent = progress.total > 0 ? Math.round((progress.done / progress.total) * 100) : 0 const largeWindow = listing !== null && listing.candidates.length > CONTENT_PIECE_PROFILE_IMPORT_LARGE_WINDOW_THRESHOLD const windowStep = ( <>
Importar do perfil Escolha quais publicações de {PROFILE_HANDLE} procurar. Só as que ainda não estão na Central entram, sempre como rascunho.

Qual janela de publicações?

O recorte usa a data de publicação do post.

{mode === 'period' ? (

Deixe “Até” em branco para buscar até hoje.

) : null}
{windowError ? (

{windowError}

) : null}

) return ( { if (phase === 'running') return setOpen(next) if (!next) reset() }} > { if (phase === 'running') event.preventDefault() }} onEscapeKeyDown={(event) => { if (phase === 'running') event.preventDefault() }} > {phase === 'done' && result ? ( <>
Importação concluída {result.created === 0 && result.failed === 0 ? `Nenhuma novidade na ${ result.windowLabel ? 'janela escolhida' : 'janela recente' } — a Central já estava em dia.` : 'As novidades já estão na Central como rascunho. Nada foi publicado.'} {result.windowLabel ? (

{result.windowLabel}

) : null}
{result.truncated ? (
) : null}
{result.created} novas criadas
{result.existing} já estavam
{result.failed} {result.failed === 1 ? 'falhou' : 'falharam'}
{linkOnlyRows.length > 0 || result.failed > 0 ? (
{linkOnlyRows.map(([reason, count], index) => { const status = IMPORT_STATUS[reason] return (
0 ? 'border-b' : '', )} > Peça-link
{count} {status.title} · criado como peça-link

{status.description}

) })} {result.failed > 0 ? (
) : null}
) : null} ) : phase === 'confirm' && listing ? ( <>
Importar do perfil A janela escolhida tem {listing.found}{' '} {plural(listing.found, 'publicação', 'publicações')}. Confira o tamanho antes de criar os rascunhos.
{listing.candidates.length} novas a criar
{listing.existingCount} já estavam
{listing.found} total na janela
{largeWindow ? (
) : null}

Reexecutar a mesma janela não duplica: o que já está é reconhecido pela identidade do post. Pode demorar um pouco em janelas grandes.

) : phase === 'empty' ? ( <>
Nenhuma publicação neste período Nada de {PROFILE_HANDLE} foi publicado entre{' '} {formatCivilDateLabel(since)} e{' '} {until ? formatCivilDateLabel(until) : 'hoje'}.

O recorte está vazio. Confira as datas ou importe as publicações recentes do perfil.

) : phase === 'error' ? ( <>
Importar do perfil {mode === 'period' ? ( <> A janela de{' '} {contentPieceProfileWindowLabel(periodWindow())} {' '} não pôde ser buscada agora. ) : ( <>As publicações recentes não puderam ser buscadas agora. )}
) : phase === 'running' ? ( <>
Importando do perfil Mantenha esta janela aberta até concluir.
{searching ? ( ) : (
{searching ? mode === 'period' ? 'Buscando as publicações do período…' : 'Buscando as publicações recentes…' : mode === 'period' && listing ? `Janela encontrada · ${listing.found} avaliadas` : 'Publicações recentes encontradas'}

{searching ? `Consultando ${PROFILE_HANDLE} pela API oficial.` : mode === 'period' && listing ? `${listing.candidates.length} novas · ${listing.existingCount} já estavam. A busca foi feita em ${PROFILE_HANDLE} pela API oficial.` : `A busca foi feita em ${PROFILE_HANDLE} pela API oficial.`}

{!searching && progress.total > 0 ? ( <>
Importando {Math.min(progress.done + 1, progress.total)} de {progress.total} … {mode === 'period' ? ( ) : null}

Criando apenas as novidades como rascunho e reconhecendo o que já estava na Central.

) : null}

{mode === 'period' ? ( <> Pode demorar — a janela é grande e cada mídia é preparada uma a uma. O resultado final separa novas, já existentes e falhas; nenhuma falha fica escondida. ) : ( <> Algumas mídias podem levar mais tempo para serem preparadas. O resultado final separa novas, já existentes e falhas — nenhuma falha fica escondida. )}

) : ( windowStep )}
) }