import AsyncStorage from '@react-native-async-storage/async-storage';
import AppText from 'components/AppText';
import LayoutTwo from 'components/LayoutTwo';
import NoResult from 'components/NoResult';
import * as React from 'react';
import { useTranslation } from 'react-i18next';
import {
  RefreshControl,
  ScrollView,
  StyleSheet,
  TouchableOpacity,
} from 'react-native';
import Clock from 'svg/Clock';
import { NotificationsData } from '../lib/data';
import NotificationsModal from './NotificationsModal';

const Notifications = () => {
  const [notifications, setNotifications] = React.useState<NotificationsData[]>(
    [],
  );
  const [refreshing, setRefreshing] = React.useState(false);
  const [modalVisible, setModalVisible] = React.useState(false);
  const { t } = useTranslation();
  const [selectedOrder, setSelectedOrder] =
    React.useState<NotificationsData | null>(null);

  const onRefresh = React.useCallback(() => {
    setRefreshing(true);
    setTimeout(() => {
      setRefreshing(false);
    }, 1500);
  }, []);

  const openModal = React.useCallback((item: NotificationsData) => {
    setSelectedOrder(item);
    setModalVisible(true);
  }, []);

  const refreshControl = React.useMemo(
    () => <RefreshControl refreshing={refreshing} onRefresh={onRefresh} />,
    [refreshing, onRefresh],
  );

  const loadNotifications = async () => {
    const stored = await AsyncStorage.getItem('notifications');
    if (stored) {
      setNotifications(JSON.parse(stored));
    }
  };

  React.useEffect(() => {
    const unsubscribe = loadNotifications();
    return () => {
      unsubscribe;
    };
  }, []);

  return (
    <LayoutTwo title={t('Bildirishnomalar')}>
      <ScrollView
        keyboardShouldPersistTaps="handled"
        refreshControl={refreshControl}
      >
        {notifications.length > 0 ? (
          notifications.map(item => (
            <TouchableOpacity
              onPress={() => openModal(item)}
              style={styles.card}
              key={item.id}
            >
              <AppText style={styles.text}>{item.message}</AppText>
              <Clock color="#000000" />
            </TouchableOpacity>
          ))
        ) : (
          <NoResult />
        )}
      </ScrollView>
      <NotificationsModal
        visible={modalVisible}
        setVisible={setModalVisible}
        selectedOrder={selectedOrder}
      />
    </LayoutTwo>
  );
};

export default Notifications;

const styles = StyleSheet.create({
  card: {
    borderBottomWidth: 1,
    borderColor: '#D8DADC',
    width: '95%',
    marginLeft: 'auto',
    marginRight: 'auto',
    marginTop: 20,
    paddingBottom: 18,
    paddingLeft: 12,
    paddingRight: 12,
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'space-between',
  },
  text: {
    fontSize: 18,
    fontWeight: '400',
    width: '80%',
  },
});
