import { View, Text, Platform, StyleSheet, FlatList, Image, TouchableOpacity } from 'react-native';
import React, { useEffect, useState } from 'react';
import Container from '../components/container';
import CustomHeader from '../components/customHeader';
import { connect } from 'react-redux';
import { mapDispatchToProps, mapStateToProps } from '../reducers/contextProvider';
import IMAGES from '../constants/Images';
import NOTIFICATIONAPISERVICES from '../NotificationApiService';
import { get_item } from '../components/localStorage';
import { notify } from '../components/notify';
import moment from 'moment';
import CustomLoader from '../components/CustomLoader';

const NotificationList = (props) => {

  const [list , setList] = useState([]);
  const [processing, setProcessing] = useState(true);

  const updatereadstatus = async (item) => {

    try {
        const data = { NotificationId : item?.NotificationId};

        NOTIFICATIONAPISERVICES.updatenotificationreadstatus.post(data)
            .then(async  res => {
              console.log(res, "response?////// of read status")
              if (!res.UpdateNotificationReadStatus) {
                notify('Invalid response format', 'SHORT');
                return;
               }
               const updateInfo = res?.UpdateNotificationReadStatus?.length > 0 ? res?.UpdateNotificationReadStatus[0] : {};
               const status = updateInfo?.Status;
               const message = updateInfo?.Message || '';
               if (status === 1) {
               // navigate
               props?.navigation.navigate('NotificationListDetail', { notificationdata: { ...item } });
               getNotificationList();

              } 
              else if (status === 0) {
                notify(message,'SHORT');
              } 
              else {
                  notify(`Status: ${status} with message: ${message}`, 'SHORT');
              }
            })
            .catch(err => {
                console.error(err);
                notify('Something went wrong. Please try again later.','SHORT');
            });
          } catch (error) {
              console.error(error);
              notify('Failed to retrieve information.','LONG');
          }
  };

  const getNotificationList = async () => {
    setProcessing(true);
    try {
        let projectInfo = await get_item('projectInfo');
        let projectDetails = projectInfo != null ? JSON.parse(projectInfo) : {};

        let loginInfo = await get_item('loginInfo');
        const loginDetails = JSON.parse(loginInfo);
        const data = { UserName: loginDetails?.UserId, ProjectCode: projectDetails?.ProjectCode };

        NOTIFICATIONAPISERVICES.getnotificationlist.post(data)
            .then(async  res => {
              setProcessing(false);
              console.log(res, "response?////// readddd")
              if (!res.GetNotificationListofUser) {
                notify('Invalid response format', 'SHORT');
                return;
               }
               const notificationInfo = res?.GetNotificationListofUser ? res?.GetNotificationListofUser : {};
               const status = notificationInfo?.Status;
               const message = notificationInfo?.Message || '';

               console.log(notificationInfo, "statusInfo")
                if (status === 1) {
                  setList(notificationInfo?.Data);

                } 
                else if (status === 2) {
                    notify(message,'SHORT');
                } 
                else {
                    notify(`Status: ${status} with message: ${message}`, 'SHORT');
                }
             
            })
            .catch(err => {
                console.error(err);
                setProcessing(false);
                notify('Something went wrong. Please try again later.','SHORT');
            });
          } catch (error) {
              setProcessing(false);
              console.error(error);
              notify('Failed to retrieve notification information.','LONG');
          }
  };

  const renderNotification = ({ item }) => {
    const { Title, msg, ReadStatus , Icon , DateTime} = item;
    return (
      <View style={styles.notificationWrapper}>
      
        <View style={styles.readTag}>
          {!ReadStatus && <Image style={styles.readTagImage} source={IMAGES.read_tag_icon} />}
        </View>
        <View style={styles.notifyData}>
          <TouchableOpacity onPress={() => updatereadstatus(item)}>
            <View style={styles.notifyItem}>
              <Image style={styles.notificationIcon} source={IMAGES.p_notification_icon} />
              <View style={styles.itemData}>
                <Text style={styles.title} numberOfLines={2}>{Title}</Text>
                <Text style={ !ReadStatus ? [styles.body] : [styles.body, {color:'#8F8F8F'}] } numberOfLines={3}>{msg}</Text>
                <View style={styles.timestamp}>
                  <Text style={styles.time}>{moment(DateTime).format('MMM DD, YYYY')}</Text>
                  <View style={styles.dot} />
                  <Text style={styles.time}>{moment(DateTime).format('HH:mm')}</Text>
                </View>
              </View>
            </View>
          </TouchableOpacity>
        </View>
      </View>
    );
  };

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

  return (
    <Container {...props} pt={0} avoidSafeArea={Platform.OS === 'ios'}>
    
      <CustomHeader {...props}showaddstore={true} title="Notification" screen="NotificationList" />
      <View style={styles.footer}>
      {processing ? (
        <CustomLoader title="Loading" />
      ) : list?.length > 0 ? (
        <FlatList
          contentContainerStyle={styles.flatListContent}
          data={list}
          keyExtractor={(item) => item?.NotificationId?.toString()}
          ItemSeparatorComponent={() => <View style={styles.itemSeparator} />}
          renderItem={renderNotification}
        />
      ) : (
        <View style={styles.emptyCartContainer}>
          <Image style={styles.NOnotificationIcon} source={IMAGES.noNotification_icon} />
          <Text style={styles.emptyCartMessage}>No Notifications</Text>
        </View>
      )}
      </View>
    </Container>
  );
};

export default connect(mapStateToProps, mapDispatchToProps)(NotificationList);

const styles = StyleSheet.create({
  footer: {
    flex: 5,
    width: "100%",
    backgroundColor: "#f2f5f7",
    paddingBottom: 15,
    paddingTop: 10,
  },
  emptyCartContainer: {
    marginTop: 250,
    justifyContent: "center",
    alignItems: "center",
  },
  emptyCartMessage: {
    fontSize: 20,
    color: '#000',
    marginTop:10
  },
  body: {
    fontSize: 14,
    paddingTop: 5,
    color: "#000",
    textAlign: "left",
  },
  title: {
    color: '#000',
    fontWeight: "600",
    fontSize: 16,
  },
  notifyData: {
    padding: 8,
    backgroundColor: "#fff",
    shadowOpacity: 0.22,
    shadowRadius: 2.22,
    elevation: 1,
    borderRadius: 8,
  },
  notifyItem: {
    padding: 1,
    marginTop: 5,
    backgroundColor: "#fff",
    flexDirection: "row",
    marginHorizontal: 5,
    alignItems: 'center',
  },
  itemData: {
    flex: 3,
    marginHorizontal: 10,
    flexDirection: "column",
  },
  time: {
    fontSize: 12,
    paddingTop: 5,
    color: "#8F8F8F",
    textAlign: "left",
  },
  notificationIcon: {
    height: 40,
    width: 40,
  },
  NOnotificationIcon: {
    height: 80,
    width: 80,
    resizeMode : 'contain',
    tintColor : '#8BB5D3'
  },
  timestamp: {
    flexDirection: 'row',
    alignItems: 'center',
  },
  dot: {
    width: 8,
    height: 8,
    backgroundColor: '#8F8F8F',
    borderRadius: 50,
    marginTop: 5,
    marginHorizontal: 6,
  },
  flatListContent: {
    paddingBottom: 50,
  },
  itemSeparator: {
    paddingVertical: 6,
  },
  notificationWrapper: {
    marginHorizontal: 10,
  },
  readTag: {
    position: 'absolute',
    zIndex: 100,
  },
  readTagImage: {
    height: 25,
    width: 30,
    borderTopLeftRadius: 8,
    resizeMode: 'cover',
  },
});
