/* eslint-disable prettier/prettier */
/* eslint-disable react-native/no-inline-styles */

import Moment from 'moment';
import React, {useState} from 'react';
import {
  Image,
  SafeAreaView,
  ScrollView,
  TouchableOpacity,
  View,
} from 'react-native';
import DateTimePickerModal from 'react-native-modal-datetime-picker';
import SelectDropdown from 'react-native-select-dropdown';
//import {ScrollView} from 'react-native-virtualized-view';
import Alert from 'react-native-awesome-alerts';
import ButtonComponent from '../../components/ButtonComponent';
import LoadingProgress from '../../components/LoadingProgress';
import TextInputComponent from '../../components/TextInputComponent';
import colors from '../../values/colors';
import {IconTimeSheet, IMAGES} from '../../values/images';
import ConfirmedShiftContainer from './shift-tabs/ConfirmedShiftScreen/ConfirmedShiftContainer';
import {contentStyle, mainStyle} from './style';
import AppText from '../../components/AppText';
const ShiftScreen = ({
  userDetails,
  prevWeek,
  nextWeek,
  managerDate,
  numberWeekOfYear,
  setTime,
  totalTime,
  dataDropDown,
  onChangeSelectDropDownProjectName,
  onChangeSelectDropDownJobName,
  managerTimePicker,
  managerDisabled,
  onJustSave,
  onPressSend,
  onPressRightIcon,
  onPressCloseDesInput,
  arrJob,
  addMoreJob,
  onChangeTextDes,
  onChangeTextNote,
  isLoading,
  error,
  onCollapseView,
  onExpandView,
  onDeleteItem,
  showAlert,
  onConfirmDelete,
  hideAlert,
  managerArr,
  onSelectManagement,
}) => {
  const [text, onChangeText] = useState();
  const [tabChange, setTabChange] = useState('MY-SHIFT');
  const onTabChange = tab => {
    setTabChange(tab);
  };
  const renderItem = (item, index, index_arr) => {
    return (
      <View
        key={`${item.title} ${index}`}
        style={{flex: 1, flexDirection: 'row'}}>
        {index !== 7 ? (
          <TouchableOpacity
            key={`${item.title} ${index}`}
            onPress={() => {
              !managerDisabled.datePicker
                ? managerTimePicker('open', item, index, index_arr)
                : null;
            }}
            style={{
              flex: 1,
              flexDirection: 'row',
              margin: 5,
              borderWidth: 0.5,
              height: 30,
            }}>
            <View style={contentStyle.viewItemDay}>
              <AppText>{item.title ? item.title : ''}</AppText>
            </View>
            <View
              style={{
                flex: 4,
                justifyContent: 'center',
                alignItems: 'center',
              }}>
              <AppText>
                {item.time && item.time.toString().includes(':')
                  ? item.time
                  : item.time !== 0 && item.time !== ''
                  ? Moment(item.time).format('HH:mm')
                  : '00:00'}
              </AppText>
              <DateTimePickerModal
                isVisible={item.isOpen}
                mode="time"
                date={new Date()}
                onConfirm={time => setTime(item, index, index_arr, time)}
                onCancel={() =>
                  managerTimePicker('close', item, index, index_arr)
                }
              />
            </View>
          </TouchableOpacity>
        ) : (
          <View
            style={{
              flex: 1,
              justifyContent: 'center',
              alignItems: 'center',
              margin: 5,
              borderWidth: 0.5,
              height: 30,
            }}>
            <AppText style={{color: '#ffa117', fontWeight: '500'}}>{`${
              item.title
            } ${totalTime || 0}`}</AppText>
          </View>
        )}
      </View>
    );
  };

  return (
    <SafeAreaView>
      <ScrollView
        nestedScrollEnabled={true}
        overScrollMode={'auto'}
        style={{padding: 10}}>
        <View
          style={[
            mainStyle.row,
            mainStyle.marginSpaceAround,
            {marginBottom: 10},
          ]}>
          <TouchableOpacity
            onPress={() => onTabChange('MY-SHIFT')}
            style={{
              borderBottomWidth: tabChange === 'MY-SHIFT' ? 1 : 0,
              borderBottomColor: '#5d78ff',
            }}>
            <AppText
              style={{
                color: tabChange === 'MY-SHIFT' ? '#5d78ff' : '#959595',
                fontWeight: '500',
              }}>
              Timesheet của tôi
            </AppText>
          </TouchableOpacity>
          <TouchableOpacity
            style={{
              borderBottomWidth: tabChange !== 'MY-SHIFT' ? 1 : 0,
              borderBottomColor: '#5d78ff',
            }}
            onPress={() => onTabChange('CONFIRMED-SHIFT')}>
            <AppText
              style={{
                color: tabChange !== 'MY-SHIFT' ? '#5d78ff' : '#959595',
                fontWeight: '500',
              }}>
              Timesheet cần duyệt
            </AppText>
          </TouchableOpacity>
        </View>
        {tabChange === 'MY-SHIFT' ? (
          <>
            <View style={mainStyle.row}>
              <Image
                source={{uri: 'https://meu.anawork.com' + userDetails.avatar}}
                style={{width: 70, height: 70}}
              />
              <View style={{marginLeft: 15, justifyContent: 'center'}}>
                <AppText style={{color: '#434349', fontWeight: '500'}}>{`${
                  userDetails.first_name
                } ${userDetails.middle_name ? userDetails.middle_name : ''} ${
                  userDetails.last_name
                } (${userDetails.employee_code})`}</AppText>
                <AppText style={{fontSize: 13}}>
                  {userDetails.department}
                </AppText>
              </View>
            </View>
            <View
              style={[
                mainStyle.row,
                {justifyContent: 'space-between', alignItems: 'center'},
              ]}>
              <View style={{flexDirection: 'row'}}>
                <AppText style={{color: '#5c65dc'}}>Tổng giờ tuần này:</AppText>
                <AppText style={{color: '#ffa117'}}> {totalTime} giờ</AppText>
              </View>
              <ButtonComponent
                iconSource={IconTimeSheet.IcCopyBlue}
                styleIcon={{height: 20, width: 20}}
                style={{
                  backgroundColor: '#e9eaf9',
                  padding: 5,
                }}
              />
            </View>
            <View style={[mainStyle.row, {justifyContent: 'space-between'}]}>
              <ButtonComponent
                style={{
                  backgroundColor: '#e9eaf9',
                  padding: 5,
                }}
                iconSource={IconTimeSheet.IcLeftForward}
                styleIcon={{height: 20, width: 20}}
                onPress={prevWeek}
              />
              <View
                style={{
                  flexDirection: 'row',
                  backgroundColor: '#e9eaf9',
                  justifyContent: 'center',
                  alignItems: 'center',
                  paddingLeft: 10,
                  paddingRight: 10,
                }}>
                <AppText style={{color: '#615f71', fontWeight: '500'}}>
                  {`Tuần ${numberWeekOfYear} `}{' '}
                </AppText>
                <AppText>{`${Moment(managerDate.currentDate).format(
                  'DD/MM/YYYY',
                )} - ${Moment(managerDate.theWeekend).format(
                  'DD/MM/YYYY',
                )}`}</AppText>
                <Image
                  source={IMAGES.IcCalendarGray}
                  style={{height: 20, width: 20, marginLeft: 10}}
                />
              </View>
              <ButtonComponent
                style={{
                  backgroundColor: '#e9eaf9',
                  padding: 5,
                }}
                iconSource={IconTimeSheet.IcRightForward}
                styleIcon={{height: 20, width: 20}}
                onPress={nextWeek}
              />
            </View>
            <ButtonComponent
              style={[mainStyle.row, contentStyle.btnAddJob]}
              leftIcon={IMAGES.IcAdd}
              styleIcon={{height: 15, width: 15, marginRight: 5}}
              text={'THÊM CÔNG VIỆC'}
              textStyle={{color: 'white'}}
              onPress={addMoreJob}
            />
            {arrJob &&
              arrJob.map((item, index_arr) => {
                // console.log("item", index_arr % 2 === 0 ? '#0abb87' : '#959595')
                return (
                  // expand view
                  (item?.isExpand && (
                    <View key={`_key${index_arr.toString()}`}>
                      <View
                        style={{
                          marginTop: 20,
                          backgroundColor: colors.white,
                          padding: 10,
                        }}>
                        <ButtonComponent
                          iconSource={IconTimeSheet.IcCollapse}
                          styleIcon={{width: 30, height: 30}}
                          onPress={() => onCollapseView(index_arr)}
                          style={{alignItems: 'flex-end'}}
                        />

                        {dataDropDown.projectName && (
                          <SelectDropdown
                            disabled={managerDisabled.dropdown}
                            data={dataDropDown.projectName}
                            dropdownIconPosition={'right'}
                            defaultButtonText={item.projectName || 'Dự án'}
                            buttonStyle={mainStyle.dropdown1BtnStyle}
                            onSelect={(selectedItem, index_item) => {
                              //console.log("dataDropDown", dataDropDown.projectId[index])
                              onChangeSelectDropDownProjectName(
                                selectedItem,
                                dataDropDown.projectId[index_item],
                                index_arr,
                              );
                            }}
                            placeholder
                            dropdownStyle={mainStyle.dropdown1DropdownStyle}
                            rowStyle={mainStyle.dropdown1RowStyle}
                            rowTextStyle={mainStyle.dropdown1RowTxtStyle}
                            buttonTextStyle={mainStyle.dropdown1BtnTxtStyle}
                            renderDropdownIcon={isOpened => {
                              return (
                                <Image
                                  source={
                                    isOpened
                                      ? IMAGES.IcUpArrow
                                      : IMAGES.IcDownArrow
                                  }
                                  style={{
                                    width: 20,
                                    height: 20,
                                    marginRight: 10,
                                  }}
                                />
                              );
                            }}
                          />
                        )}

                        <SelectDropdown
                          disabled={managerDisabled.dropdown}
                          data={dataDropDown.jobName || ''}
                          dropdownIconPosition={'right'}
                          defaultButtonText={item.jobName || 'Tên công việc'}
                          buttonStyle={mainStyle.dropdown1BtnStyle}
                          onSelect={(selectedItem, item_index) => {
                            //console.log(idLeavesCategory[index].id)

                            onChangeSelectDropDownJobName(
                              selectedItem,
                              dataDropDown.jobId[item_index],
                              index_arr,
                            );
                          }}
                          placeholder
                          dropdownStyle={mainStyle.dropdown1DropdownStyle}
                          rowStyle={mainStyle.dropdown1RowStyle}
                          rowTextStyle={mainStyle.dropdown1RowTxtStyle}
                          buttonTextStyle={mainStyle.dropdown1BtnTxtStyle}
                          renderDropdownIcon={isOpened => {
                            return (
                              <Image
                                source={
                                  isOpened
                                    ? IMAGES.IcUpArrow
                                    : IMAGES.IcDownArrow
                                }
                                style={{width: 20, height: 20, marginRight: 10}}
                              />
                            );
                          }}
                        />
                        <TextInputComponent
                          value={item.taskName}
                          noBorder={true}
                          styleAreaInput={{backgroundColor: colors.white}}
                          placeholder={'Chi tiết công việc'}
                          keyboardType={'email-address'}
                          rightIcon={IconTimeSheet.IcDocument}
                          onPressRightIcon={() => onPressRightIcon(index_arr)}
                          onChangeText={text =>
                            onChangeTextDes(text, index_arr)
                          }
                          disable={managerDisabled.desInput}
                        />
                        {error && (
                          <AppText style={{color: 'red', fontSize: 12}}>
                            Vui lòng nhập chi tiết công việc
                          </AppText>
                        )}
                        {item.isDes && (
                          <TextInputComponent
                            value={item.description}
                            noBorder={true}
                            styleAreaInput={{backgroundColor: colors.white}}
                            placeholder={'Ghi chú công việc'}
                            keyboardType={'email-address'}
                            rightIcon={IconTimeSheet.IcClose}
                            onChangeText={text =>
                              onChangeTextNote(text, index_arr)
                            }
                            onPressRightIcon={() =>
                              onPressCloseDesInput(index_arr)
                            }
                            disable={managerDisabled.desInput}
                          />
                        )}
                        <View>
                          {/* <FlatList
                            data={item.calendar}
                            renderItem={({item, index}) =>
                              renderItem(item, index, index_arr)
                            }
                            listKey={(item, index) => `_key${index.toString()}`}
                            keyExtractor={(item, index) =>
                              `_key${index.toString()}`
                            }
                            numColumns={2}
                            ListHeaderComponent={() => {
                              <AppText>AAA</AppText>;
                            }}
                          /> */}
                          {item.calendar &&
                            item.calendar.map((el, index) => {
                              return (
                                <View
                                  key={`${el.title} ${index}`}
                                  style={{flex: 1, flexDirection: 'row'}}>
                                  {index !== 7 ? (
                                    <TouchableOpacity
                                      key={`${el.title} ${index}`}
                                      onPress={() => {
                                        !managerDisabled.datePicker
                                          ? managerTimePicker(
                                              'open',
                                              el,
                                              index,
                                              index_arr,
                                            )
                                          : null;
                                      }}
                                      style={{
                                        flex: 1,
                                        flexDirection: 'row',
                                        margin: 5,
                                        borderWidth: 0.5,
                                        height: 30,
                                      }}>
                                      <View style={contentStyle.viewItemDay}>
                                        <AppText>
                                          {el.title ? el.title : ''}
                                        </AppText>
                                      </View>
                                      <View
                                        style={{
                                          flex: 4,
                                          justifyContent: 'center',
                                          alignItems: 'center',
                                        }}>
                                        <AppText>
                                          {el.time &&
                                          el.time.toString().includes(':')
                                            ? el.time
                                            : el.time !== 0 && el.time !== ''
                                            ? Moment(el.time).format('HH:mm')
                                            : '00:00'}
                                        </AppText>
                                        <DateTimePickerModal
                                          isVisible={el.isOpen}
                                          mode="time"
                                          date={new Date()}
                                          onConfirm={time =>
                                            setTime(el, index, index_arr, time)
                                          }
                                          onCancel={() =>
                                            managerTimePicker(
                                              'close',
                                              el,
                                              index,
                                              index_arr,
                                            )
                                          }
                                        />
                                      </View>
                                    </TouchableOpacity>
                                  ) : (
                                    <View
                                      style={{
                                        flex: 1,
                                        justifyContent: 'center',
                                        alignItems: 'center',
                                        margin: 5,
                                        borderWidth: 0.5,
                                        height: 30,
                                      }}>
                                      <AppText
                                        style={{
                                          color: '#ffa117',
                                          fontWeight: '500',
                                        }}>{`${el.title} ${
                                        totalTime || 0
                                      }`}</AppText>
                                    </View>
                                  )}
                                </View>
                              );
                            })}
                        </View>
                        {arrJob.length > 0 && !arrJob[0]?.isSubmit && (
                          <ButtonComponent
                            style={[mainStyle.deleteBtn]}
                            text={'Xóa'}
                            textStyle={[
                              mainStyle.saveAndSendBtn,
                              {color: '#e5493a'},
                            ]}
                            onPress={() => onDeleteItem(item)}
                          />
                        )}
                      </View>
                    </View>
                  )) || (
                    // collapse view
                    <TouchableOpacity
                      onPress={() => onExpandView(index_arr)}
                      key={`_key${index_arr.toString()}`}
                      style={[
                        mainStyle.collapseView,
                        {
                          borderLeftColor:
                            index_arr % 2 === 0 ? '#0abb87' : '#959595',
                        },
                      ]}>
                      {/* {arrJob.length > 0 && !arrJob[0]?.isSubmit && (
                        <ButtonComponent
                          onPress={() => onDeleteItem(item)}
                          style={{alignSelf: 'flex-end'}}
                          iconSource={IconProfile.IcCloseBlack}
                          styleIcon={{width: 20, height: 20}}
                        />
                      )} */}
                      <View style={{flexDirection: 'row'}}>
                        <View style={{justifyContent: 'flex-start', flex: 6}}>
                          <AppText
                            style={{
                              fontSize: 14,
                              color: 'black',
                              fontWeight: 'bold',
                            }}>
                            {item.projectName}
                          </AppText>
                          <AppText>{item.taskName}</AppText>
                        </View>
                        <TouchableOpacity
                          onPress={() => onExpandView(index_arr)}
                          style={{flex: 1, justifyContent: 'center'}}>
                          <Image
                            source={IMAGES.IcArrowRight}
                            style={{height: 20, width: 20}}
                          />
                        </TouchableOpacity>
                      </View>
                    </TouchableOpacity>
                  )
                );
              })}
            {arrJob.length > 0 && arrJob[0].isSubmit ? (
              <View style={mainStyle.viewBtn}>
                <ButtonComponent
                  style={[
                    mainStyle.viewSaveAndSendBtn,
                    {
                      backgroundColor: colors.grayE9,
                      marginRight: 10,
                    },
                  ]}
                  text={'Timesheet đã nộp'}
                  textStyle={[mainStyle.saveAndSendBtn, {color: colors.blue5c}]}
                />
              </View>
            ) : (
              <View>
                {managerArr && managerArr?.nameManager?.length > 0 && (
                  <SelectDropdown
                    data={managerArr?.nameManager}
                    dropdownIconPosition={'right'}
                    defaultButtonText={'Cấp trên duyệt'}
                    buttonStyle={mainStyle.dropdown1BtnSelectManager}
                    onSelect={selectedItem => onSelectManagement(selectedItem)}
                    dropdownStyle={mainStyle.dropdown1DropdownStyle}
                    rowStyle={mainStyle.dropdown1RowStyle}
                    rowTextStyle={mainStyle.dropdown1RowTxtStyle}
                    buttonTextStyle={mainStyle.dropdown1BtnTxtStyle}
                    renderDropdownIcon={isOpened => {
                      return (
                        <Image
                          source={
                            isOpened ? IMAGES.IcUpArrow : IMAGES.IcArrowDown
                          }
                          style={{width: 20, height: 20}}
                        />
                      );
                    }}
                  />
                )}
                <View style={mainStyle.viewBtn}>
                  <ButtonComponent
                    style={[
                      mainStyle.viewSaveAndSendBtn,
                      {
                        backgroundColor: colors.white,
                        marginRight: 10,
                        borderColor: colors.green0a,
                        borderWidth: 1.5,
                      },
                    ]}
                    text={'Lưu và nộp'}
                    textStyle={[
                      mainStyle.saveAndSendBtn,
                      {color: colors.green0a},
                    ]}
                    onPress={onPressSend}
                  />
                  <ButtonComponent
                    style={[
                      mainStyle.viewSaveAndSendBtn,
                      {
                        backgroundColor: colors.grayE9,
                      },
                    ]}
                    text={'Lưu'}
                    textStyle={[
                      mainStyle.saveAndSendBtn,
                      {color: colors.blue5c},
                    ]}
                    onPress={onJustSave}
                  />
                </View>
              </View>
            )}
          </>
        ) : (
          <ConfirmedShiftContainer />
        )}
        <Alert
          show={showAlert.isError}
          showProgress={false}
          title={showAlert.title}
          message={showAlert.message}
          closeOnTouchOutside={true}
          closeOnHardwareBackPress={false}
          showConfirmButton={showAlert.isShowActionBtn}
          showCancelButton={true}
          cancelText={'Đóng'}
          confirmText="Xóa"
          confirmButtonColor="#DD6B55"
          onConfirmPressed={onConfirmDelete}
          onCancelPressed={hideAlert}
        />
      </ScrollView>
      {isLoading && <LoadingProgress />}
    </SafeAreaView>
  );
};

export default ShiftScreen;
