import React, {useEffect, useState} from 'react';
import {
  SafeAreaView,
  ScrollView,
  TouchableOpacity,
  Image,
  Text,
  View,
  TextInput,
  Modal,
  Dimensions,
  StyleSheet,
  KeyboardAvoidingView,
} 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 {
  getImageByCode,
  getConfirmDayHistories,
  getCommentByCode,
  postRejectConfirmDate,
  postApproveConfirmDate,
  postComment,
  deleteApproveConfirmDay,
} from '../../../store/actions/UserAction';
const windowWidth = Dimensions.get('window').width;
const windowHeight = Dimensions.get('window').height;
const ConfirmModalAddNew = ({
  userDetails,
  onClose,
  alertMessage,
  detailItem,
  setApproveReqPayload,
}) => {
  const dispatch = useDispatch();
  const userDirectManagersList = useSelector(
    state => state.MyDirectManagers.myDirectManagers,
  );
  const confirmDay = useSelector(state => state.ConfirmDay.confirmDay);
  // init state
  const initComment = {
    code: '',
    content: '',
  };
  // state
  const [userManagerList, setUserManagerList] = useState([]);

  const [isNextApprover, setIsNextApprover] = useState(false);
  const [nextApproverId, setNextApproverId] = useState('');

  const [commentApprove, setCommentApprove] = useState();
  const [confirmDateComment, setConfirmDateComment] = useState([]);
  const [confirmDateDetail, setConfirmDateDetail] = useState(null);
  const [confirmDateHistory, setConfirmDateHistory] = useState([]);
  const [detailImage, setDetailImage] = useState([]);

  const [comment, setComment] = useState(initComment);
  //console.log('confirmDateDetail', confirmDateDetail);
  const onSelectManager = async (value, index, item) => {
    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('');
      }
    }
  };
  const onSubmitComment = async () => {
    if (comment.content) {
      const res = await dispatch(postComment(comment));
      if (res) {
        setComment(initComment);
        const responseComment = await dispatch(getCommentByCode(comment.code));
        Toast.show({
          type: 'success',
          text1: 'Hệ thống',
          text2: 'Bình luận thành công👍',
          style: {zIndex: 1001},
        });
        setConfirmDateComment(responseComment.reverse());
        return;
      }
    }
  };
  const onOpenDetail = async item => {
    setConfirmDateDetail(item);
    const responseImage = await dispatch(getImageByCode(item.id));
    //console.log(responseImage)
    setDetailImage(responseImage);
    const responseHistories = await dispatch(getConfirmDayHistories(item.id));
    setConfirmDateHistory(responseHistories);
    const responseComment = await dispatch(getCommentByCode(item.id));
    setConfirmDateComment(responseComment.reverse());
    const objectClone = JSON.parse(JSON.stringify(userDirectManagersList));
    let obj = [];
    objectClone.forEach(element => {
      element.checked = false;
      obj.push(element);
    });
    setUserManagerList(obj);
  };
  const onRejectRequest = async id => {
    const res = await dispatch(postRejectConfirmDate(id, commentApprove));
    if (res) {
      alertMessage('Thành công👍');
      setApproveReqPayload(prev => ({...prev, isRefresh: true}));
    } else {
      alertMessage('Thất bại👎');
    }
    onClose(null);
  };

  const onApproveRequest = async id => {
    const res = await dispatch(
      postApproveConfirmDate(id, commentApprove, nextApproverId),
    );
    if (res) {
      alertMessage('Thành công👍');
      setApproveReqPayload(prev => ({...prev, isRefresh: true}));
    } else {
      alertMessage('Thất bại👎');
    }
    onClose(null);
  };
  const downloadImage = item => {
    console.log('confirmDateDetail', confirmDateDetail);
    console.log(
      'aa',
      Moment(confirmDateDetail.finish).diff(confirmDateDetail.start, 'hour'),
    );
  };
  const deleteItem = async () => {
    const res = await dispatch(deleteApproveConfirmDay(detailItem.id));
    if (res.success) {
      onClose(null);
      Toast.show({
        type: 'success',
        text1: `Hệ thống`,
        text2: `Hủy yêu cầu thành công 💓`,
        style: {zIndex: 1001},
        visibilityTime: 2000,
      });
    } else {
      onClose(null);
      Toast.show({
        type: 'error',
        text1: `Hệ thống`,
        text2: `Hủy yêu cầu thất bại 💔`,
        style: {zIndex: 1001},
        visibilityTime: 2000,
      });
    }
    //console.log('deleteItem', detailItem);
  };
  const minutesToHours = (start, finish) => {
    //console.log(start, finish);
    let time = Moment(finish).diff(Moment(start), 'minutes');
    var Hours = Math.floor(time / 60);
    var minutes = time % 60;
    return `${Hours}:${minutes} giờ`;
  };
  useEffect(() => {
    onOpenDetail(detailItem);
  }, []);

  return (
    <Modal
      animationType="slide"
      transparent={true}
      visible={true}
      onRequestClose={() => {
        onClose(null);
      }}>
      <SafeAreaView>
        <ScrollView showsVerticalScrollIndicator={false}>
          <View style={styles.modalViewEdit}>
            <View style={styles.headerModalBottom}>
              <Text style={styles.titleModalBottom}>Chi tiết ngày công</Text>
              <TouchableOpacity
                onPress={() => {
                  onClose(null);
                }}>
                <Image
                  style={{height: 20, width: 20}}
                  source={IMAGES.IcClose}
                />
              </TouchableOpacity>
            </View>
            <View style={styles.bodyHeight}>
              <ScrollView>
                <View style={styles.bodyModal}>
                  <View style={{flex: 1, flexDirection: 'row'}}>
                    <Image
                      source={{
                        uri:
                          'https://meu.anawork.com' +
                          confirmDateDetail?.extend_creator_avatar,
                      }}
                      style={{width: 40, height: 40, borderRadius: 2}}
                    />
                    <View
                      style={{
                        flex: 1,
                        justifyContent: 'space-around',
                        marginLeft: 16,
                      }}>
                      <Text style={{fontSize: 14, fontWeight: '600'}}>
                        {confirmDateDetail?.extend_creator_full_name} -{' '}
                        {confirmDateDetail?.extend_creator_employee_code}
                      </Text>
                      <Text>{confirmDateDetail?.extend_creator_position}</Text>
                    </View>
                  </View>
                  {confirmDateDetail && (
                    <View style={{flex: 1, marginTop: 16}}>
                      <Text
                        style={{
                          fontWeight: '500',
                          fontSize: 14,
                          marginBottom: 12,
                        }}>
                        Thông tin chung
                      </Text>

                      <View style={styles.commonDetail}>
                        <Text style={styles.textMediumGrey}>Từ ngày</Text>
                        <Text>
                          {`${Moment(confirmDateDetail.start).format(
                            'DD/MM/YYYY HH:mm',
                          )} `}
                        </Text>
                      </View>
                      <View style={styles.commonDetail}>
                        <Text style={styles.textMediumGrey}>Đến ngày</Text>
                        <Text>
                          {`${Moment(confirmDateDetail.finish).format(
                            'DD/MM/YYYY HH:mm',
                          )}`}
                        </Text>
                      </View>
                      <View style={styles.commonDetail}>
                        <Text style={styles.textMediumGrey}>
                          Thời gian nghỉ
                        </Text>
                        <Text>
                          {minutesToHours(
                            confirmDateDetail.start,
                            confirmDateDetail.finish,
                          )}
                        </Text>
                      </View>
                      <View style={styles.commonDetail}>
                        <Text style={[styles.textMediumGrey, {flex: 1}]}>
                          Lý do
                        </Text>
                        <Text
                          style={{
                            flex: 1,
                            textAlign: 'right',
                          }}>
                          {confirmDateDetail.reason}
                        </Text>
                      </View>
                      <View style={styles.commonDetail}>
                        <Text style={[styles.textMediumGrey, {fontSize: 12}]}>
                          Tệp đính kèm
                        </Text>
                        {
                          <View style={styles.attachment}>
                            {
                              //physical_path.slice(30)
                              detailImage.length > 0 &&
                                detailImage.map((item, index) => (
                                  <ButtonComponent
                                    key={index}
                                    text={item.file_name}
                                    textStyle={{fontSize: 13, color: '#5d78ff'}}
                                    onPress={() => downloadImage(item)}
                                  />
                                ))
                            }
                            {detailImage.length == 0 && (
                              <Text style={{fontSize: 13, color: '#757575'}}>
                                Không có tệp đính kèm
                              </Text>
                            )}
                          </View>
                        }
                      </View>
                    </View>
                  )}
                  <View style={{flex: 1, marginTop: 16}}>
                    <Text
                      style={{
                        fontWeight: '500',
                        fontSize: 14,
                        marginBottom: 12,
                      }}>
                      Lịch sử duyệt
                    </Text>
                    {confirmDateHistory &&
                      confirmDateHistory?.map((item, index) => (
                        <View key={index} style={{flexDirection: 'row'}}>
                          <Image
                            source={{
                              uri:
                                'https://meu.anawork.com' +
                                item.extend_approver_avatar,
                            }}
                            style={styles.avatarApprove}
                          />
                          <View>
                            <View
                              style={{
                                flexDirection: 'row',
                                justifyContent: 'space-between',
                                width: '83%',
                              }}>
                              <View
                                style={{
                                  justifyContent: 'space-between',
                                  marginLeft: 8,
                                }}>
                                <Text>{item.extend_approver_full_name}</Text>
                                <View style={{flexDirection: 'row'}}>
                                  {item.extend_approved_status_name ==
                                    'APPROVED' && (
                                    <Image
                                      style={{height: 16, width: 16}}
                                      source={IMAGES.uCheck}
                                    />
                                  )}
                                  {item.extend_approved_status_name ==
                                    'PENDING' && (
                                    <Image source={IMAGES.uMinus} />
                                  )}
                                  {item.extend_approved_status_name ==
                                    'REJECTED' && (
                                    <Image
                                      source={IMAGES.IcReject}
                                      style={{
                                        height: 12,
                                        width: 12,
                                        alignSelf: 'center',
                                      }}
                                    />
                                  )}
                                  <Text
                                    style={{
                                      color: item.extend_approved_status_color,
                                      fontStyle: 'italic',
                                      fontSize: 12,
                                    }}>
                                    {item.extend_approved_status_name ==
                                      'APPROVED' && 'Đã duyệt'}
                                    {item.extend_approved_status_name ==
                                      'PENDING' && 'Đang chờ'}
                                    {item.extend_approved_status_name ==
                                      'REJECTED' && 'Đã từ chối'}
                                  </Text>
                                </View>
                              </View>
                              <Text style={{fontSize: 12, color: '#959595'}}>
                                {Moment(item.created_at).format('DD/MM/YYYY')}
                              </Text>
                            </View>
                            <View style={{marginLeft: 8}}>
                              {/* {item.comment && (
                                <Text style={{fontSize: 13, color: '#757575'}}>
                                  {item.comment}
                                </Text>
                              )} */}
                            </View>
                          </View>
                        </View>
                      ))}
                    {confirmDateDetail?.extend_approved_status_name ==
                      'PENDING' &&
                      confirmDateDetail?.approver_id == userDetails.id && (
                        <View style={{flexDirection: 'row'}}>
                          <Image
                            source={{
                              uri:
                                'https://meu.anawork.com' + userDetails.avatar,
                            }}
                            style={styles.avatarApprove}
                          />
                          <View>
                            <View
                              style={{
                                flexDirection: 'row',
                                justifyContent: 'space-between',
                                width: '83%',
                              }}>
                              <View
                                style={{
                                  justifyContent: 'space-between',
                                  marginLeft: 8,
                                }}>
                                <Text>
                                  {confirmDateDetail.extend_approver_full_name}
                                </Text>
                                <View style={{flexDirection: 'row'}}>
                                  {confirmDateDetail.extend_approved_status_name ==
                                  'APPROVED' ? (
                                    <Image
                                      style={{height: 16, width: 16}}
                                      source={IMAGES.uCheck}
                                    />
                                  ) : (
                                    <Image source={IMAGES.uMinus} />
                                  )}
                                  <Text
                                    style={{
                                      color:
                                        confirmDateDetail.extend_approved_status_color,
                                      fontStyle: 'italic',
                                      fontSize: 12,
                                    }}>
                                    {confirmDateDetail.extend_approved_status_name ==
                                      'APPROVED' && 'Đã duyệt'}
                                    {confirmDateDetail.extend_approved_status_name ==
                                      'PENDING' && 'Đang chờ'}
                                    {confirmDateDetail.extend_approved_status_name ==
                                      'REJECTED' && 'Đã từ chối'}
                                  </Text>
                                </View>
                              </View>
                              <Text style={{fontSize: 12, color: '#959595'}}>
                                {Moment().format('DD/MM/YYYY')}
                              </Text>
                            </View>
                            <View style={{marginLeft: 8}}>
                              <View style={styles.wrapperComment}>
                                <TextInput
                                  placeholder="Nhập lý do tại đây"
                                  style={styles.commentInput}
                                  multiline
                                  value={commentApprove}
                                  onChangeText={text => {
                                    setCommentApprove(text);
                                  }}
                                />
                              </View>
                            </View>
                          </View>
                        </View>
                      )}
                  </View>
                  {confirmDateDetail?.approver_id == userDetails.id && (
                    <View
                      style={{
                        marginTop: 12,
                        flexDirection: 'row',
                        alignItems: 'center',
                      }}>
                      <CheckBox
                        boxType="square"
                        animationDuration={0.3}
                        value={isNextApprover}
                        onValueChange={value => setIsNextApprover(value)}
                        lineWidth={2}
                      />
                      <Text
                        style={{
                          fontSize: 13,
                          color: '#434349',
                          marginLeft: 10,
                        }}>
                        Chọn người duyệt tiếp theo
                      </Text>
                    </View>
                  )}

                  {isNextApprover &&
                    userManagerList.map((item, index) => (
                      <View
                        key={index}
                        style={{
                          flexDirection: 'row',
                          justifyContent: 'space-between',
                          alignItems: 'center',
                          marginTop: 12,
                        }}>
                        <Image
                          source={{
                            uri: 'https://meu.anawork.com' + item.avatar,
                          }}
                          style={styles.avatarApprove}
                        />
                        <Text
                          style={{
                            fontSize: 16,
                            fontWeight: '500',
                            marginLeft: 10,
                          }}>{`${item.extend_user_full_name}`}</Text>
                        <CheckBox
                          disabled={false}
                          value={item.checked}
                          onValueChange={newValue =>
                            onSelectManager(newValue, index, item)
                          }
                          boxType="square"
                          animationDuration={0.3}
                          lineWidth={1}
                          key={index}
                        />
                      </View>
                    ))}
                  <View style={{marginTop: 16}}>
                    <Text
                      style={{
                        fontWeight: '500',
                        fontSize: 14,
                        marginBottom: 12,
                      }}>
                      Bình luận
                    </Text>
                    {/*others comment*/}
                    {confirmDateComment.length > 0 &&
                      confirmDateComment.map((item, index) => {
                        return (
                          <View style={styles.commentHistories} key={index}>
                            <Image
                              source={{
                                uri:
                                  'https://meu.anawork.com' +
                                  item.extend_staff_avatar,
                              }}
                              style={styles.avatarComment}
                            />
                            <View style={styles.commentBox}>
                              <View
                                style={{
                                  flexDirection: 'row',
                                  justifyContent: 'space-between',
                                }}>
                                <Text
                                  style={{
                                    color: '#434349',
                                    fontSize: 12,
                                    fontWeight: '500',
                                  }}>
                                  {item.extend_staff_full_name}
                                </Text>
                                <Text style={{color: '#959595', fontSize: 10}}>
                                  {Moment(item.created_at).format(
                                    'DD/MM/YYYY hh:mm',
                                  )}
                                </Text>
                              </View>
                              <Text
                                style={{
                                  color: '#666666',
                                  fontSize: 13,
                                  marginTop: 8,
                                }}>
                                {item.content}
                              </Text>
                            </View>
                          </View>
                        );
                      })}
                    {/*my comment*/}
                    <View
                      style={[
                        styles.commentHistories,
                        {marginTop: 16, marginBottom: 20},
                      ]}>
                      <Image
                        source={{
                          uri: 'https://meu.anawork.com' + userDetails.avatar,
                        }}
                        style={styles.avatarComment}
                      />

                      <View style={{width: '88%', position: 'relative'}}>
                        <KeyboardAvoidingView
                          behavior={
                            Platform.OS === 'ios' ? 'padding' : 'height'
                          }>
                          <TextInputComponent
                            style={styles.commentText}
                            styleAreaInput={{backgroundColor: 'white'}}
                            multiline
                            placeholder="Nhập bình luận ở đây"
                            onChangeText={text => {
                              setComment({
                                content: text,
                                code: confirmDateDetail.id,
                              });
                            }}
                            noBorder
                            value={comment.content}
                            autoCapitalize="none"
                          />
                        </KeyboardAvoidingView>

                        <View style={{position: 'absolute', right: 0, top: 10}}>
                          <TouchableOpacity onPress={onSubmitComment}>
                            <Image
                              style={{height: 16, width: 16, marginRight: 4}}
                              source={IMAGES.IcSend}
                            />
                          </TouchableOpacity>
                        </View>
                      </View>
                    </View>
                  </View>
                </View>
              </ScrollView>
            </View>
            {/* bottom modal */}
            <View style={styles.bottomModal}>
              <TouchableOpacity
                style={styles.btnCancel}
                onPress={() => onClose(null)}>
                <Text
                  style={{color: '#5d78ff', fontSize: 14, fontWeight: '500'}}>
                  Hủy
                </Text>
              </TouchableOpacity>
              {confirmDateDetail?.approver_id !== userDetails.id &&
                detailItem.extend_approved_status_name === 'PENDING' && (
                  <ButtonComponent
                    style={{flexDirection: 'row', alignItems: 'center'}}
                    text={'Xóa yêu cầu'}
                    textStyle={{
                      color: '#ff0a3a',
                      fontSize: 14,
                      fontWeight: '500',
                    }}
                    leftIcon={IMAGES.IcReject}
                    styleIcon={{height: 15, width: 15, marginRight: 4}}
                    onPress={deleteItem}
                  />
                )}
              {confirmDateDetail?.approver_id == userDetails.id &&
                confirmDateDetail?.extend_approved_status_name ===
                  'PENDING' && (
                  <View style={{flexDirection: 'row'}}>
                    <TouchableOpacity
                      style={styles.btnReject}
                      onPress={() => {
                        onRejectRequest(confirmDateDetail.id);
                      }}>
                      <Image
                        style={{height: 16, width: 16, marginRight: 4}}
                        source={IMAGES.IcReject}
                      />
                      <Text
                        style={{
                          color: '#ff0a3a',
                          fontSize: 14,
                          fontWeight: '500',
                        }}>
                        Từ chối
                      </Text>
                    </TouchableOpacity>
                    <TouchableOpacity
                      style={styles.btnAccept}
                      onPress={() => {
                        onApproveRequest(confirmDateDetail.id);
                      }}>
                      <Image
                        style={{height: 16, width: 16, marginRight: 4}}
                        source={IMAGES.IcAccept}
                      />
                      <Text
                        style={{
                          color: 'white',
                          fontSize: 14,
                          fontWeight: '500',
                        }}>
                        Duyệt yêu cầu
                      </Text>
                    </TouchableOpacity>
                  </View>
                )}
            </View>
          </View>
        </ScrollView>
      </SafeAreaView>
    </Modal>
  );
};
const styles = StyleSheet.create({
  //modal detail
  modalViewEdit: {
    backgroundColor: 'white',
    borderRadius: 20,
    padding: 16,
    height: windowHeight,
    shadowColor: '#000',
    shadowOffset: {
      width: 0,
      height: 2,
    },
    shadowOpacity: 0.25,
    shadowRadius: 4,
    elevation: 5,
    marginTop: 20,
  },
  headerModalBottom: {
    paddingRight: 10,
    paddingLeft: 10,
    flexDirection: 'row',
    justifyContent: 'space-between',
  },
  titleModalBottom: {
    fontSize: 16,
    fontWeight: '500',
  },

  bodyHeightCreate: {
    height: '75%',
  },
  bodyModal: {
    flex: 1,
    paddingHorizontal: 10,
    marginTop: 16,
  },
  commonDetail: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    fontSize: 14,
    marginBottom: 12,
    fontFamily: 'Roboto',
    marginTop: 10,
  },
  attachment: {
    // borderColor: '#c4c4c4',
    // borderStyle: 'dashed',
    // borderWidth: 0.5,
    // borderRadius: 4,
    // height: 60,
    width: '50%',
    justifyContent: 'center',
    alignItems: 'center',
  },
  checkbox: {
    alignSelf: 'center',
    height: 16,
    width: 16,
    marginRight: 4,
  },
  commentHistories: {
    flexDirection: 'row',
    marginBottom: 10,
  },
  textMediumGrey: {
    color: '#757575',
  },
  avatarApprove: {
    width: 32,
    height: 32,
    borderRadius: 4,
  },
  avatarComment: {
    width: 32,
    height: 32,
    borderRadius: 32,
  },
  commentBox: {
    backgroundColor: '#e5eaf0',
    width: '88%',
    marginLeft: 8,
    paddingHorizontal: 12,
    paddingVertical: 8,
    borderTopRightRadius: 4,
    borderBottomRightRadius: 4,
    borderBottomLeftRadius: 4,
  },
  commentText: {
    marginLeft: 8,
    width: '100%',
    color: '#959595',
    fontSize: 12,
    borderBottomColor: '#5c65dc',
    borderBottomWidth: 1,
    paddingLeft: 8,
    paddingRight: 28,
    paddingVertical: 10,
  },
  bottomModal: {
    height: 50,
    width: '100%',
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'space-between',
    paddingHorizontal: 8,
  },
  wrapperComment: {
    borderColor: '#5d78ff',
    borderStyle: 'dashed',
    borderWidth: 0.5,
    borderRadius: 4,
    height: 60,
    width: '81%',
    padding: 8,
  },
  commentInput: {
    fontSize: 13,
  },
  btnAccept: {
    flexDirection: 'row',
    paddingHorizontal: 8,
    paddingVertical: 12,
    backgroundColor: '#5d78ff',
    borderRadius: 4,
  },
  btnReject: {
    flexDirection: 'row',
    paddingHorizontal: 8,
    paddingVertical: 12,
    marginRight: 8,
  },
  btnClose: {
    width: 20,
    height: 20,
    position: 'absolute',
    top: -10,
    right: 0,
  },
});
export default ConfirmModalAddNew;
