import {
  View, Text, FlatList, TouchableOpacity, RefreshControl, StyleSheet,
} from 'react-native'
import { SafeAreaView } from 'react-native-safe-area-context'
import { useState } from 'react'
import { useRouter } from 'expo-router'
import { useTermineListe, useToggleAnmeldung } from '@/hooks/useTermine'
import { TerminCard } from '@/components/termine/TerminCard'
import { EmptyState } from '@/components/ui/EmptyState'
import { LoadingSpinner } from '@/components/ui/LoadingSpinner'

type Tab = 'kommend' | 'vergangen'

export default function TermineScreen() {
  const router = useRouter()
  const [tab, setTab] = useState<Tab>('kommend')
  const { data, isLoading, refetch, isRefetching } = useTermineListe(tab === 'kommend')
  const { mutate, isPending } = useToggleAnmeldung()

  return (
    <SafeAreaView style={styles.safeArea} edges={['top']}>
      {/* Header */}
      <View style={styles.header}>
        <Text style={styles.screenTitle}>Termine</Text>

        {/* Segment control */}
        <View style={styles.segmentContainer}>
          {(['kommend', 'vergangen'] as Tab[]).map((t) => {
            const active = tab === t
            return (
              <TouchableOpacity
                key={t}
                onPress={() => setTab(t)}
                style={[styles.segment, active && styles.segmentActive]}
                activeOpacity={0.8}
              >
                <Text style={[styles.segmentLabel, active && styles.segmentLabelActive]}>
                  {t === 'kommend' ? 'Bevorstehend' : 'Vergangen'}
                </Text>
              </TouchableOpacity>
            )
          })}
        </View>
      </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 }) => (
            <TerminCard
              termin={item}
              isPast={tab === 'vergangen'}
              onPress={() => router.push(`/(app)/termine/${item.id}` as never)}
              onToggleAnmeldung={() => mutate({ terminId: item.id })}
              isToggling={isPending}
            />
          )}
          ListEmptyComponent={
            <EmptyState
              icon="calendar-outline"
              title="Keine Termine"
              subtitle={
                tab === 'kommend'
                  ? 'Aktuell keine bevorstehenden Termine'
                  : 'Keine vergangenen Termine'
              }
            />
          }
        />
      )}
    </SafeAreaView>
  )
}

const styles = StyleSheet.create({
  safeArea: {
    flex: 1,
    backgroundColor: '#F8FAFC',
  },
  header: {
    backgroundColor: '#FFFFFF',
    paddingHorizontal: 20,
    paddingTop: 18,
    paddingBottom: 14,
  },
  screenTitle: {
    fontSize: 28,
    fontWeight: '800',
    color: '#0F172A',
    letterSpacing: -0.5,
    marginBottom: 14,
  },
  segmentContainer: {
    flexDirection: 'row',
    backgroundColor: '#F4F4F5',
    borderRadius: 14,
    padding: 3,
    gap: 3,
  },
  segment: {
    flex: 1,
    paddingVertical: 9,
    borderRadius: 11,
    alignItems: 'center',
  },
  segmentActive: {
    backgroundColor: '#FFFFFF',
    shadowColor: '#000',
    shadowOffset: { width: 0, height: 1 },
    shadowOpacity: 0.08,
    shadowRadius: 4,
    elevation: 2,
  },
  segmentLabel: {
    fontSize: 13,
    fontWeight: '500',
    color: '#64748B',
  },
  segmentLabelActive: {
    color: '#0F172A',
    fontWeight: '600',
  },
  divider: {
    height: 1,
    backgroundColor: '#E2E8F0',
  },
  list: {
    padding: 16,
    gap: 10,
  },
})
