/* eslint-disable prettier/prettier */
import React, {useEffect, useState} from 'react';

import ProfileScreen from './ProfileScreen';
import {useDispatch, useSelector} from 'react-redux';
import RootNavigation from '../../navigation/RootNavigation';
import {APP_NAVIGATE_SCREEN} from '../../utils/constant';
import {
  changeAvatar,
  changeCoverAvatar,
  changeUserInfo,
  getContactUser,
  changeContactUser,
  deleteContactUser,
  addContactUser,
} from '../../store/actions/UserAction';
import {launchImageLibrary} from 'react-native-image-picker';
import Toast from 'react-native-toast-message';
import Moment from 'moment';
import {logoutApp} from '../../store/actions/CommonAction';
const ProfileContainer = props => {
  const {userDetails} = props;
  const dispatch = useDispatch();

  const [modalVisible, setModalVisible] = useState(false);
  const [isEditField, setEditField] = useState({
    detail_info: false,
    contact_info: false,
    personal_info: false,
    avatar: false,
  });
  const [btnAvailable, setBtnAvailable] = useState({
    personalBtn: false,
    contactBtn: false,
    detailBtn: false,
  });
  const [infoUser, setInfoUser] = useState(userDetails);

  const [contactUser, setContactUser] = useState([]);
  const [defaultContact, setDefaultContact] = useState([]);
  const [userInputContact, setUserInputContact] = useState({
    type: '',
    text: '',
  });

  const [avatar, setAvatar] = useState();

  const [visibleMenu, setVisibleMenu] = useState(false);
  const [isSlideShow, setSlideShow] = useState(false);
  const [dateTimePicker, setDateTimePicker] = useState({
    birthday: false,
    id_card_issue_date: false,
  });
  const [showAlert, setShowAlert] = useState({
    isError: false,
    title: '',
    message: '',
  });
  const [deleteItem, setDelItem] = useState([]);

  const hideMenu = () => setVisibleMenu(false);
  const showMenu = () => setVisibleMenu(true);
  const hideDateTimePicker = () => {
    setDateTimePicker({
      birthday: false,
      id_card_issue_date: false,
    });
  };
  const openGallery = () => {
    hideMenu();

    launchImageLibrary(
      {
        mediaType: 'photo',
        includeBase64: true,
      },
      response => {
        //console.log('res', response);
        if (!response.didCancel) {
          setAvatar(response.assets);
          setEditField(prev => ({...prev, avatar: true}));
          // hideMenu();
          //console.log(response.assets[0].uri)
        }
      },
    );
  };
  const onChangeCoverAvatar = () => {
    launchImageLibrary(
      {
        mediaType: 'photo',
        includeBase64: true,
      },
      response => {
        //console.log('res', response);
        if (!response.didCancel) {
          //setCoverAvatar(response.assets);
          const resChangeCoverAvatar = dispatch(
            changeCoverAvatar(userDetails.id, response.assets),
          );
          if (resChangeCoverAvatar) {
            setEditField(prev => ({...prev, avatar: false}));
            Toast.show({
              type: 'success',
              text1: 'Hệ thống',
              text2: 'Thay ảnh bìa thành công 💖',
            });
          }
          //setEditField(prev => ({...prev, avatar: true}));
          // hideMenu();
          //console.log(response.assets[0].uri)
        }
      },
    );
  };

  const showFullScreen = () => {
    setSlideShow(true);
    hideMenu();
  };
  const hideFullScreen = () => {
    //console.log("hide")
    setSlideShow(false);
  };
  const onSaveInfo = async () => {
    if (!!compareInfoUser) {
      const res = await dispatch(changeUserInfo(userDetails.id, infoUser));
      if (res) {
        Toast.show({
          type: 'success',
          text1: 'Hệ thống',
          text2: 'Thay đổi thông tin thành công 💖',
        });
      } else {
        Toast.show({
          type: 'error',
          text1: 'Hệ thống',
          text2: 'Thay đổi thông tin thất bại 💔',
        });
      }
    }
  };
  const onDeniedAvatar = () => {
    setAvatar(null);
    setEditField(prev => ({...prev, avatar: false}));
  };
  const onConfirmAvatar = () => {
    const res = dispatch(changeAvatar(userDetails.id, avatar));
    if (res) {
      setEditField(prev => ({...prev, avatar: false}));
      Toast.show({
        type: 'success',
        text1: 'Hệ thống',
        text2: 'Thay avatar thành công 💖',
      });
    }
  };
  const navigateMain = () => {
    RootNavigation.navigate(APP_NAVIGATE_SCREEN.MAIN);
  };
  const compareInfoUser = () => {
    // check user have change info
    if (JSON.stringify(infoUser) == JSON.stringify(userDetails)) return true;
    return false;
  };

  const compareContactUser = () => {
    // check user have change info
    // console.log("defaultContact", defaultContact)
    if (JSON.stringify(defaultContact) === JSON.stringify(contactUser))
      return false;
    return true;
  };

  const getContactSocialUser = async () => {
    const res = await dispatch(getContactUser(userDetails.id));
    //console.log(res)
    if (res.length > 0) {
      let arrContact = [];
      res.map((item, index) => {
        arrContact.push(item);
      });
      setContactUser(arrContact);
      setDefaultContact(JSON.parse(JSON.stringify(arrContact)));
    }
  };
  const onChangeDropDownContactUser = (selectedItem, index) => {
    const clone = [...contactUser];
    clone[index].type = selectedItem;
    setContactUser(clone);
    //console.log("clone", clone)
  };
  const onChangeInputContactUser = (selectedItem, index) => {
    const clone = [...contactUser];
    clone[index].contact_unique_id = selectedItem;
    setContactUser(clone);
    //console.log("clone", clone)
  };
  const checkValidDropdown = () => {
    var isValid = contactUser.map(a => a.type);
    //console.log(isValid.some((a, index) => isValid.indexOf(a) !== index))
    return isValid.some((a, index) => isValid.indexOf(a) !== index);
  };
  const onSubmitChangeContactUser = async (contact_unique_id, type) => {
    const isChange = compareContactUser();
    //console.log("defaultContact", defaultContact)
    const isValid = checkValidDropdown();
    if (!isValid) {
      if (isChange) {
        //console.log("compareEmailContactUser", isChange)
        const resultsChange = contactUser.filter(
          ({type: t1, contact_unique_id: cui_1}) =>
            !defaultContact.some(
              ({type: t2, contact_unique_id: cui_2}) =>
                t2 === t1 && cui_1 === cui_2,
            ),
        );
        //console.log("results", resultsChange)
        const res = await dispatch(
          changeContactUser(
            resultsChange[0].id,
            resultsChange[0].contact_unique_id,
            resultsChange[0].type,
          ),
        );
        if (res.success) {
          Toast.show({
            type: 'success',
            text1: 'Hệ thống',
            text2: 'Thay đổi liên lạc thành công 💖',
          });
          setEditField(prev => ({...prev, contact_info: false}));
          setBtnAvailable(prev => ({...prev, contactBtn: false}));
        } else {
          Toast.show({
            type: 'error',
            text1: 'Hệ thống',
            text2: 'Thay đổi liên lạc thất bại 💔',
          });
        }
      } else {
        setEditField(prev => ({...prev, contact_info: false}));
        setBtnAvailable(prev => ({...prev, contactBtn: false}));
      }
    } else {
      Toast.show({
        type: 'error',
        text1: 'Hệ thống',
        text2: 'Vui lòng chọn social khác nhau',
      });
    }
  };
  const onPressDeleteItem = item => {
    // console.log("item", item)
    setShowAlert({
      isError: true,
      title: 'Hệ thống',
      message: 'Bạn có chắc chắn muốn xóa dòng dữ liệu này?',
    });
    setDelItem(item);
  };
  const onPressAddItem = () => {
    setModalVisible(true);
  };
  const onConfirmDeleteAlert = async () => {
    const clone = contactUser.filter(i => i !== deleteItem);

    const res = await dispatch(deleteContactUser(deleteItem.id));
    if (res) {
      Toast.show({
        type: 'success',
        text1: 'Hệ thống',
        text2: 'Xoá thành công ',
      });
      setContactUser(clone);
      setDefaultContact(clone);
      setShowAlert({
        isError: false,
        title: '',
        message: '',
      });
    } else {
      Toast.show({
        type: 'error',
        text1: 'Hệ thống',
        text2: 'Xoá thất bại',
      });
      setShowAlert({
        isError: false,
        title: '',
        message: '',
      });
    }
    // console.log("clone", clone)
  };
  const onCancelAlert = () => {
    setShowAlert({
      isError: false,
      title: '',
      message: '',
    });
  };

  // submit add new contact
  const onSubmitCreateNew = async () => {
    if (userInputContact.text.length > 0 && userInputContact.type.length > 0) {
      //  had social network type
      const duplicateSocial = contactUser.find(
        item => item.type === userInputContact.type,
      );
      //console.log("duplicateSocial", duplicateSocial)
      if (duplicateSocial === undefined) {
        const res = await dispatch(
          addContactUser(
            userDetails.id,
            userInputContact.text,
            userInputContact.type,
          ),
        );
        if (res.success) {
          Toast.show({
            type: 'success',
            text1: 'Hệ thống',
            text2: 'Thêm contact thành công',
          });
          setEditField(prev => ({...prev, contact_info: false}));
          setBtnAvailable(prev => ({...prev, contactBtn: false}));
          setModalVisible(false);
          setUserInputContact({
            type: '',
            text: '',
          });
          getContactSocialUser();
        } else {
          Toast.show({
            type: 'error',
            text1: 'Hệ thống',
            text2: 'Thêm contact thất bại',
          });
        }
      } else {
        Toast.show({
          type: 'error',
          text1: 'Hệ thống',
          text2: 'Đã social này đã tổn tài',
        });
      }
    }
  };
  const navigateToLogout = () => {
    dispatch(logoutApp());
  };
  useEffect(() => {
    getContactSocialUser();
  }, []);

  // useEffect(() => {
  //     infoUser && console.log("infoUser", infoUser)
  // }, [])
  const profileProps = {
    userDetails,
    isEditField,
    btnAvailable,
    infoUser,
    avatar,
    visibleMenu,
    isSlideShow,
    dateTimePicker,
    contactUser,
    showAlert,
    modalVisible,
    userInputContact,
    setAvatar,
    setInfoUser,
    navigateMain,
    setEditField,
    setBtnAvailable,
    onSaveInfo,
    onDeniedAvatar,
    onConfirmAvatar,
    showMenu,
    openGallery,
    showFullScreen,
    hideFullScreen,
    hideMenu,
    hideDateTimePicker,
    setDateTimePicker,
    onSubmitChangeContactUser,
    setContactUser,
    onChangeDropDownContactUser,
    onChangeInputContactUser,
    onPressDeleteItem,
    onPressAddItem,
    onConfirmDeleteAlert,
    onCancelAlert,
    setUserInputContact,
    onSubmitCreateNew,
    setModalVisible,
    navigateToLogout,
    onChangeCoverAvatar,
  };

  // useEffect(() => {
  //     infoUser && userDetails && compareInfoUser()
  // }, [userDetails, infoUser])
  // useEffect(() => {
  //     infoUser && console.log("infoUser", infoUser)
  // }, [])

  return <ProfileScreen {...profileProps} />;
};

export default ProfileContainer;
