import {
  View, Text, FlatList, TextInput, TouchableOpacity, RefreshControl, StyleSheet,
} from 'react-native'
import { SafeAreaView } from 'react-native-safe-area-context'
import { useRouter } from 'expo-router'
import { Ionicons } from '@expo/vector-icons'
import { useMembersList } from '@/hooks/useMembers'
import { useMembersFilterStore } from '@/store/members.store'
import { MemberCard } from '@/components/members/MemberCard'
import { EmptyState } from '@/components/ui/EmptyState'
import { LoadingSpinner } from '@/components/ui/LoadingSpinner'

export default function MembersScreen() {
  const router = useRouter()
  const search = useMembersFilterStore((s) => s.search)
  const nurAusbildungsbetriebe = useMembersFilterStore((s) => s.nurAusbildungsbetriebe)
  const setSearch = useMembersFilterStore((s) => s.setSearch)
  const setNurAusbildungsbetriebe = useMembersFilterStore((s) => s.setNurAusbildungsbetriebe)
  const { data, isLoading, refetch, isRefetching } = useMembersList()

  return (
    <SafeAreaView style={styles.safeArea} edges={['top']}>
      {/* Header */}
      <View style={styles.header}>
        <View style={styles.titleRow}>
          <Text style={styles.screenTitle}>Mitglieder</Text>
          {data && (
            <Text style={styles.countText}>{data.length} gesamt</Text>
          )}
        </View>

        {/* Search bar */}
        <View style={styles.searchBar}>
          <Ionicons name="search-outline" size={16} color="#64748B" />
          <TextInput
            style={styles.searchInput}
            placeholder="Name, Betrieb, Ort, Sparte ..."
            placeholderTextColor="#64748B"
            value={search}
            onChangeText={setSearch}
            clearButtonMode="while-editing"
          />
        </View>

        {/* Training filter */}
        <TouchableOpacity
          onPress={() => setNurAusbildungsbetriebe(!nurAusbildungsbetriebe)}
          style={styles.toggleRow}
          activeOpacity={0.7}
        >
          <View style={[styles.checkbox, nurAusbildungsbetriebe && styles.checkboxActive]}>
            {nurAusbildungsbetriebe && (
              <Ionicons name="checkmark" size={11} color="#FFFFFF" />
            )}
          </View>
          <Text style={styles.toggleLabel}>Nur Ausbildungsbetriebe</Text>
        </TouchableOpacity>
      </View>

      <View style={styles.divider} />

      {isLoading ? (
        <LoadingSpinner />
      ) : (
        <FlatList
          data={data ?? []}
          keyExtractor={(item) => item.id}
          contentContainerStyle={styles.list}
          initialNumToRender={10}
          maxToRenderPerBatch={10}
          windowSize={5}
          refreshControl={
            <RefreshControl refreshing={isRefetching} onRefresh={refetch} tintColor="#003B7E" progressViewOffset={50} />
          }
          renderItem={({ item }) => (
            <MemberCard
              member={item}
              onPress={() => router.push(`/(app)/members/${item.id}` as never)}
            />
          )}
          ListEmptyComponent={
            <EmptyState
              icon="people-outline"
              title="Keine Mitglieder"
              subtitle={search ? 'Keine Treffer für deine Suche' : 'Noch keine Mitglieder eingetragen'}
            />
          }
        />
      )}
    </SafeAreaView>
  )
}

const styles = StyleSheet.create({
  safeArea: {
    flex: 1,
    backgroundColor: '#F8FAFC',
  },
  header: {
    backgroundColor: '#FFFFFF',
    paddingHorizontal: 20,
    paddingTop: 18,
    paddingBottom: 14,
  },
  titleRow: {
    flexDirection: 'row',
    alignItems: 'baseline',
    justifyContent: 'space-between',
    marginBottom: 14,
  },
  screenTitle: {
    fontSize: 28,
    fontWeight: '800',
    color: '#0F172A',
    letterSpacing: -0.5,
  },
  countText: {
    fontSize: 13,
    color: '#64748B',
    fontWeight: '500',
  },
  searchBar: {
    flexDirection: 'row',
    alignItems: 'center',
    backgroundColor: '#F4F4F5',
    borderRadius: 14,
    paddingHorizontal: 12,
    paddingVertical: 11,
    gap: 8,
    marginBottom: 10,
  },
  searchInput: {
    flex: 1,
    fontSize: 14,
    color: '#0F172A',
  },
  toggleRow: {
    flexDirection: 'row',
    alignItems: 'center',
    gap: 8,
    paddingTop: 2,
  },
  checkbox: {
    width: 18,
    height: 18,
    borderRadius: 5,
    borderWidth: 1.5,
    borderColor: '#D4D4D8',
    backgroundColor: '#FFFFFF',
    alignItems: 'center',
    justifyContent: 'center',
  },
  checkboxActive: {
    backgroundColor: '#003B7E',
    borderColor: '#003B7E',
  },
  toggleLabel: {
    fontSize: 13,
    color: '#52525B',
    fontWeight: '500',
  },
  divider: {
    height: 1,
    backgroundColor: '#E2E8F0',
  },
  list: {
    padding: 16,
    gap: 10,
  },
})
