import {
  View,
  Text,
  FlatList,
  TouchableOpacity,
  RefreshControl,
} from 'react-native'
import { SafeAreaView } from 'react-native-safe-area-context'
import { useRouter } from 'expo-router'
import { trpc } from '@/lib/trpc'
import { StelleCard } from '@/components/stellen/StelleCard'
import { EmptyState } from '@/components/ui/EmptyState'
import { LoadingSpinner } from '@/components/ui/LoadingSpinner'
import { useAuth } from '@/hooks/useAuth'

export default function StellenScreen() {
  const router = useRouter()
  const { isAuthenticated } = useAuth()
  const { data, isLoading, refetch, isRefetching } = trpc.stellen.listPublic.useQuery({})

  return (
    <SafeAreaView className="flex-1 bg-gray-50" edges={['top']}>
      {/* Header */}
      <View className="bg-white px-4 pt-3 pb-3 border-b border-gray-100">
        <View className="flex-row items-center justify-between">
          <View>
            <Text className="text-xl font-bold text-gray-900">Lehrlingsbörse</Text>
            <Text className="text-sm text-gray-500 mt-0.5">
              {data?.length ?? 0} Angebote
            </Text>
          </View>
          {isAuthenticated && (
            <TouchableOpacity
              onPress={() => router.push('/(app)/stellen/neu')}
              className="bg-brand-500 px-4 py-2 rounded-xl"
            >
              <Text className="text-white text-sm font-medium">+ Stelle anbieten</Text>
            </TouchableOpacity>
          )}
        </View>
      </View>

      {isLoading ? (
        <LoadingSpinner />
      ) : (
        <FlatList
          data={data ?? []}
          keyExtractor={(item) => item.id}
          contentContainerStyle={{ padding: 12, gap: 8 }}
          refreshControl={
            <RefreshControl
              refreshing={isRefetching}
              onRefresh={refetch}
              tintColor="#E63946"
            />
          }
          renderItem={({ item }) => (
            <StelleCard
              stelle={item}
              onPress={() => router.push(`/(app)/stellen/${item.id}`)}
            />
          )}
          ListEmptyComponent={
            <EmptyState
              icon="🎓"
              title="Keine Angebote"
              subtitle="Aktuell sind keine Ausbildungsplätze verfügbar"
            />
          }
        />
      )}
    </SafeAreaView>
  )
}
