import React from 'react';
import { View, Text, TouchableOpacity, Pressable, FlatList, StyleSheet } from 'react-native';
import { useTodoState, getFilteredTodos } from '../state';
import { colors } from '../theme';
import FilterBar from './FilterBar';
import TodoItem from './TodoItem';

function EmptyState() {
  return (
    <View style={styles.emptyContainer}>
      <Text style={styles.emptyIcon}>{'\uD83D\uDCDD'}</Text>
      <Text style={styles.emptyText}>{'No todos yet!\nTap + to add one'}</Text>
    </View>
  );
}

function TodoList() {
  const { state } = useTodoState();
  const todos = getFilteredTodos(state);

  if (todos.length === 0) {
    return <EmptyState />;
  }

  return (
    <FlatList
      data={todos}
      renderItem={({ item }) => <TodoItem todo={item} />}
      keyExtractor={item => String(item.id)}
      contentContainerStyle={{ paddingBottom: 100 }}
    />
  );
}

export default function MainScreen() {
  const { dispatch } = useTodoState();

  return (
    <View style={styles.container}>
      <View style={styles.header}>
        <Text style={styles.headerText}>Todos – JS Expo</Text>
      </View>
      <FilterBar />
      <View style={{ flex: 1 }}>
        <TodoList />
      </View>
      <Pressable
        onPress={() => dispatch({ type: 'SHOW_ADD_FORM' })}
        style={styles.fab}
      >
        <Text style={styles.fabText}>+</Text>
      </Pressable>
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: colors.background,
  },
  header: {
    backgroundColor: colors.primary,
    paddingTop: 48,
    paddingBottom: 16,
    paddingHorizontal: 24,
  },
  headerText: {
    fontSize: 28,
    fontWeight: 'bold',
    color: colors.onPrimary,
  },
  fab: {
    position: 'absolute',
    right: 24,
    bottom: 32,
    zIndex: 10,
    width: 56,
    height: 56,
    borderRadius: 28,
    backgroundColor: colors.primary,
    justifyContent: 'center',
    alignItems: 'center',
    elevation: 6,
    shadowColor: '#000',
    shadowOffset: { width: 0, height: 3 },
    shadowOpacity: 0.3,
    shadowRadius: 4,
  },
  fabText: {
    color: '#FFFFFF',
    fontSize: 28,
    lineHeight: 30,
  },
  emptyContainer: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    padding: 48,
  },
  emptyIcon: {
    fontSize: 48,
    marginBottom: 16,
  },
  emptyText: {
    fontSize: 18,
    color: colors.textSecondary,
    textAlign: 'center',
  },
});
