import React, { useCallback, useEffect, useState } from 'react';
import { View, Text, ScrollView, Pressable, StyleSheet, RefreshControl } from 'react-native';
import { useSafeAreaInsets } from 'react-native-safe-area-context';
import { CATEGORIES, categoryLabel, type Category, type PostSummary } from '@ai-radar/shared';
import { useTheme } from '../theme/ThemeProvider';
import { textStyle, space, radius, categoryColor } from '../theme';
import { getDict } from '../lib/dictionary';
import { getCategory, ApiError } from '../lib/api';
import { StoryCard } from '../components/StoryCard';
import { Loading, ErrorState, EmptyState } from '../components/States';

/**
 * Sections.
 *
 * A category picker over a list. Kept to one screen rather than a tab
 * per category: six top-level tabs would imply the categories matter
 * equally, and they do not — most days are models and updates.
 */
export function SectionsScreen({ onOpen }: { onOpen: (post: PostSummary) => void }) {
  const { palette, locale, rtl } = useTheme();
  const dict = getDict(locale);
  const insets = useSafeAreaInsets();

  const [active, setActive] = useState<Category>('model');
  const [posts, setPosts] = useState<PostSummary[]>([]);
  const [loading, setLoading] = useState(true);
  const [refreshing, setRefreshing] = useState(false);
  const [error, setError] = useState<string | null>(null);

  const load = useCallback(
    async (category: Category, mode: 'initial' | 'refresh' = 'initial') => {
      if (mode === 'refresh') setRefreshing(true);
      else setLoading(true);
      setError(null);

      try {
        const data = await getCategory(category, locale);
        setPosts(data.posts);
      } catch (err) {
        setError(err instanceof ApiError ? err.message : 'Something went wrong.');
      } finally {
        setLoading(false);
        setRefreshing(false);
      }
    },
    [locale],
  );

  useEffect(() => {
    void load(active);
  }, [active, load]);

  return (
    <View style={{ flex: 1, backgroundColor: palette.bg }}>
      <Text
        style={[
          textStyle('display', locale),
          {
            color: palette.text,
            textAlign: rtl ? 'right' : 'left',
            paddingHorizontal: space.s4,
            paddingTop: space.s4,
          },
        ]}
      >
        {dict.sections}
      </Text>

      {/* Horizontal picker. Text-only, coloured per category — the same
          rule as the labels: colour identifies, it does not decorate. */}
      <ScrollView
        horizontal
        showsHorizontalScrollIndicator={false}
        contentContainerStyle={styles.picker}
        style={styles.pickerWrap}
      >
        {CATEGORIES.map((category) => {
          const on = category === active;
          return (
            <Pressable
              key={category}
              onPress={() => setActive(category)}
              accessibilityRole="tab"
              accessibilityState={{ selected: on }}
              style={({ pressed }) => [
                styles.tab,
                {
                  borderColor: on ? categoryColor(category, palette) : palette.border,
                  opacity: pressed ? 0.7 : 1,
                },
              ]}
            >
              <Text
                style={[
                  textStyle('label', locale),
                  { color: on ? categoryColor(category, palette) : palette.text2 },
                ]}
                numberOfLines={1}
              >
                {locale === 'ar'
                  ? categoryLabel(category, locale)
                  : categoryLabel(category, locale).toUpperCase()}
              </Text>
            </Pressable>
          );
        })}
      </ScrollView>

      {loading ? (
        <Loading />
      ) : error ? (
        <ErrorState message={error} onRetry={() => void load(active)} />
      ) : (
        <ScrollView
          contentContainerStyle={[
            styles.list,
            { paddingBottom: insets.bottom + space.s10 },
          ]}
          refreshControl={
            <RefreshControl
              refreshing={refreshing}
              onRefresh={() => void load(active, 'refresh')}
              tintColor={palette.accent}
              colors={[palette.accent]}
            />
          }
        >
          {posts.length === 0 ? (
            <EmptyState title={dict.quietTitle} body={dict.quietBody} />
          ) : (
            posts.map((post) => (
              <StoryCard key={post.slug} post={post} variant="row" onPress={onOpen} />
            ))
          )}
        </ScrollView>
      )}
    </View>
  );
}

const styles = StyleSheet.create({
  pickerWrap: {
    flexGrow: 0,
    marginTop: space.s4,
  },
  picker: {
    paddingHorizontal: space.s4,
    gap: space.s2,
  },
  tab: {
    paddingVertical: space.s2,
    paddingHorizontal: space.s3,
    borderRadius: radius.chip,
    borderWidth: StyleSheet.hairlineWidth,
  },
  list: {
    paddingHorizontal: space.s4,
    paddingTop: space.s4,
  },
});
