import type { ReactNode } from 'react';
import { ActivityIndicator, Pressable, ScrollView, StyleSheet, View } from 'react-native';
import { SafeAreaView } from 'react-native-safe-area-context';

import { MaxContentWidth, Spacing } from '@/constants/theme';
import { useTheme } from '@/hooks/use-theme';
import { useStore } from '@/lib/store';

import { ThemedText } from './themed-text';

/** Shared screen chrome: safe area, in-screen title bar, scrollable content column. */
export function Screen({
  title,
  subtitle,
  children,
  scroll = true,
}: {
  title: string;
  subtitle?: string;
  children: ReactNode;
  scroll?: boolean;
}) {
  const theme = useTheme();
  const { status, refresh } = useStore();

  const body = (
    <View style={styles.content}>
      <View style={styles.titleRow}>
        <ThemedText style={styles.title}>{title}</ThemedText>
        {subtitle ? (
          <ThemedText type="small" themeColor="textSecondary">
            {subtitle}
          </ThemedText>
        ) : null}
      </View>
      {status === 'offline' ? (
        <Pressable
          onPress={refresh}
          style={({ pressed }) => [
            styles.offline,
            { backgroundColor: theme.dangerSoft },
            pressed && { opacity: 0.7 },
          ]}>
          <ThemedText type="smallBold" style={{ color: theme.danger }}>
            Can't reach the server — tap to retry
          </ThemedText>
        </Pressable>
      ) : null}
      {status === 'loading' ? (
        <ActivityIndicator color={theme.felt} style={styles.loading} />
      ) : (
        children
      )}
    </View>
  );

  return (
    <SafeAreaView edges={['top']} style={[styles.safe, { backgroundColor: theme.background }]}>
      {scroll ? (
        <ScrollView
          contentContainerStyle={styles.scrollContent}
          keyboardShouldPersistTaps="handled">
          {body}
        </ScrollView>
      ) : (
        body
      )}
    </SafeAreaView>
  );
}

const styles = StyleSheet.create({
  safe: { flex: 1 },
  scrollContent: { paddingBottom: Spacing.five },
  content: {
    flex: 1,
    width: '100%',
    maxWidth: MaxContentWidth,
    alignSelf: 'center',
    paddingHorizontal: Spacing.three,
    gap: Spacing.two,
  },
  titleRow: {
    flexDirection: 'row',
    alignItems: 'baseline',
    justifyContent: 'space-between',
    paddingVertical: Spacing.two,
  },
  title: {
    fontSize: 26,
    lineHeight: 32,
    fontWeight: '800',
  },
  offline: {
    borderRadius: 10,
    paddingVertical: 10,
    alignItems: 'center',
  },
  loading: {
    marginTop: Spacing.five,
  },
});
