Skip to content

armgit / lyftr

Public Imported from GitHub
0

Self-hosted fitness tracker. Log workouts, track nutrition, and monitor progress. Docker deployment, mobile-friendly.

8.6 KB
Raw Blame
import { useEffect, useMemo, useState } from 'react'
import { ActivityIndicator, FlatList, Modal, Pressable, View } from 'react-native'
import { BookOpen, ChevronRight, Dumbbell, Moon, X } from 'lucide-react-native'
import type { Program, ProgramDay, UiMessage } from '@lyftr/shared'
import { workoutDays, dayLabel, todaysDay, uiMessage, useTranslation } from '@lyftr/shared'
import { AppText, EmptyState, ErrorState, Field, IconButton } from '../ui'
import { client } from '../../lib/lyftr'
import { useTheme } from '../../theme/useTheme'
import { pickProgramDay } from '../programs/DayPickerSheet'

interface Props {
  onSelect: (program: Program, day: ProgramDay) => void
  onClose: () => void
}

// Port of web/components/ProgramPicker.tsx: dimmed overlay + centered card, with the
// same two-step pick-a-program-then-pick-a-day flow (a single-workout-day program
// skips the day step, same as web). One directed addition over web: a search field —
// client-side name filter, since the program list is a single un-paginated fetch.
export function ProgramPicker({ onSelect, onClose }: Props) {
  const { t } = useTranslation()
  const { colors, accent } = useTheme()
  const [programs, setPrograms] = useState<Program[]>([])
  const [query, setQuery] = useState('')
  const [loading, setLoading] = useState(true)
  // A UiMessage rather than a sentence, so a failure already on screen follows a language switch.
  const [error, setError] = useState<UiMessage | null>(null)
  const [dayPickFor, setDayPickFor] = useState<Program | null>(null)
  const [retryKey, setRetryKey] = useState(0)

  useEffect(() => {
    setLoading(true)
    client.programAPI.list()
      .then((data) => { setPrograms(data || []); setError(null) })
      .catch((err) => setError({ key: 'workouts.form.programPicker.loadFailed', cause: err }))
      .finally(() => setLoading(false))
  }, [retryKey])

  const shown = useMemo(() => {
    const q = query.trim().toLowerCase()
    return q ? programs.filter((p) => p.name.toLowerCase().includes(q)) : programs
  }, [programs, query])

  // Decision logic (auto-select the lone day vs. open the day list) lives once in
  // DayPickerSheet.tsx's pickProgramDay — reused here instead of re-branching it.
  const pickProgram = (p: Program) => pickProgramDay(p, onSelect, setDayPickFor)

  const title = dayPickFor ? dayPickFor.name : t('workouts.form.programPicker.title')
  const subtitle = dayPickFor ? t('workouts.form.programPicker.pickDay') : t('workouts.form.programPicker.pickProgram')

  return (
    <Modal visible transparent animationType="fade" onRequestClose={dayPickFor ? () => setDayPickFor(null) : onClose}>
      <View className="flex-1 items-center justify-center bg-black/60 px-4">
        {/* maxHeight is layout math NativeWind percentages don't cover reliably — inline. */}
        <View className="w-full rounded-2xl border border-surface-border bg-surface-base" style={{ maxHeight: '80%' }}>
          <View className="flex-row items-center justify-between border-b border-surface-border px-4 py-3">
            <View className="flex-1 pr-2">
              <AppText variant="heading" numberOfLines={1}>{title}</AppText>
              <AppText variant="caption" color="muted" className="mt-0.5">{subtitle}</AppText>
            </View>
            <IconButton
              icon={X}
              label={t('workouts.form.programPicker.close')}
              variant="ghost"
              size="md"
              onPress={dayPickFor ? () => setDayPickFor(null) : onClose}
            />
          </View>

          {dayPickFor ? (
            <FlatList
              data={workoutDays(dayPickFor)}
              keyExtractor={(d, i) => String(d.id ?? i)}
              keyboardShouldPersistTaps="handled"
              renderItem={({ item: day }) => {
                const isToday = todaysDay(dayPickFor)?.id === day.id
                return (
                  <Pressable
                    accessibilityRole="button"
                    onPress={() => onSelect(dayPickFor, day)}
                    className="flex-row items-center gap-3 border-b border-surface-border px-4 py-3 active:bg-surface-muted"
                  >
                    <View className="h-9 w-9 items-center justify-center rounded-lg border border-brand-500/20 bg-brand-500/10">
                      <Dumbbell size={16} color={accent} />
                    </View>
                    <View className="flex-1">
                      <View className="flex-row items-center gap-1.5">
                        <AppText variant="subheading" numberOfLines={1}>{dayLabel(day, day.order_index)}</AppText>
                        {isToday ? (
                          <View className="rounded-full bg-brand-500/15 px-1.5 py-0.5">
                            <AppText variant="caption" style={{ color: accent }}>{t('common.todayChip')}</AppText>
                          </View>
                        ) : null}
                      </View>
                      <AppText variant="caption" color="muted" numberOfLines={1} className="mt-0.5">
                        {t('common.count.exercises', { count: (day.exercises ?? []).length })}
                      </AppText>
                    </View>
                    <ChevronRight size={16} color={colors.txMuted} />
                  </Pressable>
                )
              }}
            />
          ) : (
            <>
              <View className="border-b border-surface-border px-4 py-3">
                <Field
                  value={query}
                  onChangeText={setQuery}
                  placeholder={t('programs.list.searchPlaceholder')}
                  autoCapitalize="none"
                  autoCorrect={false}
                  returnKeyType="search"
                />
              </View>

              {loading ? (
                <View className="flex-row items-center justify-center gap-2 p-8">
                  <ActivityIndicator color={accent} />
                  <AppText variant="body" color="muted">{t('workouts.start.loadingPrograms')}</AppText>
                </View>
              ) : error ? (
                <ErrorState
                  title={t('programs.list.loadFailed')}
                  message={uiMessage(error)}
                  onRetry={() => setRetryKey((k) => k + 1)}
                />
              ) : shown.length === 0 ? (
                <EmptyState
                  compact
                  icon={BookOpen}
                  title={query ? t('workouts.form.programPicker.noMatches') : t('workouts.start.noPrograms')}
                  subtitle={query ? t('common.tryDifferentSearch') : t('workouts.form.programPicker.createFirst')}
                />
              ) : (
                <FlatList
                  data={shown}
                  keyExtractor={(p) => String(p.id)}
                  keyboardShouldPersistTaps="handled"
                  renderItem={({ item }) => {
                    const days = workoutDays(item)
                    return (
                      <Pressable
                        accessibilityRole="button"
                        disabled={days.length === 0}
                        onPress={() => pickProgram(item)}
                        className={`flex-row items-center gap-3 border-b border-surface-border px-4 py-3 active:bg-surface-muted ${days.length === 0 ? 'opacity-40' : ''}`}
                      >
                        <View className="h-9 w-9 items-center justify-center rounded-lg border border-brand-500/20 bg-brand-500/10">
                          <BookOpen size={16} color={accent} />
                        </View>
                        <View className="flex-1">
                          <AppText variant="subheading" numberOfLines={1}>{item.name}</AppText>
                          <View className="mt-0.5 flex-row items-center gap-1.5">
                            <Dumbbell size={12} color={colors.txMuted} />
                            <AppText variant="caption" color="muted" numberOfLines={1}>
                              {days.length === 0 ? t('workouts.form.programPicker.noExercises') : t('workouts.form.programPicker.workoutDays', { count: days.length })}
                            </AppText>
                            {(item.days ?? []).some((d) => d.is_rest_day) ? (
                              <Moon size={12} color={colors.txMuted} />
                            ) : null}
                          </View>
                        </View>
                        <ChevronRight size={16} color={colors.txMuted} />
                      </Pressable>
                    )
                  }}
                />
              )}
            </>
          )}
        </View>
      </View>
    </Modal>
  )
}