import React, {useEffect, useState} from 'react';
import {
  SafeAreaView,
  ScrollView,
  TouchableOpacity,
  Image,
  View,
  TextInput,
  Modal,
  Dimensions,
  StyleSheet,
} from 'react-native';
import colors from '../../../values/colors';
import {IMAGES} from '../../../values/images';
import DateTimePickerModal from 'react-native-modal-datetime-picker';
import CheckBox from '@react-native-community/checkbox';
import {Toast} from 'react-native-toast-message/lib/src/Toast';
import Moment from 'moment';
import Alert from 'react-native-awesome-alerts';
import TextInputComponent from '../../../components/TextInputComponent';
import ButtonComponent from '../../../components/ButtonComponent';
import {useDispatch, useSelector} from 'react-redux';
import {launchImageLibrary} from 'react-native-image-picker';
import {postUserConfirmDay} from '../../../store/actions/UserAction';
import AppText from '../../../components/AppText';
const windowWidth = Dimensions.get('window').width;
const windowHeight = Dimensions.get('window').height;
const ConfirmModalAddNew = ({userDetails, onClose}) => {
  const dispatch = useDispatch();
  const userDirectManagersList = useSelector(
    state => state.MyDirectManagers.myDirectManagers,
  );
  // init state
  const initStateConfirm = {
    since: new Date(),
    hourSince: new Date(),
    finish: new Date(),
    hourFinish: new Date(),
    reason: '',
    taken_hours: 0,
    approved_date: new Date(),
  };
  const [postImage, setPostImage] = useState([]);
  const [userManagerList, setUserManagerList] = useState([]);
  const [openTimePicker, setOpenTimePicker] = useState({
    start: false,
    hourSince: false,
    finish: false,
    hourFinish: false,
  });
  const [confirmDate, setConfirm] = useState(initStateConfirm);
  const [toggleCheckBox, setToggleCheckBox] = useState(false);
  const [isNextApprover, setNextApproverId] = useState(false);

  const [showAlert, setShowAlert] = useState({
    isShow: false,
    title: '',
    message: '',
  });
  // main function
  const alertMessage = message => {
    setShowAlert({
      isError: true,
      title: 'Thông báo',
      message: `${message} 👍`,
    });
  };
  const onHideAlert = () => {
    setShowAlert({
      isError: false,
      title: '',
      message: '',
    });
  };
  const onOpenCreateConfirmDate = () => {
    // setModalVisible(true);
    const objectClone = JSON.parse(JSON.stringify(userDirectManagersList));
    let obj = [];
    objectClone.forEach(element => {
      element.checked = false;
      obj.push(element);
    });
    setUserManagerList(obj);
  };
  const openGallery = () => {
    launchImageLibrary(
      {
        mediaType: 'photo',
        includeBase64: true,
      },
      response => {
        if (!response.didCancel) {
          //console.log('AAA');
          const {assets} = response;
          setPostImage(prev => [...prev, ...assets]);
          //console.log(response.assets[0].uri)
        }
      },
    );
  };
  const onDeleteImage = index => {
    const clone = [...postImage];
    clone.splice(index, 1);
    setPostImage(clone);
  };
  const onSelectManager = async (value, index, item) => {
    setToggleCheckBox(value);
    let userManagerListClone = [...userManagerList];

    if (item !== undefined) {
      let elementFound = userManagerListClone.find(
        element => element.id == item.id,
      );
      let indexElementFound = userManagerListClone.findIndex(
        element => element.id == item.id,
      );
      userManagerListClone.splice(indexElementFound, 1, {
        ...elementFound,
        checked: value,
      });
      setUserManagerList(userManagerListClone);

      if (isNextApprover) {
        setNextApproverId(item.id);
      } else {
        setNextApproverId('');
        // setLeave(state => ({
        //     ...state,
        //     approver_id: item.id
        // }))
      }
    }
  };
  const onSubmitConfirmDate = async () => {
    //console.log(confirmDate.since === confirmDate.finish)
    if (confirmDate.since > confirmDate.finish) {
      alertMessage('Vui chọn ngày bắt đầu nhỏ hơn ngày kết thúc!!!');
      return;
    }

    if (
      confirmDate.since === confirmDate.finish &&
      confirmDate.hourSince >= confirmDate.hourFinish
    ) {
      alertMessage('Vui chọn ngày bắt đầu nhỏ hơn ngày kết thúc!!!');
      return;
    }
    if (confirmDate.reason === '') {
      alertMessage('Vui lòng nhập lý do');
      return;
    }

    if (!toggleCheckBox) {
      alertMessage('Vui lòng nhập chọn người duyệt');
      return;
    }

    const res = await dispatch(
      postUserConfirmDay(userManagerList[0].id, confirmDate, postImage),
    );
    if (res.success) {
      Toast.show({
        type: 'success',
        text1: 'Hệ thống',
        text2: 'Xác nhận ngày công thành công👍',
        style: {zIndex: 1001},
      });
      onClose(null);
    } else {
      Toast.show({
        type: 'error',
        text1: 'Hệ thống',
        text2: 'Xác nhận ngày công thất bại 💔',
        style: {zIndex: 1001},
      });
    }
  };
  useEffect(() => {
    onOpenCreateConfirmDate();
  }, []);

  return (
    <Modal
      animationType="slide"
      transparent={true}
      visible={true}
      onRequestClose={() => {
        onClose(null);
      }}>
      <SafeAreaView>
        <View style={styles.modalView}>
          <View style={{flexDirection: 'row', justifyContent: 'space-between'}}>
            <AppText style={styles.modalTitle}>Xác nhận ngày công</AppText>
            <TouchableOpacity
              onPress={() => {
                onClose(null);
              }}>
              <Image source={IMAGES.IcClose} />
            </TouchableOpacity>
          </View>
          <View style={{flexDirection: 'row', marginTop: 10}}>
            <Image
              source={{uri: 'https://meu.anawork.com' + userDetails.avatar}}
              style={styles.ImgAvatar}
            />
            <View style={{marginLeft: 15}}>
              <AppText style={styles.modalTitle}>{`${userDetails.first_name} ${
                userDetails.middle_name ? userDetails.middle_name : ''
              } ${userDetails.last_name}`}</AppText>
              <AppText>{userDetails.position}</AppText>
            </View>
          </View>
          <View style={styles.bodyHeightCreate}>
            <ScrollView>
              <View style={{marginTop: 20}}>
                <AppText style={styles.modalTitle}>Thông tin xác nhận</AppText>
                <View style={styles.rowView}>
                  <AppText style={{flex: 1}}>Từ ngày</AppText>
                  <View style={{flex: 1}}>
                    <TouchableOpacity
                      onPress={() =>
                        setOpenTimePicker(state => ({
                          ...state,
                          start: true,
                        }))
                      }
                      style={[
                        styles.dropdown1BtnStyle,
                        {
                          alignItems: 'flex-end',
                          flexDirection: 'row',
                          justifyContent: 'flex-end',
                        },
                      ]}>
                      <AppText>
                        {Moment(confirmDate.since).format('DD/MM/YYYY')}
                      </AppText>
                      <Image
                        source={IMAGES.IcCalendarGray}
                        style={{width: 20, height: 20}}
                      />
                    </TouchableOpacity>
                    <DateTimePickerModal
                      isVisible={openTimePicker.start}
                      mode="date"
                      date={confirmDate.start}
                      onConfirm={time => {
                        setOpenTimePicker(state => ({
                          ...state,
                          start: false,
                        }));
                        setConfirm(state => ({
                          ...state,
                          since: time,
                        }));
                      }}
                      onCancel={() => {
                        setOpenTimePicker(state => ({
                          ...state,
                          start: false,
                        }));
                      }}
                    />
                  </View>
                </View>
                <View style={styles.rowView}>
                  <AppText>Giờ</AppText>
                  <TouchableOpacity
                    onPress={() =>
                      setOpenTimePicker(state => ({
                        ...state,
                        hourSince: true,
                      }))
                    }
                    style={{flexDirection: 'row'}}>
                    <AppText>
                      {Moment(confirmDate.hourSince).format('HH:mm')}
                    </AppText>
                    <Image
                      source={IMAGES.IcLockGrey}
                      style={{width: 20, height: 20}}
                    />
                  </TouchableOpacity>
                  <DateTimePickerModal
                    isVisible={openTimePicker.hourSince}
                    mode="time"
                    date={confirmDate.hourSince}
                    onConfirm={time => {
                      setOpenTimePicker(state => ({
                        ...state,
                        hourSince: false,
                      }));
                      setConfirm(state => ({
                        ...state,
                        hourSince: time,
                      }));
                    }}
                    onCancel={() => {
                      setOpenTimePicker(state => ({
                        ...state,
                        hourSince: false,
                      }));
                    }}
                  />
                </View>
                <View style={styles.rowView}>
                  <AppText style={{flex: 1}}>Đến ngày</AppText>
                  <View style={{flex: 1}}>
                    <TouchableOpacity
                      onPress={() =>
                        setOpenTimePicker(state => ({
                          ...state,
                          finish: true,
                        }))
                      }
                      style={[
                        styles.dropdown1BtnStyle,
                        {
                          alignItems: 'flex-end',
                          flexDirection: 'row',
                          justifyContent: 'flex-end',
                        },
                      ]}>
                      <AppText>
                        {Moment(confirmDate.finish).format('DD/MM/YYYY')}
                      </AppText>
                      <Image
                        source={IMAGES.IcCalendarGray}
                        style={{width: 20, height: 20}}
                      />
                    </TouchableOpacity>
                    <DateTimePickerModal
                      isVisible={openTimePicker.finish}
                      mode="date"
                      date={confirmDate.finish}
                      onConfirm={time => {
                        setOpenTimePicker(state => ({
                          ...state,
                          finish: false,
                        }));
                        setConfirm(state => ({
                          ...state,
                          finish: time,
                        }));
                      }}
                      onCancel={() => {
                        setOpenTimePicker(state => ({
                          ...state,
                          finish: false,
                        }));
                      }}
                    />
                  </View>
                </View>
                <View style={styles.rowView}>
                  <AppText>Giờ</AppText>
                  <TouchableOpacity
                    onPress={() =>
                      setOpenTimePicker(state => ({
                        ...state,
                        hourFinish: true,
                      }))
                    }
                    style={{flexDirection: 'row'}}>
                    <AppText>
                      {Moment(confirmDate.hourFinish).format('HH:mm')}
                    </AppText>
                    <Image
                      source={IMAGES.IcLockGrey}
                      style={{width: 20, height: 20}}
                    />
                  </TouchableOpacity>
                  <DateTimePickerModal
                    isVisible={openTimePicker.hourFinish}
                    mode="time"
                    date={confirmDate.hourFinish}
                    onConfirm={time => {
                      setOpenTimePicker(state => ({
                        ...state,
                        hourFinish: false,
                      }));
                      setConfirm(state => ({
                        ...state,
                        hourFinish: time,
                      }));
                    }}
                    onCancel={() => {
                      setOpenTimePicker(state => ({
                        ...state,
                        hourFinish: false,
                      }));
                    }}
                  />
                </View>

                <View style={styles.rowView}>
                  <AppText
                    style={{
                      flex: 1,
                      color: confirmDate.reason.length === 0 ? 'red' : 'grey',
                    }}>
                    {`Lý do (*)`}
                  </AppText>
                  <View style={{flex: 1}}>
                    <TextInput
                      style={styles.inputText}
                      values={confirmDate.reason}
                      placeholder="Nhập lý do tại đây"
                      onChangeText={text => {
                        setConfirm(prev => ({
                          ...prev,
                          reason: text,
                        }));
                      }}
                    />
                  </View>
                </View>
                <View style={styles.rowView}>
                  <AppText style={{flex: 1}}>Tệp đính kèm</AppText>
                  <View
                    style={{
                      flex: 2,
                      flexDirection: 'row',
                      justifyContent: 'center',
                      alignItems: 'center',
                      marginTop: 10,
                    }}>
                    {postImage.length > 0 &&
                      postImage.map((item, index) => {
                        //console.log("item", item[0].uri)
                        return (
                          <View key={index}>
                            <ButtonComponent
                              iconSource={IMAGES.IcClose}
                              style={styles.btnClose}
                              onPress={() => onDeleteImage(index)}
                            />
                            <Image
                              source={{uri: item.uri}}
                              style={[styles.imgUpload]}
                            />
                          </View>
                        );
                      })}

                    {postImage.length < 3 && (
                      <ButtonComponent
                        style={styles.touchableOpacity}
                        onPress={openGallery}
                        iconSource={IMAGES.IcAddMoreImg}
                      />
                    )}
                  </View>
                </View>
                <View style={{marginTop: 20}}>
                  <AppText
                    style={[
                      styles.modalTitle,
                      {
                        marginBottom: 10,
                      },
                    ]}>
                    Người duyệt
                  </AppText>
                  {userManagerList.map((item, index) => (
                    <View
                      key={index}
                      style={{
                        flexDirection: 'row',
                        justifyContent: 'space-between',
                        alignItems: 'center',
                      }}>
                      <View style={{flexDirection: 'row'}}>
                        <Image
                          source={{
                            uri: 'https://meu.anawork.com' + item.avatar,
                          }}
                          style={{width: 60, height: 60, borderRadius: 10}}
                        />
                        <View>
                          <AppText
                            style={{
                              fontSize: 16,
                              fontWeight: '500',
                              marginLeft: 10,
                            }}>{`${item.extend_user_full_name}`}</AppText>
                          <AppText
                            style={{
                              fontSize: 13,
                              fontWeight: '500',
                              marginLeft: 10,
                            }}>{`${item?.position} - ${item?.department}`}</AppText>
                        </View>
                      </View>
                      <CheckBox
                        disabled={false}
                        value={item.checked}
                        onValueChange={newValue =>
                          onSelectManager(newValue, index, item)
                        }
                        boxType="square"
                        animationDuration={0.3}
                        lineWidth={1}
                        key={index}
                      />
                    </View>
                  ))}
                </View>
              </View>
            </ScrollView>
          </View>
          <View style={{flexDirection: 'row', justifyContent: 'flex-end'}}>
            <TouchableOpacity
              onPress={() => {
                onClose(null);
              }}
              style={styles.btnCancel}>
              <AppText style={styles.blueTxt}>Hủy</AppText>
            </TouchableOpacity>
            <TouchableOpacity
              style={styles.btnSubmit}
              onPress={onSubmitConfirmDate}>
              <AppText style={styles.whiteTxt}>Gửi yêu cầu</AppText>
            </TouchableOpacity>
          </View>
        </View>
      </SafeAreaView>
      <Alert
        show={showAlert.isError}
        showProgress={false}
        title={showAlert.title}
        message={showAlert.message}
        closeOnTouchOutside={true}
        closeOnHardwareBackPress={false}
        showConfirmButton={true}
        confirmText="Đóng"
        confirmButtonColor="#DD6B55"
        onConfirmPressed={onHideAlert}
      />
    </Modal>
  );
};
const styles = StyleSheet.create({
  container: {
    flex: 1,
  },
  pieChartContainer: {
    flexDirection: 'row',
  },
  pieChartView: {
    borderWidth: 1,
    borderColor: 'white',
    borderRadius: 5,
    backgroundColor: 'white',
    marginTop: 10,
    flexDirection: 'row',
    marginLeft: 10,
    marginRight: 10,
    padding: 10,
  },
  pieItem: {
    alignItems: 'center',
  },
  pieFill: {
    position: 'absolute',
    width: 100,
    height: 200,
    alignItems: 'center',
    justifyContent: 'center',
  },
  pieFillTextAmount: {
    fontSize: 15,
    color: '#757575',
  },
  pieFillText: {
    fontSize: 10,
    lineHeight: 15,
  },
  boldTitle: {
    fontWeight: '500',
    marginBottom: 10,
    fontSize: 14,
    color: 'black',
    marginLeft: 10,
  },
  h2: {
    fontWeight: '500',
    fontSize: 20,
    color: 'black',
  },
  viewTextPie: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'center',
  },
  bgLeftViewTextPie: {
    width: 10,
    height: 10,
  },
  bgRightViewTextPie: {
    backgroundColor: '#0abb87',
    width: 10,
    height: 10,
    marginRight: 5,
  },
  view: {
    width: windowWidth,
    alignSelf: 'center',
    borderWidth: 1,
    backgroundColor: colors.white,
    borderColor: colors.white,
    padding: 10,
    marginTop: 10,
  },
  btnConfirm: {
    backgroundColor: '#5d78ff',
    alignItems: 'center',
    justifyContent: 'center',
    borderWidth: 1,
    borderColor: '#5d78ff',
    borderRadius: 8,
    width: windowWidth - 100,
    height: 35,
    flexDirection: 'row',
  },
  whiteTxt: {
    color: colors.white,
    fontWeight: '500',
  },
  blueTxt: {
    color: '#5d78ff',
    fontWeight: '500',
  },
  iconPlus: {
    width: 20,
    height: 20,
    marginRight: 10,
  },
  primary_blue: {
    color: '#5d78ff',
  },
  item: {
    padding: 20,
    marginVertical: 8,
    marginHorizontal: 16,
    borderWidth: 1,
    borderBottomColor: '#f2f2f2',
    borderTopColor: '#f2f2f2',
    borderRightColor: '#f2f2f2',
    borderTopLeftRadius: 10,
    borderBottomLeftRadius: 10,
    borderLeftWidth: 5,
    flexDirection: 'row',
  },
  title: {
    fontWeight: '500',
    fontSize: 14,
    color: 'black',
  },
  centeredView: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    marginTop: 22,
  },
  modalView: {
    backgroundColor: 'white',
    borderRadius: 20,
    padding: 20,
    shadowColor: '#000',
    shadowOffset: {
      width: 0,
      height: 2,
    },
    shadowOpacity: 0.25,
    shadowRadius: 4,
    elevation: 5,
    marginTop: 20,
    height: windowHeight,
  },
  button: {
    borderRadius: 20,
    padding: 10,
    elevation: 2,
  },
  buttonOpen: {
    backgroundColor: '#F194FF',
  },
  buttonClose: {
    backgroundColor: '#2196F3',
  },
  textStyle: {
    color: 'white',
    fontWeight: 'bold',
    textAlign: 'center',
  },
  modalTitle: {
    fontWeight: '500',
    fontSize: 16,
  },
  dropdown1DropdownStyle: {backgroundColor: '#EFEFEF'},
  dropdown1RowStyle: {backgroundColor: '#EFEFEF', borderBottomColor: '#C5C5C5'},
  dropdown1RowTxtStyle: {color: '#444', textAlign: 'left'},
  dropdown1BtnStyle: {
    backgroundColor: '#FFF',
    borderBottomWidth: 0.2,
    borderColor: '#444',
  },
  dropdown1BtnTxtStyle: {color: 'red', textAlign: 'left'},
  rowView: {
    flexDirection: 'row',
    marginTop: 10,
    justifyContent: 'space-between',
    alignItems: 'center',
  },
  inputText: {
    backgroundColor: '#FFF',
    borderBottomWidth: 0.2,
    borderColor: '#444',
  },
  touchableOpacity: {
    borderColor: colors.primary_blue,
    borderStyle: 'dotted',
    borderWidth: 2,
    justifyContent: 'center',
    alignItems: 'center',
    height: 50,
    padding: 10,
    width: 50,
  },
  btnSubmit: {
    backgroundColor: '#5d78ff',
    justifyContent: 'center',
    alignItems: 'center',
    height: 40,
    borderRadius: 8,
    width: 100,
  },
  btnCancel: {
    backgroundColor: colors.white,
    justifyContent: 'center',
    alignItems: 'center',
    height: 40,
    borderRadius: 8,
    width: 100,
  },
  ImgAvatar: {
    width: 50,
    height: 50,
    borderRadius: 30,
  },
  imgUpload: {
    resizeMode: 'contain',
    height: 80,
    width: 80,
  },
  btnClose: {
    width: 20,
    height: 20,
    position: 'absolute',
    top: -10,
    right: 0,
  },
});
export default ConfirmModalAddNew;
