import React, { useEffect, useLayoutEffect } from 'react';
import {
  View,
  Text,
  FlatList,
  TouchableOpacity,
} from 'react-native';
import { useNavigation } from '@react-navigation/native';
import Icon from 'react-native-vector-icons/Ionicons';
import { useTheme } from '@theme';
import { getStyles } from './notification.styles';
import { useAppDispatch, useAppSelector, RootState } from '@store';
import { getStaffNotifications, markNotificationRead, clearNotifications } from './thunk';
import { NotificationItem as NotificationItemType } from '@interfaces';
import { Loader, NotificationItem } from '@components';
import { navigateToLeadDetails } from '@utils';


export const NotificationScreen = () => {
  const dispatch = useAppDispatch();
  const navigation = useNavigation();
  const { theme: colors } = useTheme();
  const styles = getStyles(colors);

  const { items, loading, error } = useAppSelector(
    (state: RootState) => state.notifications,
  );
  const user_data = useAppSelector((state: RootState) => state.auth.user_data);

  useEffect(() => {
    if (user_data?.staffid) {
      dispatch(getStaffNotifications(user_data.staffid));
    }
  }, [dispatch, user_data]);

  useLayoutEffect(() => {
    navigation.setOptions({
      headerTitle: 'Notifications',
      headerRight: () => {
        const hasUnread = items.some(n => String(n.isread) === '0');
        if (!hasUnread) return null;
        return (
          <TouchableOpacity
            style={styles.headerRightBtn}
            onPress={() => {
              if (user_data?.staffid) {
                dispatch(clearNotifications(user_data.staffid));
              }
            }}
            activeOpacity={0.7}
          >
            <Text style={styles.clearAllText}>Clear All</Text>
          </TouchableOpacity>
        );
      },
    });
  }, [navigation, items, styles]);

  const handleNotificationPress = (item: NotificationItemType) => {
    if (String(item.isread) === '0' && user_data?.staffid) {
      dispatch(
        markNotificationRead({
          staffId: user_data.staffid,
          notificationId: item.id,
        }),
      );
    }
    
    if (item.link) {
      const match = item.link.match(/#leadid=(\d+)/);
      if (match) {
        const leadId = match[1];
        navigateToLeadDetails(leadId);
      }
    }
  };

  const renderItem = ({ item }: { item: NotificationItemType }) => {
    return <NotificationItem item={item} onPress={handleNotificationPress} />;
  };

  if (loading) {
    return <Loader message="Loading notifications..." />;
  }

  if (error) {
    return (
      <View style={styles.emptyContainer}>
        <Icon name="alert-circle-outline" size={48} color={colors.textMuted} />
        <Text style={styles.emptyTitle}>{error}</Text>
        {/* <Text style={styles.emptySubtitle}>{error}</Text> */}
      </View>
    );
  }

  return (
    <View style={styles.container}>
        <FlatList
          data={items}
          keyExtractor={item => item.id}
          renderItem={renderItem}
          contentContainerStyle={styles.listContent}
          showsVerticalScrollIndicator={false}
        />
    </View>
  );
};
