import React, {useEffect, useState} from 'react';

import {launchImageLibrary} from 'react-native-image-picker';
import Toast from 'react-native-toast-message';
import {useDispatch} from 'react-redux';
import RootNavigation from '../../navigation/RootNavigation';
import Utils from '../../utils';
import {APP_NAVIGATE_SCREEN} from '../../utils/constant';
import {logout} from '../authentication/authSlice';
import profilePropsProvider from './profilePropsProvider';
import ProfileMainView from './template/ProfileMainView';
import {ToastMessage} from '../../utils/MessageUtil';
import config from '../../config';
import {changeAvatar, changeCoverAvatar, changeUserInfo} from './profileSlice';

const ProfileContainer = props => {
  const {userInfo} = props;
  const dispatch = useDispatch();
  const [isEditField, setEditField] = useState({
    detail_info: false,
    contact_info: false,
    personal_info: false,
    avatar: false,
  });

  const [editUserInfo, setEditUserInfo] = useState({
    personalInfo: false,
    detailInfo: false,
  });

  const [avatar, setAvatar] = useState();
  const [coverAvatar, setCoverAvatar] = useState();

  const [visibleMenu, setVisibleMenu] = useState(false);

  const hideMenu = () => setVisibleMenu(false);
  const showMenu = () => setVisibleMenu(true);

  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) {
          const {assets} = response;
          setCoverAvatar(response.assets);
          let uploadImage = new FormData();
          uploadImage.append('file', {
            uri: assets[0].uri,
            name: assets[0].fileName,
            type: assets[0].type,
          });
          dispatch(
            changeCoverAvatar({id: userInfo.id, file: uploadImage}),
          ).then(result => {
            const {success} = Utils.getValues(result, 'payload', false);
            setEditField(prev => ({...prev, avatar: false}));
            Toast.show({
              type: success ? 'success' : 'error',
              text1: 'Hệ thống',
              text2: `Thay ảnh bìa ${success ? 'thành công 💖' : 'thất bại'} `,
            });
          });

          //setEditField(prev => ({...prev, avatar: true}));
          // hideMenu();
          //console.log(response.assets[0].uri)
        }
      },
    );
  };

  const onSubmitChangeInfo = async values => {
    if (userInfo) {
      const {
        first_name,
        middle_name,
        last_name,
        cell_phone,
        gender,
        birthday,
        birthplace,
        nationality,
        id_card_number,
        id_card_issue_date,
        id_card_issue_palce,
        ethnic,
        religion,
        domicile,
        personal_tax_code,
        address,
        permanent_address,
      } = values;
      const payload = {
        first_name: first_name || userInfo?.first_name,
        middle_name: middle_name || userInfo?.middle_name,
        last_name: last_name || userInfo?.last_name,
        cell_phone: cell_phone || userInfo?.cell_phone,
        gender: gender === 'Nam',
        birthday: birthday || userInfo?.birthday,
        birthplace: birthplace || userInfo?.birthplace,
        nationality: nationality || userInfo?.nationality,
        id_card_number: id_card_number || userInfo?.id_card_number,
        id_card_issue_date: id_card_issue_date || userInfo?.id_card_issue_date,
        id_card_issue_palce:
          id_card_issue_palce || userInfo?.id_card_issue_palce,
        ethnic: ethnic || userInfo?.ethnic,
        religion: religion || userInfo?.religion,
        domicile: domicile || userInfo?.domicile,
        personal_tax_code: personal_tax_code || userInfo?.personal_tax_code,
        address: address || userInfo?.address,
        permanent_address: permanent_address || userInfo?.permanent_address,
      };

      dispatch(changeUserInfo({id: userInfo.id, body: payload})).then(
        response => {
          const {success} = Utils.getValues(response, 'payload', false);
          success && onEditUserInfo();
          ToastMessage({
            title: 'Hệ thống',
            message: `Thay đổi thông tin ${
              success ? 'thành công 💖' : 'thất bại 💔'
            }  `,
            type: success ? 'success' : 'error',
          });
        },
      );
    }
  };
  const onDeniedAvatar = () => {
    setAvatar(null);
    setEditField(prev => ({...prev, avatar: false}));
  };
  const onConfirmAvatar = () => {
    if (avatar) {
      let uploadImage = new FormData();
      for (let i = 0; i < avatar.length; i++) {
        uploadImage.append('file', {
          uri: avatar[i].uri,
          name: avatar[i].fileName,
          type: avatar[i].type,
        });
      }
      dispatch(changeAvatar({id: userInfo.id, file: uploadImage})).then(
        response => {
          const {success} = Utils.getValues(response, 'payload', false);
          setEditField(prev => ({...prev, avatar: false}));
          Toast.show({
            type: success ? 'success' : 'error',
            text1: 'Hệ thống',
            text2: `Thay avatar ${success ? 'thành công 💖' : 'thất bại!!!'}`,
          });
        },
      );
    }
  };

  const navigateToLogout = () => {
    dispatch(logout()).then(response => {
      const {success} = Utils.getValues(response, 'payload', false);
      if (success) {
        Utils.restartApp();
      }
    });
  };

  const onEditUserInfo = field => {
    setEditUserInfo({
      personalInfo: field === config.profileField.PERSONAL_INFO,
      detailInfo: field === config.profileField.DETAIL_INFO,
    });
  };

  const profileProps = {
    userInfo,
    isEditField,
    avatar,
    visibleMenu,
    editUserInfo,
    coverAvatar,
    onDeniedAvatar,
    onConfirmAvatar,
    showMenu,
    openGallery,
    hideMenu,
    navigateToLogout,
    onChangeCoverAvatar,
    onEditUserInfo,
    onSubmitChangeInfo,
  };

  return <ProfileMainView {...profilePropsProvider(profileProps)} />;
};

export default ProfileContainer;
