/* eslint-disable react-native/no-inline-styles */
import CheckBox from '@react-native-community/checkbox';
import Moment from 'moment';
import React, {useMemo} from 'react';
import {Image, Modal, ScrollView, TouchableOpacity, View} from 'react-native';
import DateTimePickerModal from 'react-native-modal-datetime-picker';
import AppText from '../../../../components/AppText';
import ButtonComponent from '../../../../components/ButtonComponent';
import SelectDropdownComponent from '../../../../components/Select';
import TextInputComponent from '../../../../components/TextInputComponent';
import config from '../../../../config';
import {IMAGES} from '../../../../values/images';
import {leavesModalStyles} from '../../style';

// const ButtonAction = React.memo(
//   ({
//     onCloseModal,
//     onSubmitApproveLeaveRequest,
//     isRequest,
//     onSubmitLeaveRequest,
//     userInfo,
//   }) => {
//     return (
//       <View
//         style={{
//           flexDirection: 'row',
//           justifyContent: 'flex-end',
//           marginTop: 20,
//         }}>
//         <TouchableOpacity
//           onPress={onCloseModal}
//           style={leavesModalStyles.btnCancel}>
//           <AppText style={leavesModalStyles.blueTxt}>Hủy</AppText>
//         </TouchableOpacity>
//         {isRequest && (
//           <TouchableOpacity
//             style={leavesModalStyles.btnSubmit}
//             onPress={onSubmitLeaveRequest}>
//             <AppText style={leavesModalStyles.whiteTxt}>Gửi yêu cầu</AppText>
//           </TouchableOpacity>
//         )}
//         {userInfo?.isApprover && (
//           <TouchableOpacity
//             style={leavesModalStyles.btnSubmit}
//             onPress={() => onSubmitApproveLeaveRequest(userInfo?.leave_id)}>
//             <AppText style={leavesModalStyles.whiteTxt}>Duyệt yêu cầu</AppText>
//           </TouchableOpacity>
//         )}
//       </View>
//     );
//   },
//   function areEquals(prevProps, nextProps) {
//     return (
//       prevProps.isRequest === nextProps.isRequest ||
//       prevProps.userInfo === nextProps.userInfo ||
//       prevProps.onSubmitLeaveRequest === nextProps.onSubmitLeaveRequest ||
//       prevProps.onCloseModal === nextProps.onCloseModal ||
//       prevProps.onSubmitApproveLeaveRequest ===
//         nextProps.onSubmitApproveLeaveRequest
//     );
//   },
// );

const UserHeader = React.memo(
  ({userInfo, fullName}) => {
    return (
      <View style={{flexDirection: 'row', marginVertical: 10}}>
        <Image
          source={
            userInfo?.avatar
              ? {
                  uri: config.imageEndPoint + userInfo?.avatar,
                }
              : IMAGES.IcAvatarDefault
          }
          style={leavesModalStyles.ImgAvatar}
        />
        <View style={{marginLeft: 15}}>
          <AppText
            style={
              leavesModalStyles.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(
  ({leaveRequestImage, onDeleteLeaveRequestImage, openGallery}) => {
    return (
      <View style={leavesModalStyles.rowView}>
        <AppText>Tệp đính kèm</AppText>
        <View style={{flexDirection: 'row'}}>
          {leaveRequestImage.length > 0 &&
            leaveRequestImage.map((item, index) => {
              //console.log("item", item[0].uri)
              return (
                <View key={index}>
                  <ButtonComponent
                    iconSource={IMAGES.IcReject}
                    style={leavesModalStyles.btnClose}
                    onPress={() => onDeleteLeaveRequestImage(index)}
                  />
                  <Image
                    source={{uri: item.uri}}
                    style={leavesModalStyles.imgUpload}
                  />
                </View>
              );
            })}

          {leaveRequestImage.length < 3 && (
            <ButtonComponent
              style={leavesModalStyles.addLeaveRequestImageBtn}
              onPress={openGallery}
              iconSource={IMAGES.IcAddMoreImg}
            />
          )}
        </View>
      </View>
    );
  },
);

const ButtonAction = ({
  onCloseModal,
  onSubmitApproveLeaveRequest,
  isRequest,
  onSubmitLeaveRequest,
  userInfo,
}) => {
  return (
    <View
      style={{
        flexDirection: 'row',
        justifyContent: 'flex-end',
        marginTop: 20,
      }}>
      <TouchableOpacity
        onPress={onCloseModal}
        style={leavesModalStyles.btnCancel}>
        <AppText style={leavesModalStyles.blueTxt}>Hủy</AppText>
      </TouchableOpacity>
      {isRequest && (
        <TouchableOpacity
          style={leavesModalStyles.btnSubmit}
          onPress={onSubmitLeaveRequest}>
          <AppText style={leavesModalStyles.whiteTxt}>Gửi yêu cầu</AppText>
        </TouchableOpacity>
      )}
      {userInfo?.isApprover && (
        <TouchableOpacity
          style={leavesModalStyles.btnSubmit}
          onPress={() => onSubmitApproveLeaveRequest(userInfo?.leave_id)}>
          <AppText style={leavesModalStyles.whiteTxt}>Duyệt yêu cầu</AppText>
        </TouchableOpacity>
      )}
    </View>
  );
};
const RequestLeavesDays = props => {
  const {
    userInfo,
    onCloseModal,
    leaveCategory,
    directManagersList = [],
    openTimePicker,
    setOpenTimePicker,
    timeRequestLeave,
    setTimeRequestLeave,
    leaveRequestImage = [],
    openGallery,
    onDeleteLeaveRequestImage,
    leaveRequestTicket,
    setLeaveRequestTicket,
    onSubmitLeaveRequest,
    onSelectManagerLeaveRequest,
    isRequest = false,
    onSubmitApproveLeaveRequest,
  } = props;
  const formatLeaveCategory = useMemo(() => {
    leaveCategory.map(item => {
      return {label: item.name, value: item.name};
    });
    return leaveCategory.length > 0
      ? leaveCategory.map(item => {
          return {label: item.name, value: item.name};
        })
      : [];
  }, [leaveCategory]);

  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={() => onCloseModal(null)}>
      <ScrollView>
        <View style={leavesModalStyles.modalView}>
          <View style={{marginVertical: 10}}>
            <AppText style={leavesModalStyles.modalTitle}>
              Nghỉ phép mới
            </AppText>
          </View>
          <UserHeader userInfo={userInfo} fullName={fullName} />
          <View>
            <AppText style={leavesModalStyles.modalTitle}>
              Thông tin chung
            </AppText>
            <View style={leavesModalStyles.rowView}>
              <AppText>Loại nghỉ phép</AppText>
              <SelectDropdownComponent
                disable={!isRequest}
                selectData={formatLeaveCategory}
                setValue={value =>
                  setLeaveRequestTicket(prev => ({
                    ...prev,
                    leaveCategory: value,
                  }))
                }
                width={200}
                height={30}
              />
            </View>
            <View style={leavesModalStyles.rowView}>
              <AppText>Từ ngày</AppText>
              <View>
                <TouchableOpacity
                  disabled={!isRequest}
                  onPress={() =>
                    setOpenTimePicker(state => ({
                      ...state,
                      startDate: true,
                    }))
                  }
                  style={leavesModalStyles.chooseTimeSection}>
                  <AppText>
                    {Moment(timeRequestLeave.startDate).format('DD/MM/YYYY')}
                  </AppText>
                  <Image
                    source={IMAGES.IcCalendarGray}
                    style={{width: 20, height: 20, marginLeft: 8}}
                  />
                </TouchableOpacity>
                <DateTimePickerModal
                  isVisible={openTimePicker.startDate}
                  mode="date"
                  date={timeRequestLeave.startDate}
                  onConfirm={time => {
                    setTimeRequestLeave(prev => ({...prev, startDate: time}));
                    setOpenTimePicker(state => ({
                      ...state,
                      startDate: false,
                    }));
                  }}
                  onCancel={() => {
                    setOpenTimePicker(state => ({
                      ...state,
                      startDate: false,
                    }));
                  }}
                />
              </View>
            </View>
            <View style={leavesModalStyles.rowView}>
              <AppText>Giờ</AppText>
              <View>
                <TouchableOpacity
                  disabled={!isRequest}
                  onPress={() =>
                    setOpenTimePicker(state => ({
                      ...state,
                      startTime: true,
                    }))
                  }
                  style={leavesModalStyles.chooseTimeSection}>
                  <AppText>
                    {Moment(timeRequestLeave.startDate).format('HH:mm')}
                  </AppText>
                  <Image
                    source={IMAGES.IcLeaveNoti}
                    style={{width: 20, height: 20}}
                  />
                </TouchableOpacity>
                <DateTimePickerModal
                  isVisible={openTimePicker.startTime}
                  mode="time"
                  date={timeRequestLeave.startDate}
                  onConfirm={time => {
                    setTimeRequestLeave(prev => ({...prev, startDate: time}));
                    setOpenTimePicker(state => ({
                      ...state,
                      startTime: false,
                    }));
                  }}
                  onCancel={() => {
                    setOpenTimePicker(state => ({
                      ...state,
                      startTime: false,
                    }));
                  }}
                />
              </View>
            </View>
            <View style={leavesModalStyles.rowView}>
              <AppText>Đến ngày</AppText>
              <View>
                <TouchableOpacity
                  disabled={!isRequest}
                  onPress={() =>
                    setOpenTimePicker(state => ({
                      ...state,
                      finishDate: true,
                    }))
                  }
                  style={leavesModalStyles.chooseTimeSection}>
                  <AppText>
                    {Moment(timeRequestLeave.finishDate).format('DD/MM/YYYY')}
                  </AppText>
                  <Image
                    source={IMAGES.IcCalendarGray}
                    style={{width: 20, height: 20, marginLeft: 8}}
                  />
                </TouchableOpacity>
                <DateTimePickerModal
                  isVisible={openTimePicker.finishDate}
                  mode="date"
                  date={timeRequestLeave.finishDate}
                  onConfirm={time => {
                    setTimeRequestLeave(prev => ({...prev, finishDate: time}));
                    setOpenTimePicker(state => ({
                      ...state,
                      finishDate: false,
                    }));
                  }}
                  onCancel={() => {
                    setOpenTimePicker(state => ({
                      ...state,
                      finishDate: false,
                    }));
                  }}
                />
              </View>
            </View>
            <View style={leavesModalStyles.rowView}>
              <AppText>Giờ</AppText>
              <View>
                <TouchableOpacity
                  disabled={!isRequest}
                  onPress={() =>
                    setOpenTimePicker(state => ({
                      ...state,
                      finishTime: true,
                    }))
                  }
                  style={leavesModalStyles.chooseTimeSection}>
                  <AppText>
                    {Moment(timeRequestLeave.finishDate).format('HH:mm')}
                  </AppText>
                  <Image
                    source={IMAGES.IcLeaveNoti}
                    style={{width: 20, height: 20}}
                  />
                </TouchableOpacity>
                <DateTimePickerModal
                  isVisible={openTimePicker.finishTime}
                  mode="time"
                  date={timeRequestLeave.finishDate}
                  onConfirm={time => {
                    setTimeRequestLeave(prev => ({...prev, finishDate: time}));
                    setOpenTimePicker(state => ({
                      ...state,
                      finishTime: false,
                    }));
                  }}
                  onCancel={() => {
                    setOpenTimePicker(state => ({
                      ...state,
                      finishTime: false,
                    }));
                  }}
                />
              </View>
            </View>
            {/* <View style={leavesModalStyles.rowView}>
              <AppText>{`Thời gian nghỉ (*)`}</AppText>
              <View style={leavesModalStyles.takeTimeStyle}>
                <AppText style={{paddingLeft: 18}}>
                    {durationLeave.stringTime}
                  </AppText>
              </View>
            </View> */}
            <View style={leavesModalStyles.rowView}>
              <AppText
                style={{
                  color:
                    leaveRequestTicket.reason.length === 0 ? 'red' : 'grey',
                }}>{`Lý do(*)`}</AppText>
              <View>
                <TextInputComponent
                  disable={isRequest}
                  styleAreaInput={leavesModalStyles.inputText}
                  value={leaveRequestTicket.reason}
                  placeholder="Nhập lý do tại đây"
                  onChangeText={text => {
                    setLeaveRequestTicket(state => ({
                      ...state,
                      reason: text,
                    }));
                  }}
                  noBorder
                />
              </View>
            </View>
            <Attachments
              leaveRequestImage={leaveRequestImage}
              onDeleteLeaveRequestImage={onDeleteLeaveRequestImage}
              openGallery={openGallery}
            />
            {/* <View style={leavesModalStyles.rowView}>
              <AppText>Tệp đính kèm</AppText>
              <View style={{flexDirection: 'row'}}>
                {leaveRequestImage.length > 0 &&
                  leaveRequestImage.map((item, index) => {
                    //console.log("item", item[0].uri)
                    return (
                      <View key={index}>
                        <ButtonComponent
                          iconSource={IMAGES.IcReject}
                          style={leavesModalStyles.btnClose}
                          onPress={() => onDeleteLeaveRequestImage(index)}
                        />
                        <Image
                          source={{uri: item.uri}}
                          style={leavesModalStyles.imgUpload}
                        />
                      </View>
                    );
                  })}

                {leaveRequestImage.length < 3 && (
                  <ButtonComponent
                    style={leavesModalStyles.addLeaveRequestImageBtn}
                    onPress={openGallery}
                    iconSource={IMAGES.IcAddMoreImg}
                  />
                )}
              </View>
            </View> */}
            {isRequest && directManagersList.length > 0 && (
              <View style={{marginTop: 10}}>
                <AppText
                  style={[
                    leavesModalStyles.modalTitle,
                    {
                      marginBottom: 10,
                    },
                  ]}>
                  Người duyệt
                </AppText>
                {directManagersList.map((item, index) => (
                  <View
                    key={index}
                    style={{
                      flexDirection: 'row',
                      justifyContent: 'space-between',
                      alignItems: 'center',
                      marginTop: 4,
                    }}>
                    <View
                      style={{
                        flexDirection: 'row',
                        alignItems: 'center',
                        paddingLeft: 18,
                      }}>
                      <Image
                        source={{
                          uri: config.imageEndPoint + item.avatar,
                        }}
                        style={leavesModalStyles.avatarApprove}
                      />
                      <AppText
                        style={{
                          marginLeft: 10,
                        }}>{`${item.extend_user_full_name}`}</AppText>
                    </View>
                    <View style={{paddingRight: 10}}>
                      <CheckBox
                        disabled={false}
                        value={item.isChecked}
                        onValueChange={newValue =>
                          onSelectManagerLeaveRequest(index, newValue)
                        }
                        boxType={'square'}
                        animationDuration={0.3}
                        lineWidth={1}
                        key={index}
                        tintColors={'#9E663C'}
                      />
                    </View>
                  </View>
                ))}
              </View>
            )}
          </View>
          <ButtonAction
            onCloseModal={onCloseModal}
            isRequest={isRequest}
            userInfo={userInfo}
            onSubmitLeaveRequest={onSubmitLeaveRequest}
            onSubmitApproveLeaveRequest={onSubmitApproveLeaveRequest}
          />
        </View>
      </ScrollView>
    </Modal>
  );
};

export default RequestLeavesDays;
