import React, { useEffect, useState, useCallback } from 'react';
import { View, StyleSheet, ScrollView, TouchableOpacity, Image, ActivityIndicator, RefreshControl } from 'react-native';
import { router } from 'expo-router';
import { useFocusEffect } from '@react-navigation/native';
import { SafeAreaView } from 'react-native-safe-area-context';
import { Ionicons } from '@expo/vector-icons';
import { FLEX, COLOR_SCALES } from '@/theme';
import Text from '@/components/common/Text';
import ProfileHeader from '@/components/common/ProfileHeader';
import Loading from '@/components/common/Loading';
import Empty from '@/components/common/Empty';
import Toast from '@/components/common/Toast';
import useToast from '@/hooks/useToast';
import { getNotification, deleteNotification } from '@/services/user';
export default function NotificationsScreen() {
  const [notifications, setNotifications] = useState([]);
  const [isLoading, setIsLoading] = useState(true);
  const { toast, showSuccessToast, showErrorToast, hideToast } = useToast();

  const formatDateTime = useCallback((isoString) => {
    if (!isoString) return '';
    try {
      const d = new Date(isoString);
      const day = String(d.getDate()).padStart(2, '0');
      const month = String(d.getMonth() + 1).padStart(2, '0');
      const year = d.getFullYear();
      const hours = String(d.getHours()).padStart(2, '0');
      const minutes = String(d.getMinutes()).padStart(2, '0');
      return `${day}.${month}.${year} ${hours}:${minutes}`;
    } catch (_e) {
      return '';
    }
  }, []);

  const loadNotifications = useCallback(async () => {
    try {
      setIsLoading(true);
      const res = await getNotification();
      const list = res?.data ?? [];
      setNotifications(Array.isArray(list) ? list : []);
    } catch (_e) {
      setNotifications([]);
    } finally {
      setIsLoading(false);
    }
  }, []);

  useEffect(() => {
    loadNotifications();
  }, [loadNotifications]);

  useFocusEffect(
    useCallback(() => {
      loadNotifications();
    }, [loadNotifications])
  );

  const [refreshing, setRefreshing] = useState(false);
  const onRefresh = useCallback(async () => {
    try {
      setRefreshing(true);
      await loadNotifications();
    } finally {
      setRefreshing(false);
    }
  }, [loadNotifications]);

  const handleBackPress = () => {
    router.push('/(tabs)/profile');
  };

  const handleDelete = async (id) => {
    try {
      await deleteNotification({ id });
      setNotifications((prev) => prev?.filter((n) => n?.id !== id));
      showSuccessToast({ title: 'Silindi', message: 'Bildirim silindi.' });
    } catch (_e) {
      showErrorToast({ title: 'Hata', message: 'Bildirim silinemedi.' });
    }
  };

  return (
    <SafeAreaView style={styles.container}>
      <ProfileHeader 
        pageTitle="Bildirim"
        showBackButton={true}
        showNotification={false}
        showUserInfo={false}
        onBackPress={handleBackPress}
      />

      <View style={styles.content}>
        {isLoading ? (
          <View style={styles.loaderWrap}>
            <ActivityIndicator size="small" color={COLOR_SCALES.primary[70]} />
          </View>
        ) : notifications?.length > 0 ? (
          <ScrollView 
            style={styles.scrollView} 
            showsVerticalScrollIndicator={false}
            contentContainerStyle={styles.scrollContent}
            refreshControl={
              <RefreshControl
                refreshing={refreshing}
                onRefresh={onRefresh}
                tintColor={COLOR_SCALES.primary[70]}
                colors={[String(COLOR_SCALES.primary[70])]} 
              />
            }
          >
            <View style={styles.notificationsContainer}>
              {notifications?.map((notification) => (
                <View
                  key={notification?.id}
                  style={[styles.notificationItem, styles.whiteCard]}
                >
                  <View style={styles.lokmaIconContainer}>
                    <Image 
                      source={require('@/assets/images/package-lokma.png')}
                      style={styles.lokmaIcon}
                      resizeMode="contain"
                    />
                  </View>

                  <View style={styles.notificationContent}>
                    <Text style={[styles.notificationTitle, styles.redText]}>
                      {notification?.title ?? ''}
                    </Text>
                    <Text style={[styles.notificationMessage, styles.redText]}>
                      {notification?.body ?? ''}
                    </Text>
                    <Text style={styles.timeText}>
                      {formatDateTime(notification?.createdAt)}
                    </Text>
                  </View>

                  <View style={styles.actionIcons}>
                    <TouchableOpacity 
                      style={styles.deleteButton}
                      onPress={() => handleDelete(notification?.id)}
                    >
                      <Ionicons 
                        name="trash-outline" 
                        size={18} 
                        color={COLOR_SCALES.primary[70]} 
                      />
                    </TouchableOpacity>
                  </View>
                </View>
              ))}
            </View>
          </ScrollView>
        ) : (
          <Empty 
            title="Bildirim Bulunamadı" 
            description="Henüz bildiriminiz yok."
            fullscreen={false}
            icon={<Ionicons name="notifications-off-outline" size={48} color={COLOR_SCALES.colorGray[40]} />}
          />
        )}
      </View>
      <Toast 
        visible={toast?.visible}
        title={toast?.title}
        message={toast?.message}
        type={toast?.type}
        duration={toast?.duration}
        onHide={hideToast}
      />
    </SafeAreaView>
  );
}

const styles = StyleSheet.create({
  container: {
    ...FLEX.fill,
    backgroundColor: COLOR_SCALES.gray[10],
  },
  content: {
    flex: 1,
  },
  loaderWrap: {
    flex: 1,
    alignItems: 'center',
    justifyContent: 'center',
  },
  scrollView: {
    flex: 1,
  },
  scrollContent: {
    paddingTop: 12,
  },
  notificationsContainer: {
    paddingBottom: 100,
  },
  notificationItem: {
    flexDirection: 'row',
    alignItems: 'center',
    padding: 12,
    shadowColor: '#000',
    shadowOffset: {
      width: 0,
      height: 2,
    },
    shadowOpacity: 0.1,
    shadowRadius: 4,
    elevation: 3,
    borderRadius: 8,
    marginHorizontal: 14,
    marginBottom: 10,
  },
  whiteCard: {
    backgroundColor: COLOR_SCALES.white.white,
  },
  lokmaIconContainer: {
    width: 36,
    height: 36,
    marginRight: 10,
    alignItems: 'center',
    justifyContent: 'center',
  },
  lokmaIcon: {
    width: 28,
    height: 28,
  },
  notificationContent: {
    flex: 1,
    marginRight: 10,
  },
  notificationMessage: {
    fontSize: 13,
    lineHeight: 18,
    fontWeight: '400',
  },
  notificationTitle: {
    fontSize: 14,
    lineHeight: 20,
    fontWeight: '600',
    marginBottom: 3,
  },
  redText: {
    color: COLOR_SCALES.primary[70],
  },
  timeText: {
    fontSize: 11,
    color: COLOR_SCALES.colorGray[60],
    marginTop: 4,
    alignSelf: 'flex-end',
  },
  actionIcons: {
    alignItems: 'center',
    gap: 8,
  },
  deleteButton: {
    width: 18,
    height: 18,
    alignItems: 'center',
    justifyContent: 'center',
  },
}); 