import React, {useEffect, useState, useCallback} from 'react';
import {useDispatch, useSelector} from 'react-redux';
import {
  getRandomQuotation,
  getBirthDayUserByDate,
  getUserDirectManagers,
  getCompanyInfo,
  getPersonnel,
  sendNotification,
  getNotificationOfUser,
} from '../../store/actions/UserAction';
import {
  Platform,
  Linking,
  BackHandler,
  Alert,
  View,
  Text,
  TouchableOpacity,
  Image,
} from 'react-native';
import HomeScreen from './HomeScreen';
import Moment from 'moment';
import {launchImageLibrary} from 'react-native-image-picker';
import Swiper from 'react-native-swiper';
import styles from './style';
import {IMAGES, IconProfile} from '../../values/images';
import Toast from 'react-native-toast-message';
import ProfileUserComponent from './components/ProfileUserComponent';
import QuotesComponent from './components/QuotesComponent';

// import {CheckInPage} from '@meunpm/imcheckin';
const HomeContainer = () => {
  const dispatch = useDispatch();
  const userDetails = useSelector(state => state.UserInfo.userInfo);
  const quotation = useSelector(state => state.Quotation.quotation);
  const BirthDay = useSelector(state => state.BirthDayUser.birthday);

  const [arrPersonnel, setArrPersonnel] = useState([]);
  //console.log('userDetails', userDetails);
  const dataBirthday = [
    {
      id: 0,
      name: 'Tiến Dũng',
      position: 'Phó giám đốc',
    },
    {
      id: 1,
      name: 'Vĩnh Lộc',
      position: 'Trưởng phòng nhân sự',
    },
    {
      id: 2,
      name: 'Phước Vũ',
      position: 'Trường phòng test',
    },
    {
      id: 3,
      name: 'Thanh Bình',
      position: 'Trưởng phòng test',
    },
  ];

  const [openView, setOpenView] = useState([
    {enable: false},
    {enable: false},
    {enable: false},
    {enable: false},
  ]);
  const [bdUserCurrentMonth, setArrBdCurrentMonth] = useState();
  const [birthdayOfUser, setBirthOfUser] = useState();
  //deep link imcheckin
  const supportedURL = 'im-checkin://login_step_2';
  const chPlayLink =
    'https://play.google.com/store/apps/details?id=com.imchecking';
  const appStore = 'https://apps.apple.com/vn/app/imcheckin/id1545100199?l=vi';

  {
    /* modal - item birthdayArr - Image*/
  }
  const [modalVisible, setModalVisible] = useState({
    isVisible: false,
    birthdayArr: null,
    day: '',
    managerOpenWish: [],
  });
  const [chooseSetting, setSettingView] = useState({
    isVisible: false,
    view: <QuotesComponent quotation={quotation} />,
    title: 'Slide personnel',
  });
  const [openProfileComponent, setOpenProfileComponent] = useState(false);
  const [openCheckIn, setOpenCheckIn] = useState(false);
  const [imgArr, setImgArr] = useState([]);

  {
    /**wish birthday */
  }
  const [wishTxt, setWishTxt] = useState();
  const [wishList, setWishList] = useState([]);

  // main function
  const loadListPersonnel = async () => {
    const res = await dispatch(getPersonnel());
    if (res && res.length > 0) {
      //console.log(res);
      setArrPersonnel(res);
    }
  };

  const handleOpenDesBirthday = useCallback(
    day => {
      //   console.log(
      //     'bdUserCurrentMonth',
      //     `${day.day < 10 ? `0${day.day}` : `${day.day}`}-${
      //       day.month < 10 ? `0${day.month}` : `${day.month}`
      //     }-${day.year}`,
      //   );
      const formatDate = `${day.day < 10 ? `0${day.day}` : `${day.day}`}-${
        day.month < 10 ? `0${day.month}` : `${day.month}`
      }-${day.year}`;
      let arrBdUser = [];
      let lengthKey = [];
      for (const [key, value] of Object.entries(BirthDay)) {
        if (key.includes(formatDate)) {
          arrBdUser.push(...value);
          value.forEach(item => lengthKey.push({enable: false}));
        }
      }
      // console.log("lengthKey", lengthKey)
      setModalVisible({
        isVisible: true,
        birthdayArr: arrBdUser,
        day: day,
        managerOpenWish: lengthKey,
      });
    },
    [BirthDay],
  );
  const handleCloseDesBirthday = useCallback(() => {
    setModalVisible({
      isVisible: false,
      birthdayArr: null,
      day: '',
      managerOpenWish: [],
    });
  }, []);
  const OpenURLButton = async () => {
    const supported = await Linking.canOpenURL(supportedURL);

    if (supported) {
      // Opening the link with some app, if the URL scheme is "http" the web link should be opened
      // by some browser in the mobile
      await Linking.openURL(supportedURL);
    } else {
      if (Platform.OS === 'ios') {
        await Linking.openURL(appStore);
      } else {
        await Linking.openURL(chPlayLink);
      }
    }
  };
  const openModalHappyBirthday = index => {
    //console.log("item", index)
    let newState = [...openView];
    newState[index].enable = true;
    setOpenView(newState);
    //setOpenView(state => ({ ...state, [openView[index].enable]: true }))
  };
  const closeModalHappyBirthday = index => {
    let newState = [...openView];
    newState[index].enable = false;
    setOpenView(newState);
  };
  const openModalWishBirthday = index => {
    //console.log("item", index)
    let managerOpenWish = [...modalVisible.managerOpenWish];
    managerOpenWish[index].enable = true;
    setModalVisible(prev => ({...prev, managerOpenWish}));
    // console.log("clone", clone)
  };
  const closeModalWishBirthday = index => {
    let managerOpenWish = [...modalVisible.managerOpenWish];
    managerOpenWish[index].enable = false;
    setModalVisible(prev => ({...prev, managerOpenWish}));
  };
  const sendWishBirthday = async (approver, index) => {
    //console.log('user', user);

    if (!wishTxt) {
      return;
    }
    const {imgArr} = modalVisible.birthdayArr[0];
    //console.log('imgArr', imgArr);
    const res = await dispatch(
      sendNotification(
        approver.id,
        userDetails.id,
        imgArr,
        'Lời chúc sinh nhật',
        wishTxt,
        208,
        'sinh nhật',
      ),
    );
    if (res) {
      setWishTxt();
      closeModalWishBirthday(index);
      Toast.show({
        type: 'success',
        text1: `Hệ thống`,
        text2: `Gửi lời chúc thành công`,
        style: {zIndex: 1001},
        visibilityTime: 2000,
      });
    }
  };
  const loadWishUser = async () => {
    const arrNoti = await dispatch(
      getNotificationOfUser(
        `?Filters=${encodeURIComponent(
          `created_at>=${Moment()
            .startOf('year')
            .format('YYYY-MM-DD')},sub_category_type==208`,
        )}`,
      ),
    );

    //console.log('arrNoti', arrNoti);
    if (arrNoti) {
      setWishList(arrNoti);
    }
  };
  const formatDateList = async () => {
    // const tokenUser = await AsyncStorage.getItem(AsyncStorageKeys.userToken);
    //console.log('tokenUser', tokenUser);
    var size = Object.keys(BirthDay).length;
    const today = new Date();
    const formatToday = Moment(today).format('DD-MM-YYYY');
    // console.log(formatToday)
    // console.log('size', size)
    if (size >= 1) {
      let lstBdUser = [];
      for (const [key, value] of Object.entries(BirthDay)) {
        if (value.length > 0) {
          //console.log("key", value)
          if ([key].length > 0) {
            const formatToday = [key];
            const arr = formatToday[0].split('-');
            const res = arr[2] + '-' + arr[1] + '-' + arr[0];
            // console.log('formatToday', arr[2] + '-' + arr[1] + '-' + arr[0])
            lstBdUser.push({
              [res]: {marked: true, dotColor: 'red', activeOpacity: 0},
            });
          }
        }
        if (key.includes(formatToday)) {
          const lengthObj = BirthDay[key];
          //console.log("lengthObj", lengthObj);
          if (lengthObj.length <= 0) {
          } else {
            lengthObj.forEach(o => {
              //console.log("nameUser", name)
              setBirthOfUser(lengthObj);
            });
          }
        }
      }
      //console.log({ ...lstBdUser })
      const convertArr = Object.assign({}, ...lstBdUser);
      setArrBdCurrentMonth(convertArr);
    }
  };
  const getBirthDayUserByMonth = () => {
    const date = new Date();
    const month =
      date.getMonth() > 8 ? date.getMonth() + 1 : '0' + (date.getMonth() + 1);
    //console.log(month)
    dispatch(getBirthDayUserByDate(month, date.getFullYear()));
  };
  const onCalendarChangeMonth = time => {
    dispatch(getBirthDayUserByDate(time.month, time.year));
  };
  const addMoreImgFromGallery = index => {
    launchImageLibrary(
      {
        mediaType: 'photo',
        includeBase64: true,
      },
      response => {
        //console.log('res', response);
        if (!response.didCancel) {
          //console.log('res', response.assets)
          const {assets} = response;
          //console.log('res', assets)
          let clone = modalVisible.birthdayArr;
          //console.log("index", clone[index])
          clone[index].imgArr = assets;
          //console.log('index', clone);

          setModalVisible(prev => ({...prev, birthdayArr: clone}));
          //console.log("index", clone[index])
        }
      },
    );
  };
  // component
  const SlidePersonnel = () => {
    // console.log('arrPersonnel', arrPersonnel);
    return (
      <Swiper
        style={{
          height: 300,
        }}
        showsButtons={false}
        loop={false}
        showsPagination={false}
        autoplay
        autoplayTimeout={5}
        activeDot={
          <View
            style={{
              backgroundColor: '#007aff',
              width: 25,
              height: 8,
              borderRadius: 4,
            }}
          />
        }>
        {arrPersonnel &&
          arrPersonnel.length > 0 &&
          arrPersonnel.map((item, index) => {
            //console.log(item);
            return (
              <View
                key={index}
                style={[
                  styles.viewContent,
                  {
                    justifyContent: 'center',
                    alignItems: 'center',
                  },
                ]}>
                <Image
                  source={
                    (item.cover_image && {
                      uri: 'https://meu.anawork.com' + item.cover_image,
                    }) ||
                    IMAGES.ImageCoverBg
                  }
                  style={styles.coverImage}
                />
                <TouchableOpacity
                  style={styles.viewAvatar}
                  onPress={() => OpenProfileUserComponent(item)}>
                  <Image
                    source={{
                      uri: 'https://meu.anawork.com' + item.avatar,
                    }}
                    style={styles.imgAvatar}
                  />
                </TouchableOpacity>
                <Text style={{color: 'black', fontSize: 18}}>
                  {`${item.first_name} ${
                    item.middle_name ? item.middle_name : ''
                  } ${item.last_name}`}{' '}
                </Text>
                <Text style={{marginBottom: 20}}>{item.position}</Text>
              </View>
            );
          })}
      </Swiper>
    );
  };
  const openCheckInPage = () => {
    // setOpenCheckIn(<CheckInPage />);
  };
  const openSettingView = () => {
    setSettingView(prev => ({
      ...prev,
      isVisible: true,
    }));
  };
  const chooseSettingView = () => {
    if (chooseSetting.title == 'Slide personnel') {
      setSettingView({
        isVisible: false,
        view: <SlidePersonnel />,
        title: 'Quotes',
      });
    } else {
      setSettingView({
        isVisible: false,
        view: <QuotesComponent quotation={quotation} />,
        title: 'Slide personnel',
      });
    }
  };
  const hideMenu = () => {
    setSettingView(prev => ({...prev, isVisible: false}));
  };
  const OpenProfileUserComponent = info => {
    //console.log('info', info);
    return setOpenProfileComponent(
      <ProfileUserComponent
        userDetails={info}
        onClose={onCloseProfileComponent}
      />,
    );
  };
  const onCloseProfileComponent = () => {
    //console.log('onCloseProfileComponent');
    return setOpenProfileComponent();
  };

  // useEffect
  useEffect(() => {
    const backAction = () => {
      Alert.alert('Hold on!', 'Are you sure you want to go back?', [
        {
          text: 'Cancel',
          onPress: () => null,
          style: 'cancel',
        },
        {text: 'YES', onPress: () => BackHandler.exitApp()},
      ]);
      return true;
    };

    const backHandler = BackHandler.addEventListener(
      'hardwareBackPress',
      backAction,
    );
    let time = setTimeout(() => dispatch(getRandomQuotation()), 20000);
    getBirthDayUserByMonth();
    loadWishUser();
    dispatch(getUserDirectManagers());
    loadListPersonnel();
    return () => {
      clearTimeout(time);
      backHandler.remove();
    };
  }, []);

  useEffect(() => {
    BirthDay && formatDateList();
  }, [BirthDay]);

  // useEffect(() => {
  //   modalVisible && console.log(modalVisible);
  // }, [modalVisible]);

  //props
  const homeProps = {
    userDetails,
    quotation,
    birthdayOfUser,
    dataBirthday,
    openView,
    bdUserCurrentMonth,
    BirthDay,
    modalVisible,
    imgArr,
    arrPersonnel,
    wishTxt,
    wishList,
    openProfileComponent,
    openCheckIn,
    chooseSetting,
    chooseSettingView,
    openSettingView,
    hideMenu,
    OpenProfileUserComponent,
    setWishTxt,
    sendWishBirthday,
    SlidePersonnel,
    openModalHappyBirthday,
    closeModalHappyBirthday,
    openModalWishBirthday,
    closeModalWishBirthday,
    OpenURLButton,
    handleOpenDesBirthday,
    handleCloseDesBirthday,
    addMoreImgFromGallery,
    onCalendarChangeMonth,
    openCheckInPage,
  };
  return <HomeScreen {...homeProps} />;
};

export default HomeContainer;
