import { Image, type ImageProps } from 'expo-image';
import React from 'react';
import { ActivityIndicator, StyleSheet, Text, View, type ViewStyle } from 'react-native';
import { theme } from '../theme';

type Status = 'loading' | 'loaded' | 'error' | 'empty';

interface Props {
  url?: string | null;
  style?: ViewStyle;
  contentFit?: ImageProps['contentFit'];
  /** Override missing-thumb glyph — default: video camera */
  emptyGlyph?: string;
}

/**
 * Thumbnail z 3 stanami:
 *   - empty (URL nie istnieje) → ikonka kamery + szare tło
 *   - loading → spinner
 *   - error (load failed, np. 404 obrazka) → ikonka "broken"
 * Hide spinner po fazie loaded — Image jest na wierzchu.
 */
export function Thumb({ url, style, contentFit = 'cover', emptyGlyph = '🎬' }: Props) {
  const [status, setStatus] = React.useState<Status>(url ? 'loading' : 'empty');

  React.useEffect(() => {
    setStatus(url ? 'loading' : 'empty');
  }, [url]);

  return (
    <View style={[styles.wrap, style]}>
      {url ? (
        <Image
          source={{ uri: url }}
          style={StyleSheet.absoluteFill}
          contentFit={contentFit}
          transition={150}
          onLoad={() => setStatus('loaded')}
          onError={() => setStatus('error')}
          recyclingKey={url}
        />
      ) : null}

      {status === 'loading' && (
        <View style={[StyleSheet.absoluteFill, styles.center]}>
          <ActivityIndicator size="small" color={theme.mutedDim} />
        </View>
      )}

      {status === 'empty' && (
        <View style={[StyleSheet.absoluteFill, styles.center]}>
          <Text style={styles.glyph}>{emptyGlyph}</Text>
        </View>
      )}

      {status === 'error' && (
        <View style={[StyleSheet.absoluteFill, styles.center]}>
          {/* Błąd ładowania (np. wygasła sxyprn/trafficdeposit miniaturka, 404) →
              czysty placeholder jak 'empty', nie alarmowe ⚠ (bug 2026-06-10). */}
          <Text style={styles.glyph}>{emptyGlyph}</Text>
        </View>
      )}
    </View>
  );
}

const styles = StyleSheet.create({
  wrap: {
    backgroundColor: theme.bgElevated,
    borderRadius: 8,
    overflow: 'hidden',
  },
  center: { alignItems: 'center', justifyContent: 'center' },
  glyph: { fontSize: 24, opacity: 0.4 },
  glyphError: { fontSize: 22, color: theme.bad, opacity: 0.7 },
});
