import { useCallback, useEffect, useMemo, useRef, useState } from 'react' import { ActivityIndicator, Alert, FlatList, KeyboardAvoidingView, Modal, Platform, Pressable, RefreshControl, ScrollView, StyleSheet, TextInput, View, } from 'react-native' import type { NavigationProp, ParamListBase } from '@react-navigation/native' import { useFocusEffect } from '@react-navigation/native' import type { Meeting, MeetingLanguage, UserTemplate } from '@d3ro/api-client' import { useI18n } from '@d3ro/i18n' import { useAuth } from '../lib/auth-context' import { useMobilePreferences } from '../lib/preferences-context' import { ThemeButton, ThemeCard, ThemeText } from '../theme/themed-components' import { ScreenHeader } from '../components/ScreenHeader' import { createMeetingCreationIdempotencyKey, createMeetingWorkspaceWithMetadata, deleteMeetingRevisionSafe, listMeetingsPage, MeetingServiceError, updateMeetingTitleRevisionSafe, } from '../features/meetings/meetings-service' import { loadTemplateLibrary } from '../features/templates' import { useTabScreenBottomPadding } from '../navigation/tab-layout' interface MeetingsScreenProps { navigation: NavigationProp route?: { params?: { createRequest?: number } } } type EditorMode = | { kind: 'create' } | { kind: 'edit'; meeting: Meeting } | null const MEETING_LANGUAGES = ['ko', 'en', 'ja', 'zh-cn'] as const export default function MeetingsScreen({ navigation, route, }: MeetingsScreenProps): React.ReactElement { const bottomPadding = useTabScreenBottomPadding() const { t, formatDate } = useI18n() const { user } = useAuth() const { palette } = useMobilePreferences() const styles = useMemo(() => createStyles(palette), [palette]) const requestGeneration = useRef(0) const templateRequestGeneration = useRef(0) const editorBusyRef = useRef(false) const editorUserIdRef = useRef(user?.id ?? null) const handledCreateRequests = useRef(new Set()) const openCreateRef = useRef<() => void>(() => undefined) const [meetings, setMeetings] = useState([]) const [total, setTotal] = useState(0) const [page, setPage] = useState(0) const [hasMore, setHasMore] = useState(false) const [search, setSearch] = useState('') const [committedSearch, setCommittedSearch] = useState('') const [loading, setLoading] = useState(true) const [refreshing, setRefreshing] = useState(false) const [loadingMore, setLoadingMore] = useState(false) const [error, setError] = useState(null) const [busyId, setBusyId] = useState(null) const [editor, setEditor] = useState(null) const [editorTitle, setEditorTitle] = useState('') const [editorAttendees, setEditorAttendees] = useState('') const [editorLanguage, setEditorLanguage] = useState('ko') const [editorTemplates, setEditorTemplates] = useState([]) const [editorTemplateId, setEditorTemplateId] = useState(null) const [editorTemplatesLoading, setEditorTemplatesLoading] = useState(false) const [editorCreationKey, setEditorCreationKey] = useState(null) const [editorError, setEditorError] = useState(null) const [editorBusy, setEditorBusy] = useState(false) useEffect(() => { const nextUserId = user?.id ?? null if (editorUserIdRef.current === nextUserId) return editorUserIdRef.current = nextUserId templateRequestGeneration.current += 1 editorBusyRef.current = false setEditor(null) setEditorTemplates([]) setEditorTemplateId(null) setEditorCreationKey(null) setEditorError(null) setEditorBusy(false) }, [user?.id]) useEffect(() => { const timer = setTimeout(() => setCommittedSearch(search.trim()), 300) return () => clearTimeout(timer) }, [search]) const loadFirstPage = useCallback(async ( pullToRefresh = false, ): Promise => { const generation = ++requestGeneration.current if (user === null) { setMeetings([]) setTotal(0) setHasMore(false) setError(t('mobile.meetings.loginRequired')) setLoading(false) setRefreshing(false) return } if (pullToRefresh) setRefreshing(true) else setLoading(true) setError(null) try { const result = await listMeetingsPage({ userId: user.id, search: committedSearch, page: 0, }) if (generation !== requestGeneration.current) return setMeetings(result.meetings) setTotal(result.total) setPage(0) setHasMore(result.hasMore) } catch (requestError) { if (generation !== requestGeneration.current) return setError(meetingErrorMessage(requestError, t)) } finally { if (generation === requestGeneration.current) { setLoading(false) setRefreshing(false) } } }, [committedSearch, t, user]) useFocusEffect(useCallback(() => { void loadFirstPage(false) return () => { requestGeneration.current += 1 } }, [loadFirstPage])) const loadMore = async (): Promise => { if (user === null || loading || loadingMore || !hasMore) return const targetPage = page + 1 setLoadingMore(true) try { const result = await listMeetingsPage({ userId: user.id, search: committedSearch, page: targetPage, }) setMeetings((current) => mergeMeetings(current, result.meetings)) setPage(targetPage) setTotal(result.total) setHasMore(result.hasMore) } catch (requestError) { setError(meetingErrorMessage(requestError, t)) } finally { setLoadingMore(false) } } const openDetail = (meeting: Meeting): void => { const target = navigation.getParent() ?? navigation target.navigate('MeetingDetail', { meetingId: meeting.id }) } const loadCreationTemplates = async (): Promise => { if (user === null) return const generation = ++templateRequestGeneration.current const requestedUserId = user.id setEditorTemplatesLoading(true) try { const library = await loadTemplateLibrary(user.id, 'meeting_document') if ( generation !== templateRequestGeneration.current || editorUserIdRef.current !== requestedUserId ) return setEditorTemplates(library.templates) const selectedId = library.selections.meeting_document?.template_id setEditorTemplateId( library.templates.some((template) => template.id === selectedId) ? selectedId ?? null : library.templates[0]?.id ?? null, ) } catch { if ( generation !== templateRequestGeneration.current || editorUserIdRef.current !== requestedUserId ) return setEditorError(t('mobile.meetings.templateLoadError')) setEditorTemplates([]) setEditorTemplateId(null) } finally { if (generation === templateRequestGeneration.current) { setEditorTemplatesLoading(false) } } } const openCreate = (): void => { setEditor({ kind: 'create' }) setEditorTitle('') setEditorAttendees('') setEditorLanguage('ko') setEditorTemplates([]) setEditorTemplateId(null) setEditorError(null) try { setEditorCreationKey(createMeetingCreationIdempotencyKey()) } catch (requestError) { setEditorCreationKey(null) setEditorError(meetingErrorMessage(requestError, t)) } void loadCreationTemplates() } openCreateRef.current = openCreate useEffect(() => { const request = route?.params?.createRequest if (request === undefined || handledCreateRequests.current.has(request)) return handledCreateRequests.current.add(request) navigation.setParams({ createRequest: undefined }) openCreateRef.current() }, [navigation, route?.params?.createRequest]) const openEdit = (meeting: Meeting): void => { setEditor({ kind: 'edit', meeting }) setEditorTitle(meeting.title ?? '') setEditorError(null) } const closeEditor = (): void => { if (editorBusyRef.current) return templateRequestGeneration.current += 1 setEditor(null) setEditorTitle('') setEditorAttendees('') setEditorTemplates([]) setEditorTemplateId(null) setEditorCreationKey(null) setEditorError(null) } const saveEditor = async (): Promise => { if (user === null || editor === null || editorBusyRef.current) return editorBusyRef.current = true setEditorBusy(true) setEditorError(null) try { if (editor.kind === 'create') { if (editorCreationKey === null) { throw new MeetingServiceError('validation', 'Meeting creation key is unavailable') } const attendees = editorAttendees .split(/[\r\n,]+/) .map((attendee) => attendee.trim()) .filter((attendee) => attendee.length > 0) const created = await createMeetingWorkspaceWithMetadata(user.id, { title: editorTitle, attendees, language: editorLanguage, templateId: editorTemplateId, idempotencyKey: editorCreationKey, }) setMeetings((current) => mergeMeetings([created], current)) setTotal((current) => current + 1) setEditor(null) openDetail(created) } else { const updated = await updateMeetingTitleRevisionSafe(editor.meeting, editorTitle) setMeetings((current) => current.map((meeting) => ( meeting.id === updated.id ? updated : meeting ))) setEditor(null) } } catch (requestError) { setEditorError(meetingErrorMessage(requestError, t)) } finally { editorBusyRef.current = false setEditorBusy(false) } } const confirmDelete = (meeting: Meeting): void => { Alert.alert( t('mobile.meetings.deleteTitle'), t('mobile.meetings.deleteBody'), [ { text: t('common.cancel'), style: 'cancel' }, { text: t('mobile.meetings.delete'), style: 'destructive', onPress: () => { void performDelete(meeting) }, }, ], ) } const performDelete = async (meeting: Meeting): Promise => { if (user === null || busyId !== null) return setBusyId(meeting.id) setError(null) try { await deleteMeetingRevisionSafe(user.id, meeting) setMeetings((current) => current.filter((candidate) => candidate.id !== meeting.id)) setTotal((current) => Math.max(0, current - 1)) } catch (requestError) { setError(meetingErrorMessage(requestError, t)) if (requestError instanceof MeetingServiceError && requestError.code === 'conflict') { void loadFirstPage(false) } } finally { setBusyId(null) } } return ( )} testID="meetings-header" /> {error !== null && ( {error} { void loadFirstPage(false) }} testID="meetings-retry" /> )} {loading && meetings.length === 0 ? ( {t('mobile.meetings.loading')} ) : ( meeting.id} contentContainerStyle={[ meetings.length === 0 ? styles.emptyList : styles.list, { paddingBottom: bottomPadding }, ]} keyboardShouldPersistTaps="handled" refreshControl={( { void loadFirstPage(true) }} tintColor={palette.accent.main} colors={[palette.accent.main]} /> )} onEndReached={() => { void loadMore() }} onEndReachedThreshold={0.3} ListEmptyComponent={( {committedSearch.length > 0 ? t('mobile.meetings.emptySearch') : t('mobile.meetings.empty')} )} ListFooterComponent={loadingMore ? ( ) : null} renderItem={({ item: meeting }) => { const busy = busyId === meeting.id const owned = meeting.user_id === user?.id return ( openDetail(meeting)} style={styles.cardBody} testID={`meeting-open-${meeting.id}`} > {meeting.title ?? t('mobile.meetings.untitled')} {formatDate(new Date(meeting.started_at), { dateStyle: 'medium', timeStyle: 'short', })} {meeting.team_id === null ? t('mobile.meetings.personal') : t('mobile.meetings.team')} openEdit(meeting)} testID={`meeting-edit-${meeting.id}`} /> {owned && ( confirmDelete(meeting)} testID={`meeting-delete-${meeting.id}`} /> )} {busy && } ) }} /> )} {editor?.kind === 'create' ? t('mobile.meetings.createTitle') : t('mobile.meetings.editTitle')} {editor?.kind === 'create' && ( {t('mobile.meetings.attendeesLabel')} {t('mobile.meetings.attendeesHint')} {t('mobile.meetings.languageLabel')} {MEETING_LANGUAGES.map((language) => { const selected = language === editorLanguage return ( setEditorLanguage(language)} style={[styles.choice, selected && styles.choiceSelected]} testID={`meeting-language-${language}`} > {t(`mobile.meetings.language.${language}`)} ) })} {t('mobile.meetings.templateLabel')} {editorTemplatesLoading ? ( {t('mobile.meetings.templateLoading')} ) : editorTemplates.length === 0 ? ( {t('mobile.meetings.templateEmpty')} { setEditorError(null) void loadCreationTemplates() }} testID="meeting-templates-retry" /> ) : ( setEditorTemplateId(null)} style={[styles.templateChoice, editorTemplateId === null && styles.choiceSelected]} testID="meeting-template-none" > {t('mobile.meetings.templateNone')} {t('mobile.meetings.templateNoneDesc')} {editorTemplates.map((template) => { const selected = template.id === editorTemplateId return ( setEditorTemplateId(template.id)} style={[styles.templateChoice, selected && styles.choiceSelected]} testID={`meeting-template-${template.id}`} > {template.name} {template.description ?? t('mobile.meetings.templateCustom')} ) })} )} {t('mobile.meetings.createNotice')} )} {editorError !== null && ( {editorError} )} { void saveEditor() }} style={styles.flexButton} testID="meeting-editor-save" /> ) } function StatusBadge({ status }: { status: Meeting['status'] }): React.ReactElement { const { t } = useI18n() const { palette } = useMobilePreferences() const label = status === 'recording' ? t('mobile.meetings.statusRecording') : status === 'processing' ? t('mobile.meetings.statusProcessing') : status === 'completed' ? t('mobile.meetings.statusCompleted') : t('mobile.meetings.statusError') const color = status === 'completed' ? palette.tag.green : status === 'error' ? palette.tag.red : palette.tag.orange return ( {label} ) } export function mergeMeetings(current: Meeting[], incoming: Meeting[]): Meeting[] { const rows = new Map(current.map((meeting) => [meeting.id, meeting])) for (const meeting of incoming) { const existing = rows.get(meeting.id) if (existing === undefined || meeting.updated_at >= existing.updated_at) { rows.set(meeting.id, meeting) } } return [...rows.values()].sort((left, right) => { const byStartedAt = right.started_at.localeCompare(left.started_at) return byStartedAt !== 0 ? byStartedAt : right.id.localeCompare(left.id) }) } type Translate = ReturnType['t'] function meetingErrorMessage(error: unknown, t: Translate): string { if (!(error instanceof MeetingServiceError)) return t('mobile.meetings.errorServer') if (error.code === 'auth') return t('mobile.meetings.loginRequired') if (error.code === 'conflict') return t('mobile.meetings.errorConflict') if (error.code === 'forbidden') return t('mobile.meetings.errorForbidden') if (error.code === 'network') return t('mobile.meetings.errorNetwork') if (error.code === 'not-found') return t('mobile.meetings.errorNotFound') if (error.code === 'validation') return t('mobile.meetings.errorValidation') return t('mobile.meetings.errorServer') } type Palette = ReturnType['palette'] const stylesStatic = StyleSheet.create({ badge: { minHeight: 28, justifyContent: 'center', paddingHorizontal: 8, borderWidth: 1, borderRadius: 999, }, }) function createStyles(palette: Palette): ReturnType { return StyleSheet.create({ container: { flex: 1, backgroundColor: palette.bg.app }, header: { minHeight: 92, paddingHorizontal: 20, paddingBottom: 10, flexDirection: 'row', alignItems: 'center', justifyContent: 'space-between', gap: 14, }, headerCopy: { flex: 1, gap: 4 }, searchWrap: { paddingHorizontal: 20, paddingBottom: 12 }, searchInput: { minHeight: 48, borderWidth: 1, borderColor: palette.border.default, borderRadius: 10, paddingHorizontal: 14, backgroundColor: palette.bg.inset, color: palette.text.primary, fontSize: 14, }, errorBanner: { marginHorizontal: 20, marginBottom: 10, paddingHorizontal: 12, minHeight: 52, flexDirection: 'row', alignItems: 'center', gap: 10, borderWidth: 1, borderColor: palette.tag.red, borderRadius: 10, backgroundColor: palette.bg.card, }, errorText: { flex: 1 }, center: { flex: 1, alignItems: 'center', justifyContent: 'center', gap: 12, padding: 32 }, list: { paddingHorizontal: 20, paddingTop: 4 }, emptyList: { flexGrow: 1, justifyContent: 'center', paddingHorizontal: 20 }, emptyCard: { alignItems: 'center', paddingVertical: 36 }, emptyText: { textAlign: 'center' }, card: { marginBottom: 12, padding: 0, overflow: 'hidden' }, cardBody: { padding: 16, gap: 7 }, cardTop: { flexDirection: 'row', alignItems: 'flex-start', gap: 12 }, cardTitle: { flex: 1 }, actions: { minHeight: 52, paddingHorizontal: 8, flexDirection: 'row', alignItems: 'center', justifyContent: 'flex-end', borderTopWidth: 1, borderTopColor: palette.border.subtle, }, loadingMore: { minHeight: 72, justifyContent: 'center', alignItems: 'center' }, modalBackdrop: { flex: 1, padding: 20, justifyContent: 'center', backgroundColor: palette.scrim, }, modalCard: { gap: 14, maxWidth: 560, maxHeight: '92%', width: '100%', alignSelf: 'center' }, modalScroll: { flexShrink: 1 }, modalScrollContent: { gap: 14, paddingBottom: 2 }, creationFields: { gap: 14 }, fieldGroup: { gap: 7 }, editorInput: { minHeight: 52, borderWidth: 1, borderColor: palette.border.strong, borderRadius: 10, paddingHorizontal: 14, backgroundColor: palette.bg.inset, color: palette.text.primary, fontSize: 15, }, attendeesInput: { minHeight: 86, paddingVertical: 10 }, choiceRow: { flexDirection: 'row', flexWrap: 'wrap', gap: 8 }, choice: { minHeight: 48, minWidth: 64, alignItems: 'center', justifyContent: 'center', paddingHorizontal: 12, borderRadius: 9, borderWidth: 1, borderColor: palette.border.default }, choiceSelected: { backgroundColor: palette.accent.main, borderColor: palette.accent.main }, templateLoading: { minHeight: 52, flexDirection: 'row', alignItems: 'center', gap: 10 }, templateEmpty: { minHeight: 52, flexDirection: 'row', alignItems: 'center', justifyContent: 'space-between', gap: 10 }, templateChoices: { gap: 9, paddingRight: 4 }, templateChoice: { width: 210, minHeight: 78, justifyContent: 'center', gap: 5, padding: 12, borderRadius: 10, borderWidth: 1, borderColor: palette.border.default, backgroundColor: palette.bg.inset }, modalActions: { flexDirection: 'row', gap: 10 }, flexButton: { flex: 1 }, }) }