/* eslint-disable prettier/prettier */
/* eslint-disable react-hooks/exhaustive-deps */
/* eslint-disable prettier/prettier */
/* eslint-disable react-native/no-inline-styles */
/* eslint-disable prettier/prettier */
/* eslint-disable no-unused-vars */
import moment from 'moment';
import React, {useEffect, useRef, useState} from 'react';
import {
  Image,
  SafeAreaView,
  Text,
  TextInput,
  TouchableOpacity,
  View,
} from 'react-native';
import SelectDropdown from 'react-native-select-dropdown';
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,
}) => {
  //Search
  const [searchTerm, setSearchTerm] = useState('');
  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;
    setSearchTerm(value);

    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,
                }}>
                <Text style={{color: '#615f71', fontWeight: '500'}}>
                  {`Tuần ${numberWeekOfYear} `}{' '}
                </Text>
                <Text>{`${moment(managerDate?.currentDate).format(
                  'DD/MM/YYYY',
                )} - ${moment(managerDate?.theWeekend).format(
                  'DD/MM/YYYY',
                )}`}</Text>
                <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}}>
                <Text style={mainStyle.textTitle}>Danh sách nhân viên</Text>
                <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,
                    }}>
                    <Text style={mainStyle.tableHeaderTitle}>#</Text>
                  </View>
                  <View
                    style={{...mainStyle.tableHeaderContainer, width: '35%'}}>
                    <Text style={mainStyle.tableHeaderTitle}>Nhân viên</Text>
                  </View>
                  <View
                    style={{...mainStyle.tableHeaderContainer, width: '35%'}}>
                    <Text style={mainStyle.tableHeaderTitle}>
                      Trạng thái timesheet
                    </Text>
                  </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}}>
                            <Text
                              style={{fontWeight: 'bold', color: '#313131'}}>
                              {index + 1}
                            </Text>
                          </View>
                          <View style={{width: '35%'}}>
                            <Text
                              style={{fontWeight: 'bold', color: '#313131'}}>
                              {el?.user?.extend_user_full_name || '--'}
                            </Text>
                          </View>
                          <View
                            style={{
                              width: '35%',
                              flexDirection: 'row',
                              alignItems: 'center',
                            }}>
                            <View
                              style={{
                                ...mainStyle.dotStatus,
                                backgroundColor: el?.user?.extend_status_color
                                  ? '#34bfa3'
                                  : '#757575',
                                marginRight: 8,
                              }}></View>
                            <Text
                              style={{fontWeight: 'bold', color: '#313131'}}>
                              {el?.user?.status}
                            </Text>
                          </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%'}}>
                                <Text>Mã nhân viên</Text>
                              </View>
                              <View style={{width: '35%'}}>
                                <Text
                                  style={{
                                    fontWeight: 'bold',
                                    color: '#313131',
                                  }}>
                                  {el?.user?.employee_code || '--'}
                                </Text>
                              </View>
                              <View style={{width: '10%'}}></View>
                            </View>
                            <View style={mainStyle.tableRowContent}>
                              <View
                                style={{width: '20%', paddingLeft: 12}}></View>
                              <View style={{width: '35%'}}>
                                <Text>Phòng ban</Text>
                              </View>
                              <View style={{width: '35%'}}>
                                <Text
                                  style={{
                                    fontWeight: 'bold',
                                    color: '#313131',
                                  }}>
                                  {el?.user?.department || '--'}
                                </Text>
                              </View>
                              <View style={{width: '10%'}}></View>
                            </View>
                            <View style={mainStyle.tableRowContent}>
                              <View
                                style={{width: '20%', paddingLeft: 12}}></View>
                              <View style={{width: '35%'}}>
                                <Text>Chức vụ</Text>
                              </View>
                              <View style={{width: '35%'}}>
                                <Text
                                  style={{
                                    fontWeight: 'bold',
                                    color: '#313131',
                                  }}>
                                  {el?.user?.position || '--'}
                                </Text>
                              </View>
                              <View style={{width: '10%'}}></View>
                            </View>
                            <View style={mainStyle.tableRowContent}>
                              <View
                                style={{width: '20%', paddingLeft: 12}}></View>
                              <View style={{width: '35%'}}>
                                <Text>Số giờ</Text>
                              </View>
                              <View style={{width: '35%'}}>
                                <Text
                                  style={{
                                    fontWeight: 'bold',
                                    color: '#313131',
                                  }}>
                                  {el?.user?.extend_total_hour}
                                </Text>
                              </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}}>
                      <Text style={{textAlign: 'center'}}>
                        Không có dữ liệu
                      </Text>
                    </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>
                  <Text>{`Trang ${currentPage}/${totalPage}`}</Text>
                  <TouchableOpacity
                    onPress={() => onPageNext()}
                    disabled={currentPage === totalPage}>
                    <Image
                      source={IMAGES.IcArrowRight}
                      style={{width: 25, height: 25}}
                    />
                  </TouchableOpacity>
                </View>
              </View>
            )}
          </View>
        )}
      </View>
    </SafeAreaView>
  );
};

export default ConfirmedShiftScreen;
