/* 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,
  ScrollView,
  TextInput,
  TouchableOpacity,
  View,
  KeyboardAvoidingView,
} from 'react-native';
import ButtonComponent from '../../../components/ButtonComponent';
import {launchImageLibrary} from 'react-native-image-picker';
import {useDispatch, useSelector} from 'react-redux';
import {getUserInfoById} from '../../../store/actions/CommonAction';
import {
  getAttachmentByOTId,
  getCommentList,
  getOTbyId,
  getOTHistoriesByOTId,
  getUserDirectManagers,
  postApproveOTVoucher,
  postAttachmentToComment,
  postLikeComment,
  postNewComment,
  deleteOtTicketRequest,
  postRejectOTVoucher,
} from '../../../store/actions/UserAction';
import {IMAGES} from '../../../values/images';
import styles from '../style';
import Toast from 'react-native-toast-message';
import AppText from '../../../components/AppText';
const OverTimeModalDetail = props => {
  const dispatch = useDispatch();
  const userDetails = useSelector(state => state.UserInfo.userInfo);
  const {onClose, modalDetailId, setPayloadOtApproveList} = props;

  const [OTDetail, setOTDetail] = useState(null);
  const [OTDetailAttachmentList, setOTDetailAttachmentList] = useState([]);
  const [OTDetailHistoriesList, setOTDetailHistoriesList] = useState([]);
  const [comment, setComment] = useState('');
  const [toggleNextApprover, setToggleNextApprover] = useState(false);
  const [myDirectorManagerList, setMyDirectorManagerList] = useState([]);
  const [toggleSelectedNextApprover, setToggleSelectedNextApprover] =
    useState(false);
  const [comment2, setComment2] = useState('');
  const [commentAttachmentList, setCommentAttachmentList] = useState([]);
  const [commentList, setCommentList] = useState([]);
  const [nextApproverId, setNextApproverId] = useState('');
  const [historyUserData, setHistoryUserData] = useState(null);

  const getOTDetailId = async () => {
    const res = await dispatch(getOTbyId(modalDetailId));
    setOTDetail(res);
  };

  const getAttachmentByOtID = async () => {
    const res = await dispatch(getAttachmentByOTId(modalDetailId));
    setOTDetailAttachmentList(res);
  };

  const getOTHistoriesByOtId = async () => {
    const res = await dispatch(getOTHistoriesByOTId(modalDetailId));
    setOTDetailHistoriesList(res);
  };

  const getMyDirectorManagerList = async () => {
    const res = await dispatch(getUserDirectManagers());
    setMyDirectorManagerList(res);
  };

  const onPostAttachmentOfComment = async commentId => {
    const res = await dispatch(
      postAttachmentToComment(commentId, commentAttachmentList),
    );
    //console.log('onPostAttachmentOfComment', res);
    if (res) {
      setCommentAttachmentList([]);
      getCommentOfModalDetailList();
    }
  };

  const onPostNewComment = async () => {
    let body = {
      code: `${modalDetailId}`,
      content: `${comment2}`,
      number_of_like: 0,
      reply_for: null,
    };
    const res = await dispatch(postNewComment(body));
    if (res) {
      let commentId = res.id;
      if (commentAttachmentList.length && commentId) {
        onPostAttachmentOfComment(commentId);
      }
    }
  };

  const getCommentOfModalDetailList = async () => {
    const res = await dispatch(getCommentList(modalDetailId));
    setCommentList(res);
  };

  const onApproverOTVoucher = async () => {
    let body = {
      OtId: modalDetailId,
      body: {
        comment: comment,
        nextApproverId: nextApproverId,
      },
    };
    const res = await dispatch(postApproveOTVoucher(body));
    if (res) {
      Toast.show({
        type: 'success',
        text1: 'Hệ thống',
        text2: 'Lưu yêu cầu tăng ca thành công👍',
        style: {zIndex: 1001},
      });
      setPayloadOtApproveList(prev => ({...prev, isRefresh: true}));
    } else {
      Toast.show({
        type: 'error',
        text1: 'Hệ thống',
        text2: 'Thao tác không thành công👍',
        style: {zIndex: 1001},
      });
    }
    onClose();
  };
  const onRejectOTVoucher = async () => {
    const res = await dispatch(postRejectOTVoucher(modalDetailId, comment));
    if (res) {
      Toast.show({
        type: 'success',
        text1: 'Hệ thống',
        text2: 'Từ chối yêu cầu tăng ca thành công👍',
        style: {zIndex: 1001},
      });
      setPayloadOtApproveList(prev => ({...prev, isRefresh: true}));
    } else {
      Toast.show({
        type: 'error',
        text1: 'Hệ thống',
        text2: 'Từ chối yêu cầu tăng ca không thành côngg👍',
        style: {zIndex: 1001},
      });
    }
    onClose();
  };
  const onDeleteRequest = async () => {
    const res = await dispatch(deleteOtTicketRequest(OTDetail.id));
    if (res) {
      Toast.show({
        type: 'success',
        text1: 'Hệ thống',
        text2: 'Hủy thành công👍',
        style: {zIndex: 1001},
      });
      onClose(null);
    } else {
      Toast.show({
        type: 'error',
        text1: 'Hệ thống',
        text2: 'Hủy  thất bại 💔',
        style: {zIndex: 1001},
      });
      onClose(null);
    }
  };
  const onPostNewLikeOfComment = async commentId => {
    const res = await dispatch(postLikeComment(commentId));
    if (res) {
      getCommentOfModalDetailList();
    }
  };

  const getUserById = async userId => {
    const res = await dispatch(getUserInfoById(userId));
    setHistoryUserData(res);
  };

  useEffect(() => {
    getCommentOfModalDetailList();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  useEffect(() => {
    getOTDetailId();
    getAttachmentByOtID();
    getOTHistoriesByOtId();
    getMyDirectorManagerList();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [modalDetailId]);

  useEffect(() => {
    if (OTDetailHistoriesList.length === 0) {
      getUserById(OTDetail?.approver_id || OTDetail?.staff_id);
    }
  }, [OTDetail]);

  //console.log('OTDetailAttachmentList', OTDetailAttachmentList);
  return (
    <Modal
      animationType="slide"
      transparent={true}
      visible={true}
      propagateSwipe={true}
      onRequestClose={() => onClose(null)}>
      <ScrollView style={styles.modalView} showsVerticalScrollIndicator={false}>
        <View style={{flexDirection: 'row', justifyContent: 'space-between'}}>
          <AppText style={styles.modalTitle}>Chi tiết tăng ca</AppText>
          <TouchableOpacity onPress={() => onClose(null)}>
            <Image source={IMAGES.IcClose} />
          </TouchableOpacity>
        </View>
        <View style={{flexDirection: 'row', marginTop: 10}}>
          <Image
            source={{
              uri: 'https://meu.anawork.com' + OTDetail?.extend_creator_avatar,
            }}
            style={styles.ImgAvatar}
          />
          <View style={{marginLeft: 15}}>
            <AppText
              style={
                styles.modalTitle
              }>{`${OTDetail?.extend_creator_full_name}`}</AppText>
            <AppText>{OTDetail?.extend_creator_department}</AppText>
          </View>
        </View>

        <View style={{marginTop: 10}}>
          <AppText style={styles.modalTitle}>Thông tin tăng ca</AppText>
          <View style={styles.rowView}>
            <AppText>Từ ngày</AppText>
            <View
              style={{
                alignItems: 'flex-end',
                flexDirection: 'row',
                justifyContent: 'flex-end',
                borderBottomWidth: 0.5,
              }}>
              <AppText>{Moment(OTDetail?.start).format('DD/MM/YYYY')}</AppText>
            </View>
          </View>
          <View style={styles.rowView}>
            <AppText>Giờ</AppText>
            <View
              style={{
                alignItems: 'flex-end',
                flexDirection: 'row',
                justifyContent: 'flex-end',
                borderBottomWidth: 0.5,
              }}>
              <AppText>{Moment(OTDetail?.start).format('HH:mm')}</AppText>
            </View>
          </View>
          <View style={styles.rowView}>
            <AppText>Đến ngày</AppText>
            <View
              style={{
                alignItems: 'flex-end',
                flexDirection: 'row',
                justifyContent: 'flex-end',
                borderBottomWidth: 0.5,
              }}>
              <AppText>{Moment(OTDetail?.finish).format('DD/MM/YYYY')}</AppText>
            </View>
          </View>
          <View style={styles.rowView}>
            <AppText>Giờ</AppText>
            <View
              style={{
                alignItems: 'flex-end',
                flexDirection: 'row',
                justifyContent: 'flex-end',
                borderBottomWidth: 0.5,
              }}>
              <AppText>{Moment(OTDetail?.finish).format('HH:mm')}</AppText>
            </View>
          </View>
          <View style={styles.rowView}>
            <AppText style={{flex: 1}}>Lý do</AppText>
            <AppText style={{flex: 1, textAlign: 'right'}}>
              {OTDetail?.reason}
            </AppText>
          </View>
          <View style={styles.rowView}>
            <AppText style={{flex: 1}}>Tệp đính kèm</AppText>
            <View
              style={{
                flex: 2,
                marginTop: 10,
              }}>
              {OTDetailAttachmentList && OTDetailAttachmentList.length !== 0 ? (
                OTDetailAttachmentList.map((el, index) => {
                  // <Image
                  //   key={index}
                  //   source={{uri: el?.uri}}
                  //   style={styles.imgUpload}
                  // />;
                  return <AppText numberOfLines={1}>{el.file_name}</AppText>;
                })
              ) : (
                <AppText style={{fontSize: 12, textAlign: 'right'}}>
                  Không có tệp đính kèm
                </AppText>
              )}
            </View>
          </View>

          {/* Lịch sử duyệt */}
          <View style={{marginTop: 20}}>
            <AppText
              style={[
                styles.modalTitle,
                {
                  marginBottom: 10,
                },
              ]}>
              Lịch sử duyệt
            </AppText>
            {OTDetailHistoriesList && OTDetailHistoriesList.length !== 0 ? (
              OTDetailHistoriesList.map((item, index) => (
                <View
                  key={item?.id}
                  style={{
                    flexDirection: 'row',
                    marginTop: 16,
                  }}>
                  <Image
                    source={{
                      uri:
                        'https://meu.anawork.com' + item.extend_approver_avatar,
                    }}
                    style={{width: 50, height: 50, borderRadius: 8}}
                  />
                  <View>
                    <AppText
                      style={{
                        fontSize: 16,
                        fontWeight: '500',
                        marginLeft: 10,
                      }}>{`${item.extend_approver_full_name}`}</AppText>
                    <View
                      style={{
                        flexDirection: 'row',
                        alignItems: 'center',
                        marginLeft: 8,
                      }}>
                      {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',
                          }}
                        />
                      )}
                      <AppText
                        style={{
                          fontSize: 12,
                          fontWeight: '500',
                          color: `${item.extend_approved_status_color}`,
                          fontStyle: 'italic',
                        }}>
                        {`${item.extend_approved_status_code}`}
                      </AppText>
                    </View>
                    {item.comment && (
                      <AppText
                        style={{
                          fontSize: 14,
                          fontWeight: '500',
                        }}>{`${item.comment}`}</AppText>
                    )}
                  </View>
                </View>
              ))
            ) : (
              <View>
                <View style={{flexDirection: 'row', alignItems: 'center'}}>
                  <Image
                    source={{
                      uri: 'https://meu.anawork.com' + historyUserData?.avatar,
                    }}
                    style={{width: 50, height: 50, borderRadius: 8}}
                  />
                  <View>
                    <AppText
                      style={{
                        fontSize: 16,
                        fontWeight: '500',
                        marginLeft: 10,
                      }}>{`${
                      OTDetail?.extend_approver_full_name ||
                      OTDetail?.extend_creator_full_name
                    }`}</AppText>
                    <View
                      style={{
                        flexDirection: 'row',
                        alignItems: 'center',
                        marginLeft: 8,
                      }}>
                      <Image source={IMAGES.IcYellowMinus} />
                      <AppText
                        style={{
                          fontSize: 12,
                          fontWeight: '500',
                          color: '#ffa117',
                        }}>
                        Đang chờ
                      </AppText>
                    </View>
                  </View>
                </View>
                {OTDetail?.approver_id == userDetails.id &&
                  OTDetail?.extend_approved_status_name === 'PENDING' && (
                    <View>
                      <KeyboardAvoidingView
                        behavior={Platform.OS === 'ios' ? 'padding' : 'height'}>
                        <TextInput
                          multiline={true}
                          numberOfLines={3}
                          placeholder="Nhập bình luận..."
                          value={comment}
                          onChangeText={text => {
                            setComment(text);
                          }}
                          style={{
                            borderWidth: 1,
                            marginTop: 10,
                            borderColor: 'lightgray',
                            borderRadius: 8,
                          }}
                        />
                      </KeyboardAvoidingView>
                    </View>
                  )}
              </View>
            )}
          </View>

          {OTDetail?.extend_approved_status_name === 'PENDING' && (
            <View
              style={{
                flexDirection: 'row',
                marginTop: 16,
                marginBottom: 16,
                alignItems: 'center',
              }}>
              <CheckBox
                disabled={false}
                value={toggleNextApprover}
                onValueChange={() => setToggleNextApprover(!toggleNextApprover)}
              />
              <AppText
                style={{
                  fontSize: 16,
                  fontWeight: '500',
                  marginLeft: 10,
                }}>
                Chọn người duyệt tiếp theo
              </AppText>
            </View>
          )}
          {myDirectorManagerList.length !== 0 ? (
            toggleNextApprover &&
            myDirectorManagerList.map((el, 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' + el?.avatar,
                    }}
                    style={{width: 50, height: 50, borderRadius: 8}}
                  />
                  <View>
                    <AppText
                      style={{
                        fontSize: 16,
                        fontWeight: '500',
                        marginLeft: 10,
                      }}>{`${el?.extend_user_full_name}`}</AppText>
                    <AppText
                      style={{
                        fontSize: 12,
                        fontWeight: '500',
                        marginLeft: 10,
                      }}>
                      {`${el?.position} - ${el?.department}`}
                    </AppText>
                  </View>
                </View>
                <View>
                  <CheckBox
                    disabled={false}
                    value={toggleSelectedNextApprover}
                    onValueChange={() => {
                      setToggleSelectedNextApprover(
                        !toggleSelectedNextApprover,
                      );
                      setNextApproverId(!toggleNextApprover ? el?.id : '');
                    }}
                  />
                </View>
              </View>
            ))
          ) : (
            <AppText
              style={{
                fontSize: 12,
              }}>
              Không có người duyệt
            </AppText>
          )}
        </View>

        {/* Bình luận */}
        <View>
          <AppText style={[styles.modalTitle]}>Bình luận</AppText>
          {commentAttachmentList.length > 0 && (
            <View
              style={{
                marginTop: 8,
                marginBottom: 8,
                flexDirection: 'row',
                justifyContent: 'space-between',
              }}>
              <View style={{width: '15%'}}></View>
              <View style={{width: '84%'}}>
                {commentAttachmentList.map((imageItem, index) => (
                  <Image
                    key={index}
                    source={{uri: imageItem.uri}}
                    style={styles.imgUpload}
                  />
                ))}
              </View>
            </View>
          )}
          {commentList &&
            commentList?.length !== 0 &&
            commentList?.map((el, index) => (
              <View key={index} style={{marginTop: 5}}>
                <View
                  style={{
                    flexDirection: 'row',
                    marginTop: 16,
                  }}>
                  <Image
                    source={{
                      uri: 'https://meu.anawork.com' + el.extend_staff_avatar,
                    }}
                    style={{width: 50, height: 50, borderRadius: 8}}
                  />
                  <View>
                    <AppText
                      style={{
                        fontSize: 16,
                        fontWeight: '500',
                        marginLeft: 10,
                      }}>{`${el.extend_staff_full_name}`}</AppText>
                    <AppText
                      style={{
                        fontSize: 12,
                        fontWeight: '500',
                        marginLeft: 10,
                      }}>
                      {`${Moment(el.created_at).format('HH:mm - DD/MM/YYYY')}`}
                    </AppText>
                    <AppText
                      style={{
                        fontSize: 14,
                        fontWeight: '500',
                        marginLeft: 10,
                        marginTop: 8,
                      }}>{`${el.content}`}</AppText>
                  </View>
                </View>
                <View
                  style={{
                    flexDirection: 'row',
                    alignItems: 'center',
                    justifyContent: 'space-between',
                    marginLeft: 50,
                    marginTop: 12,
                  }}>
                  <TouchableOpacity
                    style={{
                      marginLeft: 10,
                      flex: 1,
                    }}
                    onPress={() => onPostNewLikeOfComment(el?.id)}>
                    <View
                      style={{
                        flexDirection: 'row',
                        alignItems: 'center',
                      }}>
                      <AppText>{`${el.number_of_like}`}</AppText>
                      <Image
                        source={IMAGES.IcLike}
                        style={{
                          width: 20,
                          height: 20,
                          borderColor: 'black',
                          marginLeft: 4,
                        }}
                      />
                    </View>
                  </TouchableOpacity>
                </View>
              </View>
            ))}
          <View>
            <View
              style={{
                flexDirection: 'row',
                alignItems: 'center',
                justifyContent: 'space-between',
              }}>
              <View
                style={{
                  width: '15%',
                }}>
                <Image
                  source={{
                    uri: 'https://meu.anawork.com' + userDetails?.avatar,
                  }}
                  style={{width: 50, height: 50, borderRadius: 8}}
                />
              </View>
              <View
                style={{
                  width: '84%',
                }}>
                <View>
                  <KeyboardAvoidingView
                    behavior={Platform.OS === 'ios' ? 'padding' : 'height'}>
                    <TextInput
                      multiline={true}
                      numberOfLines={2}
                      placeholder="Nhập bình luận ở đây..."
                      value={comment2}
                      onChangeText={text => {
                        setComment2(text);
                      }}
                      style={{
                        borderWidth: 1,
                        marginTop: 10,
                        borderColor: 'lightgray',
                        borderTopWidth: 0,
                        borderLeftWidth: 0,
                        borderRightWidth: 0,
                        borderBottomColor: '#5c65dc',
                        position: 'relative',
                      }}
                    />
                  </KeyboardAvoidingView>

                  <View style={{position: 'absolute', right: 8, bottom: 16}}>
                    <TouchableOpacity
                      onPress={() => {
                        onPostNewComment();
                        setComment2('');
                      }}>
                      <Image
                        source={IMAGES.IcSendMessage}
                        style={{width: 15, height: 15}}
                      />
                    </TouchableOpacity>
                  </View>
                </View>
                <View
                  style={{
                    flexDirection: 'row',
                    marginTop: 12,
                    marginBottom: 16,
                  }}>
                  <View style={{marginRight: 12}}>
                    <TouchableOpacity>
                      <Image source={IMAGES.IcTextEditor} />
                    </TouchableOpacity>
                  </View>
                  <View style={{marginRight: 12}}>
                    <TouchableOpacity>
                      <Image source={IMAGES.IcEmoji} />
                    </TouchableOpacity>
                  </View>
                  <View style={{marginRight: 12}}>
                    <TouchableOpacity
                      onPress={() =>
                        launchImageLibrary(
                          {
                            mediaType: 'photo',
                            includeBase64: true,
                          },
                          response => {
                            if (!response.didCancel) {
                              setCommentAttachmentList(response.assets);
                            }
                          },
                        )
                      }>
                      <Image source={IMAGES.IcAttachment} />
                    </TouchableOpacity>
                  </View>
                </View>
              </View>
            </View>
          </View>
        </View>
        {/**Action button */}
        <View
          style={{
            flexDirection: 'row',
            justifyContent: 'space-between',
            marginTop: 30,
            marginBottom: 40,
          }}>
          <TouchableOpacity
            onPress={() => {
              onClose();
            }}
            style={styles.btnCancel}>
            <AppText style={styles.blueTxt}>Đóng</AppText>
          </TouchableOpacity>
          {OTDetail?.approver_id !== userDetails.id &&
            OTDetail?.extend_approved_status_name === 'PENDING' && (
              <ButtonComponent
                style={[styles.btnDelete, {padding: 10}]}
                text={'Xóa yêu cầu'}
                textStyle={styles.whiteTxt}
                onPress={onDeleteRequest}
              />
            )}
          {OTDetail?.approver_id === userDetails.id &&
            OTDetail?.extend_approved_status_name === 'PENDING' && (
              <View style={{flexDirection: 'row'}}>
                <ButtonComponent
                  style={[styles.btnDelete, {padding: 10, marginRight: 10}]}
                  text={'Từ chối'}
                  textStyle={styles.whiteTxt}
                  onPress={onRejectOTVoucher}
                />
                <ButtonComponent
                  style={[styles.btnSubmit, {padding: 10}]}
                  text={'Duyệt yêu cầu'}
                  textStyle={styles.whiteTxt}
                  onPress={onApproverOTVoucher}
                />
              </View>
            )}
        </View>
      </ScrollView>
    </Modal>
  );
};

export default OverTimeModalDetail;
