/* eslint-disable prettier/prettier */
/* eslint-disable react-native/no-inline-styles */
/* eslint-disable prettier/prettier */
import CheckBox from '@react-native-community/checkbox';
import Moment from 'moment';
import React, {useEffect, useState} from 'react';
import {
  Image,
  Modal,
  Text,
  TextInput,
  TouchableOpacity,
  View,
} from 'react-native';
import {launchImageLibrary} from 'react-native-image-picker';
import DateTimePickerModal from 'react-native-modal-datetime-picker';
import {useDispatch, useSelector} from 'react-redux';
import {
  getUserDirectManagers,
  getUserOTVoucher,
  postUserOTVoucher,
} from '../../../store/actions/UserAction';
import {IMAGES} from '../../../values/images';
import Toast from 'react-native-toast-message';
import styles from '../style';
import Alert from 'react-native-awesome-alerts';
import ButtonComponent from '../../../components/ButtonComponent';
const OverTimeModalAdd = props => {
  //userSelector
  const userDetails = useSelector(state => state.UserInfo.userInfo);
  const dispatch = useDispatch();
  const {onClose} = props;
  const [openTimePicker, setOpenTimePicker] = useState({
    start: false,
    finish: false,
    timeStart: false,
    timeFinish: false,
  });
  const [otVoucher, setOtVoucher] = useState({
    start: new Date(),
    finish: new Date(),
    timeStart: new Date(),
    timeFinish: new Date(),
    reason: '',
    approver_id: '',
  });
  const [showAlert, setShowAlert] = useState({
    isShow: false,
    title: '',
    message: '',
  });

  const [postImage, setPostImage] = useState([]);
  const [myDirectorManagerList, setMyDirectorManagerList] = useState([]);
  const [toggleSelectedNextApprover, setToggleSelectedNextApprover] =
    useState(false);

  const onHideAlert = () => {
    setShowAlert({
      isShow: false,
      title: '',
      message: '',
    });
  };
  const getMyDirectorManagerList = async () => {
    const res = await dispatch(getUserDirectManagers());
    setMyDirectorManagerList(res);
  };

  const validateOtVoucher = () => {
    if (otVoucher.reason.length < 1) {
      return false;
    }
    return true;
  };

  const validateTime = () => {
    if (otVoucher.start > otVoucher.finish) return false;
    else if (
      Moment(otVoucher.start).format('YYYY-MM-DD') ===
        Moment(otVoucher.finish).format('YYYY-MM-DD') &&
      otVoucher.timeStart >= otVoucher.timeFinish
    ) {
      return false;
    }

    return true;
  };
  const onSubmit = async () => {
    if (validateOtVoucher() && validateTime()) {
      const res = await dispatch(postUserOTVoucher(otVoucher, postImage));
      if (res) {
        Toast.show({
          type: 'success',
          text1: 'Hệ thống',
          text2: 'Tạo yêu cầu tăng ca thành công👍',
          style: {zIndex: 1001},
        });

        dispatch(getUserOTVoucher('', '', 1, 5));
      } else {
        Toast.show({
          type: 'error',
          text1: 'Hệ thống',
          text2: 'Tạo yêu cầu tăng ca không thành công👍',
          style: {zIndex: 1001},
        });
      }
      setPostImage([]);
      onClose();
    } else {
      setShowAlert({
        isShow: true,
        message: 'Vui lòng chọn ngày giờ bắt đầu nhỏ hơn ngày giờ kết thúc',
        title: 'Hệ thống',
      });
    }
  };
  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);
  };
  useEffect(() => {
    getMyDirectorManagerList();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  return (
    <Modal
      animationType="slide"
      transparent={true}
      visible={true}
      propagateSwipe={true}
      onRequestClose={() => onClose(null)}>
      <View style={styles.modalView}>
        <View style={{flexDirection: 'row', justifyContent: 'space-between'}}>
          <Text style={styles.modalTitle}>Tăng ca mới</Text>
          <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}}>
            <Text
              style={
                styles.modalTitle
              }>{`${userDetails.first_name} ${userDetails.middle_name} ${userDetails.last_name}`}</Text>
            <Text>{userDetails.position}</Text>
          </View>
        </View>

        <View style={{marginTop: 20}}>
          <Text style={styles.modalTitle}>Thông tin tăng ca</Text>
          <View style={styles.rowView}>
            <Text>Từ ngày (*)</Text>
            <TouchableOpacity
              onPress={() =>
                setOpenTimePicker({
                  ...openTimePicker,
                  start: true,
                })
              }
              style={{
                alignItems: 'flex-end',
                flexDirection: 'row',
                justifyContent: 'flex-end',
                borderBottomWidth: 0.5,
              }}>
              <Text>{Moment(otVoucher.start).format('DD/MM/YYYY')}</Text>
              <Image
                source={IMAGES.IcCalendarGray}
                style={{width: 20, height: 20, marginLeft: 8}}
              />
            </TouchableOpacity>
            <DateTimePickerModal
              isVisible={openTimePicker.start}
              mode="date"
              onConfirm={time => {
                setOtVoucher(prev => ({
                  ...prev,
                  start: time,
                }));
              }}
              onCancel={() => {
                setOpenTimePicker({
                  ...openTimePicker,
                  start: false,
                });
              }}
            />
          </View>
          <View style={styles.rowView}>
            <Text>Giờ</Text>
            <TouchableOpacity
              onPress={() =>
                setOpenTimePicker({
                  ...openTimePicker,
                  timeStart: true,
                })
              }
              style={{
                alignItems: 'flex-end',
                flexDirection: 'row',
                justifyContent: 'flex-end',
                borderBottomWidth: 0.5,
              }}>
              <Text>{Moment(otVoucher.timeStart).format('HH:mm')}</Text>
              <Image
                source={IMAGES.IcLockGrey}
                style={{width: 20, height: 20, marginLeft: 8}}
              />
            </TouchableOpacity>
            <DateTimePickerModal
              isVisible={openTimePicker.timeStart}
              mode="time"
              onConfirm={time => {
                setOtVoucher(prev => ({
                  ...prev,
                  timeStart: time,
                }));
              }}
              onCancel={() => {
                setOpenTimePicker({
                  ...openTimePicker,
                  timeStart: false,
                });
              }}
            />
          </View>
          <View style={styles.rowView}>
            <Text>Đến ngày (*)</Text>
            <TouchableOpacity
              onPress={() =>
                setOpenTimePicker({
                  ...openTimePicker,
                  finish: true,
                })
              }
              style={{
                alignItems: 'flex-end',
                flexDirection: 'row',
                justifyContent: 'flex-end',
                borderBottomWidth: 0.5,
              }}>
              <Text>{Moment(otVoucher.finish).format('DD/MM/YYYY')}</Text>
              <Image
                source={IMAGES.IcCalendarGray}
                style={{width: 20, height: 20, marginLeft: 8}}
              />
            </TouchableOpacity>
            <DateTimePickerModal
              isVisible={openTimePicker.finish}
              mode="date"
              onConfirm={time => {
                setOtVoucher(prev => ({
                  ...prev,
                  finish: time,
                }));
              }}
              onCancel={() => {
                setOpenTimePicker({
                  ...openTimePicker,
                  finish: false,
                });
              }}
            />
          </View>
          <View style={styles.rowView}>
            <Text>Giờ</Text>
            <TouchableOpacity
              onPress={() =>
                setOpenTimePicker({
                  ...openTimePicker,
                  timeFinish: true,
                })
              }
              style={{
                alignItems: 'flex-end',
                flexDirection: 'row',
                justifyContent: 'flex-end',
                borderBottomWidth: 0.5,
              }}>
              <Text>{Moment(otVoucher.timeFinish).format('HH:mm')}</Text>
              <Image
                source={IMAGES.IcLockGrey}
                style={{width: 20, height: 20, marginLeft: 8}}
              />
            </TouchableOpacity>
            <DateTimePickerModal
              isVisible={openTimePicker.timeFinish}
              mode="time"
              onConfirm={time => {
                setOtVoucher(prev => ({
                  ...prev,
                  timeFinish: time,
                }));
              }}
              onCancel={() => {
                setOpenTimePicker({
                  ...openTimePicker,
                  timeFinish: false,
                });
              }}
            />
          </View>
          <View style={styles.rowView}>
            <Text
              style={{color: otVoucher.reason.length == 0 ? 'red' : 'grey'}}>
              Lý do (*)
            </Text>
            <TextInput
              style={styles.inputTextArea}
              values={otVoucher.reason}
              multiline={true}
              numberOfLines={1}
              onChangeText={text =>
                setOtVoucher(prev => ({
                  ...prev,
                  reason: text,
                }))
              }
              placeholder="Nhập lý do tại đây"
            />
          </View>

          <View style={styles.rowView}>
            <Text style={{flex: 1}}>Tệp đính kèm</Text>
            <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.viewOpenGallery}
                  onPress={openGallery}
                  iconSource={IMAGES.IcAddMoreImg}
                />
              )}
            </View>
          </View>
          <View style={{marginTop: 20}}>
            <Text
              style={[
                styles.modalTitle,
                {
                  marginBottom: 10,
                },
              ]}>
              Người duyệt (*)
            </Text>
            {myDirectorManagerList.length !== 0 &&
              myDirectorManagerList.map((item, index) => (
                <View
                  key={index}
                  style={{
                    flexDirection: 'row',
                    alignItems: 'center',
                    justifyContent: 'space-between',
                  }}>
                  <View
                    style={{
                      flexDirection: 'row',
                      alignItems: 'center',
                    }}>
                    <Image
                      source={{
                        uri: 'https://meu.anawork.com' + item?.avatar,
                      }}
                      style={{width: 50, height: 50, borderRadius: 8}}
                    />
                    <View>
                      <Text
                        style={{
                          fontSize: 16,
                          fontWeight: '500',
                          marginLeft: 10,
                        }}>{`${item?.extend_user_full_name}`}</Text>
                      <Text
                        style={{
                          fontSize: 12,
                          fontWeight: '500',
                          marginLeft: 10,
                        }}>
                        {`${item?.position} - ${item?.department}`}
                      </Text>
                    </View>
                  </View>
                  <View>
                    <CheckBox
                      disabled={false}
                      value={toggleSelectedNextApprover}
                      onValueChange={() => {
                        setToggleSelectedNextApprover(
                          !toggleSelectedNextApprover,
                        );
                        setOtVoucher(prev => ({
                          ...prev,
                          approver_id: !toggleSelectedNextApprover
                            ? item?.id
                            : '',
                        }));
                      }}
                    />
                  </View>
                </View>
              ))}
          </View>
        </View>
        <View
          style={{
            flexDirection: 'row',
            justifyContent: 'flex-end',
            marginTop: 40,
          }}>
          <TouchableOpacity
            onPress={() => {
              onClose();
            }}
            style={styles.btnCancel}>
            <Text style={styles.blueTxt}>Hủy</Text>
          </TouchableOpacity>
          <TouchableOpacity
            disabled={
              otVoucher.reason === '' || otVoucher.approver_id === ''
                ? true
                : false
            }
            onPress={() => {
              onSubmit();
            }}
            style={{
              ...styles.btnSubmit,
              backgroundColor:
                otVoucher.reason === '' || otVoucher.approver_id === ''
                  ? 'gray'
                  : '#5d78ff',
              padding: 10,
            }}>
            <Text style={styles.whiteTxt}>Gửi yêu cầu</Text>
          </TouchableOpacity>
        </View>
      </View>
      <Alert
        show={showAlert.isShow}
        showProgress={false}
        title={showAlert.title}
        message={showAlert.message}
        closeOnTouchOutside={true}
        closeOnHardwareBackPress={false}
        showConfirmButton={true}
        confirmText="Đóng"
        confirmButtonColor="#DD6B55"
        onConfirmPressed={onHideAlert}
      />
    </Modal>
  );
};

export default OverTimeModalAdd;
