import { useQuery } from '@tanstack/react-query';
import { router } from 'expo-router';
import { MaterialCommunityIcons } from '@expo/vector-icons';
import { useEffect } from 'react';
import { ActivityIndicator, Pressable, RefreshControl, ScrollView, StyleSheet, Text, View } from 'react-native';
import { SafeAreaView } from 'react-native-safe-area-context';
import { ScreenHeader } from '../../src/components/ScreenHeader';
import { api } from '../../src/lib/api';
import { getCustomer } from '../../src/lib/session';

export default function NotificationsScreen() {
  const customerQuery = useQuery({ queryKey: ['customer'], queryFn: getCustomer });
  const notificationsQuery = useQuery({
    queryKey: ['notifications', customerQuery.data?.id],
    enabled: !!customerQuery.data?.id,
    queryFn: async () => {
      const response = await api.get('/notifications/index', { params: { customer_id: customerQuery.data?.id } });
      return response.data?.data;
    },
  });

  useEffect(() => {
    if (!customerQuery.isLoading && !customerQuery.data) router.replace('/auth/login');
  }, [customerQuery.data, customerQuery.isLoading]);

  const markAllRead = async () => {
    await api.post('/notifications/mark-read', { customer_id: customerQuery.data?.id });
    await notificationsQuery.refetch();
  };

  if (customerQuery.isLoading || notificationsQuery.isLoading) {
    return <View style={styles.loading}><ActivityIndicator size="large" color="#16A34A" /></View>;
  }

  const notifications = notificationsQuery.data?.notifications ?? [];

  return (
    <SafeAreaView style={styles.safeArea} edges={['top']}>
      <ScrollView
        style={styles.container}
        contentContainerStyle={styles.content}
        refreshControl={<RefreshControl refreshing={notificationsQuery.isFetching} onRefresh={() => notificationsQuery.refetch()} tintColor="#16A34A" />}
        showsVerticalScrollIndicator={false}
      >
        <ScreenHeader title="Notifications" subtitle="Your latest alerts and account updates." onBack={() => router.back()} />
        <Pressable style={styles.markReadButton} onPress={markAllRead}>
          <Text style={styles.markReadText}>Mark all as read</Text>
        </Pressable>
        {notifications.length === 0 ? (
          <View style={styles.emptyCard}>
            <MaterialCommunityIcons name="bell-outline" size={30} color="#94A3B8" />
            <Text style={styles.emptyText}>No notifications yet</Text>
          </View>
        ) : (
          notifications.map((note: any) => (
            <View key={note.id} style={[styles.card, note.is_read ? null : styles.unreadCard]}>
              <View style={styles.row}>
                <Text style={styles.title}>{note.type || 'Alert'}</Text>
                <Text style={styles.time}>{String(note.created_at).replace('T', ' ').slice(0, 16)}</Text>
              </View>
              <Text style={styles.message}>{note.message}</Text>
              {note.reference_id ? <Text style={styles.reference}>Ref: {note.reference_id}</Text> : null}
            </View>
          ))
        )}
      </ScrollView>
    </SafeAreaView>
  );
}

const styles = StyleSheet.create({
  safeArea: { flex: 1, backgroundColor: '#F4FAF7' },
  container: { flex: 1, backgroundColor: '#F4FAF7' },
  content: { padding: 20, paddingBottom: 40 },
  loading: { flex: 1, alignItems: 'center', justifyContent: 'center', backgroundColor: '#F4FAF7' },
  markReadButton: { alignSelf: 'flex-start', backgroundColor: '#E8F5EC', paddingHorizontal: 14, paddingVertical: 10, borderRadius: 14, marginBottom: 14 },
  markReadText: { color: '#0F5132', fontWeight: '800' },
  emptyCard: { alignItems: 'center', gap: 8, backgroundColor: '#FFFFFF', borderRadius: 20, padding: 28, borderWidth: 1, borderColor: '#D8E7DF' },
  emptyText: { color: '#64748B', fontWeight: '700' },
  card: { backgroundColor: '#FFFFFF', borderRadius: 20, padding: 16, borderWidth: 1, borderColor: '#E3EFE8', marginBottom: 12 },
  unreadCard: { borderColor: '#86EFAC', backgroundColor: '#F0FDF4' },
  row: { flexDirection: 'row', justifyContent: 'space-between', gap: 12 },
  title: { color: '#062117', fontWeight: '900', flexShrink: 1 },
  time: { color: '#64748B', fontSize: 12 },
  message: { marginTop: 8, color: '#475569', lineHeight: 20 },
  reference: { marginTop: 8, color: '#0F5132', fontWeight: '700' },
});
