import { useCallback, useEffect, useState } from 'react' import { ArrowLeft, Loader2 } from 'lucide-react' import { Button } from '@/components/ui/button' import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card' import { Input } from '@/components/ui/input' import { Label } from '@/components/ui/label' import { Textarea } from '@/components/ui/textarea' import { Checkbox } from '@/components/ui/checkbox' import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select' import { ReportError } from '@/components/ui/reporting' import { AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle } from '@/components/ui/alert-dialog' import { useNavigation } from '@/contexts/navigation-context' import { registrationAccessRequest } from './use-registration-access' import { ActivityHistory as History, activityTimezoneLabel, formatActivityDate as date, type RegistrationEvent as Event } from './activity-history' type Registration = { id: number; name: string; username: string; email: string; status: string; mode: string; source: string; revision: number; createdAt: string; updatedAt: string; expired: boolean } type Listing = { items: Registration[]; total: number; pages: number; timezone: string } type Detail = { registration: Registration; fields: { key: string; label: string; value: string }[]; fieldsLabel: string; attachments: { name: string; url: string }[]; events: Event[]; profileUrl: string; timezone: string } const statuses: Record = { needs_review: 'Needs review', all: 'All tracked', pending_verification: 'Pending verification', pending_approval: 'Pending approval', verified: 'Verified', approved: 'Approved', rejected: 'Rejected' } const message = (reason: unknown) => reason instanceof Error ? reason.message : 'The request failed. Please try again.' export function RegistrationReview({ activity = false, blocked }: { activity?: boolean; blocked: boolean }) { const { currentTab, navigateTo } = useNavigation() const selectedId = !activity ? Number(currentTab?.match(/^registrations\/(\d+)$/)?.[1] || 0) : 0 const [listing, setListing] = useState(null) const [detail, setDetail] = useState(null) const [events, setEvents] = useState([]) const [timezone, setTimezone] = useState('UTC') const [page, setPage] = useState(1) const [status, setStatus] = useState('needs_review') const [search, setSearch] = useState('') const [query, setQuery] = useState('') const [loading, setLoading] = useState(true) const [saving, setSaving] = useState(false) const [error, setError] = useState(null) const [action, setAction] = useState('note') const [note, setNote] = useState('') const [applicantMessage, setApplicantMessage] = useState('') const [notify, setNotify] = useState(false) const [confirm, setConfirm] = useState(false) const load = useCallback(async (signal?: AbortSignal) => { setLoading(true); setError(null) try { if (activity) { const result = await registrationAccessRequest<{ items: Event[]; timezone: string }>(`activity?page=${page}`, undefined, signal) if (!Array.isArray(result.items)) throw Error('Activity is unavailable. Please retry.') setEvents(result.items); setTimezone(result.timezone) } else if (selectedId) { const result = await registrationAccessRequest(`registrations/${selectedId}`, undefined, signal) if (!result.registration || !Array.isArray(result.fields)) throw Error('Registration details are unavailable.') setDetail(result); setTimezone(result.timezone); setAction(result.registration.status === 'pending_approval' ? 'approve' : result.registration.status === 'rejected' ? 'reopen' : 'note') setNote(''); setApplicantMessage(''); setNotify(false) } else { const result = await registrationAccessRequest(`registrations?${new URLSearchParams({ page: String(page), status, search: query })}`, undefined, signal) if (!Array.isArray(result.items)) throw Error('Registrations are unavailable. Please retry.') setListing(result); setTimezone(result.timezone) } } catch (reason) { if (!signal?.aborted) setError(message(reason)) } finally { if (!signal?.aborted) setLoading(false) } }, [activity, page, selectedId, status, query]) useEffect(() => { const controller = new AbortController(); void load(controller.signal); return () => controller.abort() }, [load]) const decide = async () => { if (!detail || saving || blocked) return setSaving(true); setError(null) try { const result = await registrationAccessRequest(`registrations/${selectedId}/decision`, { revision: detail.registration.revision, action, note, message: applicantMessage, notify }) setDetail(result); setNote(''); setApplicantMessage(''); setNotify(false); setAction('note') } catch (reason) { setError(message(reason)) } finally { setSaving(false) } } if (blocked) return Save or discard the workspace changes before reviewing accounts. Review actions use saved access settings. const row = detail?.registration const actions = row ? ['note', ...(row.status === 'pending_approval' ? ['approve', 'reject'] : row.status === 'rejected' ? ['reopen'] : row.status === 'pending_verification' ? ['resend', 'verify'] : [])] : [] return
{selectedId > 0 && } {error && load()} />} {loading ?

Loading {activity ? 'activity' : 'registrations'}…

: activity ? Registration activityRegistrations, account decisions and access setting changes from the last 90 days. Times in {activityTimezoneLabel(timezone)}.

Page {page}

: selectedId && row ? <> {row.name || row.username}{row.email} · @{row.username}
Access status
{statuses[row.status]}{row.expired ? ' · Link expired' : ''}
Registration source
{row.source === 'unknown' ? 'Unknown' : row.source === 'wordpress' ? 'WordPress registration' : 'WooCommerce registration'}
Registered
{date(row.createdAt, timezone)}
{row.mode === 'admin_approval' &&

Administrator approval is separate from email verification. Approval does not prove the customer confirmed this email address.

}
{detail.fieldsLabel}Passwords, hidden fields and sensitive values are excluded.{detail.fields.length ?
{detail.fields.map(field =>
{field.label}
{field.value || '—'}
)}
:

No safe registration field values are available.

}
{!!detail.attachments?.length && Current protected attachmentsAuthorized downloads from the registration form. These are current files, not historical copies.} Review actionRejecting retains the account. Reopening returns it to review without granting access.