/* eslint-disable prettier/prettier */
import moment from 'moment';
import React, { useEffect, useRef, useState } from 'react';
import {
  Image,
  SafeAreaView,
  TextInput,
  TouchableOpacity,
  View,
} from 'react-native';
import SelectDropdown from 'react-native-select-dropdown';
import AppText from '../../../../components/AppText';
import ButtonComponent from '../../../../components/ButtonComponent';
import { IconTimeSheet, IMAGES } from '../../../../values/images';
import ConfirmedShiftDetailContainer from './ConfirmedShiftDetail/ConfirmedShiftDetailContainer';
import { mainStyle } from './style';
const statusDropdownData = [
  'Tất cả trạng thái',
  'Chờ duyệt',
  'Duyệt',
  'Từ chối',
  'Nháp',
  'Chưa nhập Timesheet',
];

const ConfirmedShiftScreen = ({
  numberWeekOfYear,
  myApprovalRequestList,
  managerDate,
  currentPage,
  totalPage,
  setSearchValue,
  prevWeek,
  nextWeek,
  onPageNext,
  onPagePrevious,
}) => {
  const typingTimeoutRef = useRef(null);
  const [isDesOpen, setOpenDes] = useState(false);

  //Table list
  const [myApprovalRequestFinalList, setMyApprovalRequestFinalList] = useState(
    [],
  );
  const [userId, setUserId] = useState();
  const handleSearchDebounce = text => {
    const value = text;

    if (typingTimeoutRef.current) {
      clearTimeout(typingTimeoutRef.current);
    }

    typingTimeoutRef.current = setTimeout(() => {
      setSearchValue(value);
    }, 300);
  };

  const handleList = () => {
    if (myApprovalRequestList.length > 0) {
      const clone = [...myApprovalRequestList];
      for (let i = 0; i < clone.length; i++) {
        clone[i].isExpand = false;

        if (clone[i].week == null) {
          clone[i].user.extend_total_hour = 0;
          clone[i].user.status = 'Chưa nhập Timesheet';
          clone[i].user.extend_status_color = null;
        } else {
          clone[i].user.extend_total_hour =
            myApprovalRequestList[i].week.extend_total_hour;
          clone[i].user.status =
            myApprovalRequestList[i].week.extend_status_name;
          clone[i].user.extend_status_color =
            myApprovalRequestList[i].week.extend_status_color;
        }
      }
      setMyApprovalRequestFinalList(clone);
    }
  };

  const onExpandRow = id => {
    const clone = [...myApprovalRequestFinalList];
    let index = clone.findIndex(el => el?.user?.id === id);
    let element = clone.find(el => el?.user?.id === id);
    clone.splice(index, 1, {
      ...element,
      isExpand: true,
    });
    setMyApprovalRequestFinalList(clone);
  };

  const onCloseExpandRow = id => {
    const clone = [...myApprovalRequestFinalList];
    let index = clone.findIndex(el => el?.user?.id === id);
    let element = clone.find(el => el?.user?.id === id);
    clone.splice(index, 1, {
      ...element,
      isExpand: false,
    });
    setMyApprovalRequestFinalList(clone);
  };

  const onStatusChange = item => {
    if (item === 'Tất cả trạng thái') {
      handleList();
    } else {
      const clone = [...myApprovalRequestList];
      const newClone = clone.filter(el => el?.user.status === item);
      //console.log(newClone);
      setMyApprovalRequestFinalList(newClone);
    }
  };

  useEffect(() => {
    handleList();
  }, [myApprovalRequestList]);

  return (
    <SafeAreaView>
      <View style={mainStyle.bodyContainer}>
        {isDesOpen ? (
          <ConfirmedShiftDetailContainer
            userId={userId}
            numberOfWeek={numberWeekOfYear}
            year={moment(managerDate?.currentDate).year()}
            prevWeek={prevWeek}
            nextWeek={nextWeek}
            monday={managerDate?.currentDate}
            sunday={managerDate?.theWeekend}
          />
        ) : (
          <View>
            {/* Search  */}
            <View>
              <Image source={IMAGES.IcSearchPNG} style={mainStyle.searchIcon} />
              <TextInput
                style={mainStyle.searchInput}
                placeholder="Nhập tìm kiếm"
                onChangeText={text => handleSearchDebounce(text)}
              />
            </View>
            {/* Week  */}
            <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>
            {/* Table header */}
            <View>
              <View style={{...mainStyle.rowSpaceBetween, marginTop: 16}}>
                <AppText style={mainStyle.textTitle}>
                  Danh sách nhân viên
                </AppText>
                <SelectDropdown
                  data={statusDropdownData}
                  buttonStyle={mainStyle.statusButtonDropdown}
                  buttonTextStyle={mainStyle.statusButtonTextDropdown}
                  defaultValue={statusDropdownData[0]}
                  onSelect={selectedItem => onStatusChange(selectedItem)}
                />
              </View>
              <View style={mainStyle.tableContainer}>
                <View style={mainStyle.tableHeader}>
                  <View
                    style={{
                      ...mainStyle.tableHeaderContainer,
                      width: '20%',
                      paddingLeft: 12,
                    }}>
                    <AppText style={mainStyle.tableHeaderTitle}>#</AppText>
                  </View>
                  <View
                    style={{...mainStyle.tableHeaderContainer, width: '35%'}}>
                    <AppText style={mainStyle.tableHeaderTitle}>
                      Nhân viên
                    </AppText>
                  </View>
                  <View
                    style={{...mainStyle.tableHeaderContainer, width: '35%'}}>
                    <AppText style={mainStyle.tableHeaderTitle}>
                      Trạng thái timesheet
                    </AppText>
                  </View>
                  <View
                    style={{
                      ...mainStyle.tableHeaderContainer,
                      width: '10%',
                    }}></View>
                </View>
                <View style={mainStyle.tableBody}>
                  {/* Row */}
                  {myApprovalRequestFinalList.length > 0 ? (
                    myApprovalRequestFinalList.map((el, index) => (
                      <View key={index}>
                        <View style={mainStyle.tableRowContent}>
                          <View style={{width: '20%', paddingLeft: 12}}>
                            <AppText
                              style={{fontWeight: 'bold', color: '#313131'}}>
                              {index + 1}
                            </AppText>
                          </View>
                          <View style={{width: '35%'}}>
                            <AppText
                              style={{fontWeight: 'bold', color: '#313131'}}>
                              {el?.user?.extend_user_full_name || '--'}
                            </AppText>
                          </View>
                          <View
                            style={{
                              width: '35%',
                              flexDirection: 'row',
                              alignItems: 'center',
                            }}>
                            <View
                              style={{
                                ...mainStyle.dotStatus,
                                backgroundColor: el?.user?.extend_status_color
                                  ? '#34bfa3'
                                  : '#757575',
                                marginRight: 8,
                              }}></View>
                            <AppText
                              style={{fontWeight: 'bold', color: '#313131'}}>
                              {el?.user?.status}
                            </AppText>
                          </View>
                          <View style={{width: '10%'}}>
                            {el?.isExpand ? (
                              <TouchableOpacity
                                onPress={() => onCloseExpandRow(el?.user?.id)}>
                                <Image
                                  source={IMAGES.IcArrowDown}
                                  style={{width: 25, height: 25}}
                                />
                              </TouchableOpacity>
                            ) : (
                              <TouchableOpacity
                                onPress={() => onExpandRow(el?.user?.id)}>
                                <Image
                                  source={IMAGES.IcArrowRight}
                                  style={{width: 25, height: 25}}
                                />
                              </TouchableOpacity>
                            )}
                          </View>
                        </View>
                        {el?.isExpand && (
                          <View>
                            <View style={mainStyle.tableRowContent}>
                              <View
                                style={{width: '20%', paddingLeft: 12}}></View>
                              <View style={{width: '35%'}}>
                                <AppText>Mã nhân viên</AppText>
                              </View>
                              <View style={{width: '35%'}}>
                                <AppText
                                  style={{
                                    fontWeight: 'bold',
                                    color: '#313131',
                                  }}>
                                  {el?.user?.employee_code || '--'}
                                </AppText>
                              </View>
                              <View style={{width: '10%'}}></View>
                            </View>
                            <View style={mainStyle.tableRowContent}>
                              <View
                                style={{width: '20%', paddingLeft: 12}}></View>
                              <View style={{width: '35%'}}>
                                <AppText>Phòng ban</AppText>
                              </View>
                              <View style={{width: '35%'}}>
                                <AppText
                                  style={{
                                    fontWeight: 'bold',
                                    color: '#313131',
                                  }}>
                                  {el?.user?.department || '--'}
                                </AppText>
                              </View>
                              <View style={{width: '10%'}}></View>
                            </View>
                            <View style={mainStyle.tableRowContent}>
                              <View
                                style={{width: '20%', paddingLeft: 12}}></View>
                              <View style={{width: '35%'}}>
                                <AppText>Chức vụ</AppText>
                              </View>
                              <View style={{width: '35%'}}>
                                <AppText
                                  style={{
                                    fontWeight: 'bold',
                                    color: '#313131',
                                  }}>
                                  {el?.user?.position || '--'}
                                </AppText>
                              </View>
                              <View style={{width: '10%'}}></View>
                            </View>
                            <View style={mainStyle.tableRowContent}>
                              <View
                                style={{width: '20%', paddingLeft: 12}}></View>
                              <View style={{width: '35%'}}>
                                <AppText>Số giờ</AppText>
                              </View>
                              <View style={{width: '35%'}}>
                                <AppText
                                  style={{
                                    fontWeight: 'bold',
                                    color: '#313131',
                                  }}>
                                  {el?.user?.extend_total_hour}
                                </AppText>
                              </View>
                              <View style={{width: '10%'}}></View>
                            </View>
                            <View
                              style={{
                                flexDirection: 'row',
                                justifyContent: 'center',
                                marginBottom: 16,
                                marginTop: 8,
                              }}>
                              <ButtonComponent
                                style={mainStyle.tableButtonView}
                                textStyle={mainStyle.tableButtonTextView}
                                onPress={
                                  () => {
                                    setUserId(el?.user?.id);
                                    setOpenDes(true);
                                  }
                                  // RootNavigation.navigate(
                                  //   APP_NAVIGATE_SCREEN.CONFIRM_SHIFT_DETAIL,
                                  //   {
                                  //     sheetId: el?.user?.id,
                                  //     numberOfWeek: numberWeekOfYear,
                                  //     year: moment(managerDate?.currentDate).year(),
                                  //   },
                                  // )
                                }
                                text="Xem chi tiết"
                              />
                            </View>
                          </View>
                        )}
                      </View>
                    ))
                  ) : (
                    <View style={{marginTop: 8, marginBottom: 8}}>
                      <AppText style={{textAlign: 'center'}}>
                        Không có dữ liệu
                      </AppText>
                    </View>
                  )}
                </View>
              </View>
            </View>
            {myApprovalRequestFinalList.length > 0 && (
              <View style={mainStyle.paginationContainer}>
                <View style={mainStyle.pagination}>
                  <TouchableOpacity
                    onPress={() => onPagePrevious()}
                    disabled={currentPage === 1}>
                    <Image
                      source={IMAGES.IcArrowRight}
                      style={{
                        width: 25,
                        height: 25,
                        transform: [{rotate: '-180deg'}],
                      }}
                    />
                  </TouchableOpacity>
                  <AppText>{`Trang ${currentPage}/${totalPage}`}</AppText>
                  <TouchableOpacity
                    onPress={() => onPageNext()}
                    disabled={currentPage === totalPage}>
                    <Image
                      source={IMAGES.IcArrowRight}
                      style={{width: 25, height: 25}}
                    />
                  </TouchableOpacity>
                </View>
              </View>
            )}
          </View>
        )}
      </View>
    </SafeAreaView>
  );
};

export default ConfirmedShiftScreen;
