import React, {useMemo} from 'react';
import {
  Image,
  Modal,
  SafeAreaView,
  ScrollView,
  TouchableOpacity,
  View,
} from 'react-native';
import AppText from '../../../../components/AppText';
import config from '../../../../config';
import {IMAGES} from '../../../../values/images';
import styles, {modalRequestConfirmWorkdaysStyles} from '../../style';
import commonStyles from '../../../../styles/commonStyles';
import ButtonComponent from '../../../../components/ButtonComponent';
import CheckBox from '@react-native-community/checkbox';
import SelectDropdownComponent from '../../../../components/Select';
import moment from 'moment';
import DateTimePicker from 'react-native-modal-datetime-picker';
import TextInputComponent from '../../../../components/TextInputComponent';

const UserHeader = React.memo(
  ({userInfo, fullName}) => {
    return (
      <View style={[commonStyles.row, commonStyles.marginVertical10]}>
        <Image
          source={
            userInfo?.avatar
              ? {
                  uri: config.imageEndPoint + userInfo?.avatar,
                }
              : IMAGES.IcAvatarDefault
          }
          style={modalRequestConfirmWorkdaysStyles.avatarUser}
        />
        <View style={{marginLeft: 15}}>
          <AppText
            style={
              styles.modalTitle
            }>{`${fullName} - ${userInfo?.employee_code}`}</AppText>
          <AppText>{userInfo?.position}</AppText>
        </View>
      </View>
    );
  },
  function areEqual(prevProps, nextProps) {
    return (
      prevProps.userInfo === nextProps.userInfo ||
      prevProps.fullName === nextProps.fullName
    );
  },
);
const Attachments = React.memo(
  ({
    confirmDateRequestImage = [],
    onDeleteConfirmDateRequestImage,
    openGallery,
  }) => {
    return (
      <View style={modalRequestConfirmWorkdaysStyles.rowView}>
        <AppText>Tệp đính kèm</AppText>
        <View style={{flexDirection: 'row'}}>
          {confirmDateRequestImage.length > 0 &&
            confirmDateRequestImage.map((item, index) => {
              //console.log("item", item[0].uri)
              return (
                <View key={index}>
                  <ButtonComponent
                    iconSource={IMAGES.IcReject}
                    style={styles.btnClose}
                    onPress={() => onDeleteConfirmDateRequestImage(index)}
                  />
                  <Image source={{uri: item.uri}} style={styles.imgUpload} />
                </View>
              );
            })}

          {confirmDateRequestImage.length < 3 && (
            <ButtonComponent
              style={
                modalRequestConfirmWorkdaysStyles.addConfirmDateRequestImageBtn
              }
              onPress={openGallery}
              iconSource={IMAGES.IcAddMoreImg}
            />
          )}
        </View>
      </View>
    );
  },
);
const DirectManagers = ({
  directManagersList,
  onSelectManagerConfirmWorkingDayRequest,
}) => {
  return (
    <View style={{marginTop: 10}}>
      <AppText
        style={[
          styles.modalTitle,
          {
            marginBottom: 10,
          },
        ]}>
        Người duyệt
      </AppText>
      {directManagersList.map((item, index) => (
        <View
          key={index}
          style={[commonStyles.row, commonStyles.spaceBetweenCenter]}>
          <View
            style={{
              flexDirection: 'row',
              alignItems: 'center',
              paddingLeft: 18,
            }}>
            <Image
              source={{
                uri: config.imageEndPoint + item.avatar,
              }}
              style={styles.avatarApprove}
            />
            <AppText
              style={{
                marginLeft: 10,
              }}>{`${item.extend_user_full_name}`}</AppText>
          </View>
          <View style={{paddingRight: 10}}>
            <CheckBox
              disabled={false}
              value={item.isChecked}
              onValueChange={newValue =>
                onSelectManagerConfirmWorkingDayRequest(index, newValue)
              }
              boxType={'square'}
              animationDuration={0.3}
              lineWidth={1}
              key={index}
              tintColors={'#9E663C'}
            />
          </View>
        </View>
      ))}
    </View>
  );
};
const ButtonAction = ({
  onSubmitApproveConfirmWorkingDaysRequest,
  isRequest,
  onClose,
  userInfo,
  onSubmitConfirmWorkingDayRequest,
}) => {
  return (
    <View
      style={[
        commonStyles.row,
        commonStyles.marginVertical20,
        {
          justifyContent: 'flex-end',
        },
      ]}>
      <TouchableOpacity onPress={onClose} style={styles.btnCancel}>
        <AppText style={styles.blueTxt}>Hủy</AppText>
      </TouchableOpacity>
      {isRequest && (
        <TouchableOpacity
          style={styles.btnSubmit}
          onPress={onSubmitConfirmWorkingDayRequest}>
          <AppText style={styles.whiteTxt}>Gửi yêu cầu</AppText>
        </TouchableOpacity>
      )}
      {userInfo?.isApprover && userInfo?.confirmStatus && (
        <TouchableOpacity
          style={styles.btnSubmit}
          onPress={() =>
            onSubmitApproveConfirmWorkingDaysRequest(
              userInfo?.confirm_working_id,
            )
          }>
          <AppText style={styles.whiteTxt}>Duyệt yêu cầu</AppText>
        </TouchableOpacity>
      )}
    </View>
  );
};

const ModalRequestConfirmWorkingDays = props => {
  const {
    userInfo,
    onClose,
    isRequest = false,
    confirmDateRequestImage,
    onDeleteConfirmDateRequestImage,
    openGallery,
    setOpenTimePicker,
    confirmDateRequestTicket,
    openTimePicker,
    directManagersList,
    setConfirmDateRequestTicket,
    onSelectManagerConfirmWorkingDayRequest,
    onSubmitConfirmWorkingDayRequest,
    onSubmitApproveConfirmWorkingDaysRequest,
  } = props;

  const fullName = useMemo(() => {
    return userInfo?.full_name
      ? userInfo?.full_name
      : `${userInfo?.first_name} ${
          userInfo?.middle_name ? userInfo?.middle_name : ''
        } ${userInfo?.last_name}`;
  }, [userInfo]);

  return (
    <Modal
      animationType="slide"
      transparent={true}
      visible={true}
      onRequestClose={() => {
        onClose(null);
      }}>
      <ScrollView>
        <View style={styles.modalView}>
          <AppText style={styles.modalTitle}>Xác nhận ngày công</AppText>
          <UserHeader userInfo={userInfo} fullName={fullName} />
          <View>
            <AppText style={styles.modalTitle}>Thông tin chung</AppText>
            <View style={styles.rowView}>
              <AppText>Từ ngày</AppText>
              <View>
                <TouchableOpacity
                  disabled={!isRequest}
                  onPress={() =>
                    setOpenTimePicker(state => ({
                      ...state,
                      startDate: true,
                    }))
                  }
                  style={modalRequestConfirmWorkdaysStyles.chooseTimeSection}>
                  <AppText>
                    {moment(confirmDateRequestTicket?.startDate).format(
                      'DD/MM/YYYY',
                    )}
                  </AppText>
                  <Image
                    source={IMAGES.IcCalendarGray}
                    style={{width: 20, height: 20, marginLeft: 8}}
                  />
                </TouchableOpacity>
                <DateTimePicker
                  isVisible={openTimePicker.startDate}
                  mode="date"
                  date={confirmDateRequestTicket?.startDate}
                  onConfirm={time => {
                    setConfirmDateRequestTicket(prev => ({
                      ...prev,
                      startDate: time,
                    }));
                    setOpenTimePicker(state => ({
                      ...state,
                      startDate: false,
                    }));
                  }}
                  onCancel={() => {
                    setOpenTimePicker(state => ({
                      ...state,
                      startDate: false,
                    }));
                  }}
                />
              </View>
            </View>
            <View style={styles.rowView}>
              <AppText>Giờ</AppText>
              <View>
                <TouchableOpacity
                  disabled={!isRequest}
                  onPress={() =>
                    setOpenTimePicker(state => ({
                      ...state,
                      startTime: true,
                    }))
                  }
                  style={modalRequestConfirmWorkdaysStyles.chooseTimeSection}>
                  <AppText>
                    {moment(confirmDateRequestTicket?.startDate).format(
                      'HH:mm',
                    )}
                  </AppText>
                  <Image
                    source={IMAGES.IcLeaveNoti}
                    style={{width: 20, height: 20}}
                  />
                </TouchableOpacity>
                <DateTimePicker
                  isVisible={openTimePicker.startTime}
                  mode="time"
                  date={confirmDateRequestTicket?.startDate}
                  onConfirm={time => {
                    setConfirmDateRequestTicket(prev => ({
                      ...prev,
                      startDate: time,
                    }));
                    setOpenTimePicker(state => ({
                      ...state,
                      startTime: false,
                    }));
                  }}
                  onCancel={() => {
                    setOpenTimePicker(state => ({
                      ...state,
                      startTime: false,
                    }));
                  }}
                />
              </View>
            </View>
            <View style={styles.rowView}>
              <AppText>Đến ngày</AppText>
              <View>
                <TouchableOpacity
                  disabled={!isRequest}
                  onPress={() =>
                    setOpenTimePicker(state => ({
                      ...state,
                      finishDate: true,
                    }))
                  }
                  style={modalRequestConfirmWorkdaysStyles.chooseTimeSection}>
                  <AppText>
                    {moment(confirmDateRequestTicket?.finishDate).format(
                      'DD/MM/YYYY',
                    )}
                  </AppText>
                  <Image
                    source={IMAGES.IcCalendarGray}
                    style={{width: 20, height: 20, marginLeft: 8}}
                  />
                </TouchableOpacity>
                <DateTimePicker
                  isVisible={openTimePicker.finishDate}
                  mode="date"
                  date={confirmDateRequestTicket?.finishDate}
                  onConfirm={time => {
                    setConfirmDateRequestTicket(prev => ({
                      ...prev,
                      finishDate: time,
                    }));
                    setOpenTimePicker(state => ({
                      ...state,
                      finishDate: false,
                    }));
                  }}
                  onCancel={() => {
                    setOpenTimePicker(state => ({
                      ...state,
                      finishDate: false,
                    }));
                  }}
                />
              </View>
            </View>
            <View style={styles.rowView}>
              <AppText>Giờ</AppText>
              <View>
                <TouchableOpacity
                  disabled={!isRequest}
                  onPress={() =>
                    setOpenTimePicker(state => ({
                      ...state,
                      finishTime: true,
                    }))
                  }
                  style={modalRequestConfirmWorkdaysStyles.chooseTimeSection}>
                  <AppText>
                    {moment(confirmDateRequestTicket?.finishDate).format(
                      'HH:mm',
                    )}
                  </AppText>
                  <Image
                    source={IMAGES.IcLeaveNoti}
                    style={{width: 20, height: 20}}
                  />
                </TouchableOpacity>
                <DateTimePicker
                  isVisible={openTimePicker.finishTime}
                  mode="time"
                  date={confirmDateRequestTicket?.finishDate}
                  onConfirm={time => {
                    setConfirmDateRequestTicket(prev => ({
                      ...prev,
                      finishDate: time,
                    }));
                    setOpenTimePicker(state => ({
                      ...state,
                      finishTime: false,
                    }));
                  }}
                  onCancel={() => {
                    setOpenTimePicker(state => ({
                      ...state,
                      finishTime: false,
                    }));
                  }}
                />
              </View>
            </View>
            {/* <View style={styles.rowView}>
              <AppText>{`Thời gian nghỉ (*)`}</AppText>
              <View style={styles.takeTimeStyle}>
                <AppText style={{paddingLeft: 18}}>
                    {durationLeave.stringTime}
                  </AppText>
              </View>
            </View> */}
            <View style={styles.rowView}>
              <AppText
                style={{
                  color:
                    confirmDateRequestTicket?.reason?.length === 0
                      ? 'red'
                      : 'grey',
                }}>{`Lý do(*)`}</AppText>
              <View>
                <TextInputComponent
                  disable={isRequest}
                  styleAreaInput={styles.inputText}
                  value={confirmDateRequestTicket.reason}
                  placeholder="Nhập lý do tại đây"
                  onChangeText={text => {
                    setConfirmDateRequestTicket(state => ({
                      ...state,
                      reason: text,
                    }));
                  }}
                  noBorder
                />
              </View>
            </View>
            <Attachments
              confirmDateRequestImage={confirmDateRequestImage}
              onDeleteConfirmDateRequestImage={onDeleteConfirmDateRequestImage}
              openGallery={openGallery}
            />
            {isRequest && directManagersList.length > 0 && (
              <DirectManagers
                directManagersList={directManagersList}
                onSelectManagerConfirmWorkingDayRequest={
                  onSelectManagerConfirmWorkingDayRequest
                }
              />
            )}
          </View>
          <ButtonAction
            onClose={onClose}
            isRequest={isRequest}
            userInfo={userInfo}
            onSubmitConfirmWorkingDayRequest={onSubmitConfirmWorkingDayRequest}
            onSubmitApproveConfirmWorkingDaysRequest={
              onSubmitApproveConfirmWorkingDaysRequest
            }
          />
        </View>
      </ScrollView>
    </Modal>
  );
};

export default ModalRequestConfirmWorkingDays;
