/* eslint-disable prettier/prettier */
/* eslint-disable react/self-closing-comp */
import moment from 'moment';
import React from 'react';
import {useEffect} from 'react';
import {useState} from 'react';
import {useDispatch, useSelector} from 'react-redux';
import {
  getConfirmSheetDetail,
  getUserInfoById,
  getJobNameProject,
  approveReqTimeSheet,
  rejectReqTimeSheet,
} from '../../../../../store/actions/UserAction';
import ConfirmedShiftDetailScreen from './ConfirmedShiftDetailScreen';
import Toast from 'react-native-toast-message';
const ConfirmedShiftDetailContainer = props => {
  const dispatch = useDispatch();
  const userDetails = useSelector(state => state.UserInfo.userInfo);
  const timeSheetProjectInfo = useSelector(
    state => state.TimeSheetProjectInfo.timeSheetProject,
  );
  // init state
  const initJobTicket = {
    timesheet_id: '',
    projectName: '',
    jobName: '',
    taskName: '',
    description: '',
    projectId: '',
    jobId: '',
    timesheet_week_id: '',
    isDes: false,
    isSubmit: false,
    equalApproveId: false,
    isApproved: false,
    calendar: [],
  };
  //Week
  const [numberWeekOfYear, setNumberWeekOfYear] = useState();
  const [managerDate, setManagerDate] = useState({
    currentDate: props?.monday,
    theWeekend: props?.sunday,
  });
  const [totalTime, setTotalTime] = useState();
  //Data
  const [confirmSheetDetail, setConfirmSheetDetail] = useState([]);
  const [userInfo, setUserInfo] = useState(null);

  const [feedBack, setFeedback] = useState('');
  //API
  const fetchConfirmTimeSheetDetail = async (userId, numberOfWeek, year) => {
    const res = await dispatch(
      getConfirmSheetDetail(userId, numberOfWeek, year),
    );
    if (res) {
      // console.log("arrWork", arrWork)
      const {timesheet, weekInfo} = res;
      //console.log('timesheet', timesheet);
      if (timesheet.length > 0) {
        //console.log("timesheet.length > 0", timesheet)

        let job = {...initJobTicket};
        timesheet.map(async (item, index) => {
          const resGetJobNameProject = await dispatch(
            getJobNameProject(item.project_id),
          );
          let job_name = resGetJobNameProject.filter(
            item_name => item_name.id === item.task_type_id,
          );
          let project_name = timeSheetProjectInfo.filter(
            item_project => item.project_id === item_project.id,
          );
          // console.log("job_name", job_name)
          job.timesheet_id = item.id;
          job.projectName = project_name[0].name;
          job.jobName = job_name[0].name;
          job.taskName = item.task_name;
          job.description = item.task_notes;
          job.projectId = item.project_id;
          job.jobId = item.task_type_id;
          job.equalApproveId = weekInfo.approver_id == userDetails.id;
          job.isApproved = weekInfo.approved_status_id;
          job.isSubmit = weekInfo.submited;
          job.timesheet_week_id = item.timesheet_week_id;
          // load time
          job.calendar = [
            {
              title: 'T2',
              time: convertFloatToTime(item.mon),
              isOpen: false,
            },
            {
              title: 'T3',
              time: convertFloatToTime(item.tue),
              isOpen: false,
            },
            {
              title: 'T4',
              time: convertFloatToTime(item.wed),
              isOpen: false,
            },
            {
              title: 'T5',
              time: convertFloatToTime(item.thu),
              isOpen: false,
            },
            {
              title: 'T6',
              time: convertFloatToTime(item.fri),
              isOpen: false,
            },
            {
              title: 'T7',
              time: convertFloatToTime(item.sat),
              isOpen: false,
            },
            {
              title: 'CN',
              time: convertFloatToTime(item.sun),
              isOpen: false,
            },
            {
              title: 'Tổng',
            },
          ];
          //console.log('filterDuplicate', filterDuplicate);
          setConfirmSheetDetail(prevState => [...prevState, job]);
          job = {...initJobTicket};
          // console.log("job", job.calendar)
        });

        // if true -> job submitted

        //checkIsSubmitJob(weekInfo);
      }
    }
  };

  const fetchUserInfoData = async () => {
    const res = await dispatch(getUserInfoById(props.userId));
    if (res) {
      setUserInfo(res);
    }
  };

  //Others
  const getNumberWeekOfYear = currentDate => {
    //console.log(props);
    setNumberWeekOfYear(Number(moment(new Date(currentDate)).format('W')));
  };

  const nextWeek = () => {
    resetData();

    const monday_in_next_week = moment(managerDate.currentDate).add(7, 'days');
    const sunday_in_next_week = moment(monday_in_next_week).add(6, 'days');

    setManagerDate({
      currentDate: monday_in_next_week,
      theWeekend: sunday_in_next_week,
    });
    getNumberWeekOfYear(new Date(monday_in_next_week));
  };

  const prevWeek = () => {
    resetData();
    const monday_in_next_week = moment(managerDate.currentDate).subtract(
      7,
      'days',
    );
    const sunday_in_next_week = moment(managerDate.currentDate).subtract(
      1,
      'days',
    );
    setManagerDate({
      currentDate: monday_in_next_week,
      theWeekend: sunday_in_next_week,
    });
    getNumberWeekOfYear(new Date(monday_in_next_week));
  };
  const convertFloatToTime = value => {
    let h = Math.floor(value);
    let d = value - h;
    let p = Math.round(d * 60);
    if (h < 10 && p < 10) {
      return '0' + h + ':0' + p;
    }
    if (h < 10 && p > 10) {
      return '0' + h + ':' + p;
    }
    if (p < 10) {
      return h + ':0' + p;
    }
    return h + ':' + p;
  };
  const parseHoursToNumber = hour => {
    //console.log("hour", hour)
    var arr = hour.split(':');
    var dec = parseInt(arr[1], 10);
    //console.log("dec", dec)
    return parseFloat(parseInt(arr[0], 10) + '.' + (dec < 10 ? '0' : '') + dec);
  };
  const onChangeTime = () => {
    //console.log('arrJob', arrJob);
    let total_time = 0;
    confirmSheetDetail.map((item, index) => {
      //console.log("item", item.calendar[index])
      item.calendar &&
        item.calendar.map((item, index) => {
          //console.log("item", item)
          if (item.time !== undefined && item.time !== '00:00' && item.time) {
            //console.log("item.time", item.time)
            total_time += parseHoursToNumber(item.time.toString());
          }
        });

      //console.log("item", item.time);
    });
    // console.log("total_time", total_time)
    setTotalTime(total_time.toFixed(2));
  };
  const onCollapseView = index => {
    const clone = [...confirmSheetDetail];
    clone[index].isExpand = false;
    //console.log("id", clone[index].isExpand)
    setConfirmSheetDetail(clone);
  };
  const onExpandView = index => {
    const clone = [...confirmSheetDetail];
    clone[index].isExpand = true;
    //console.log("id", clone[index].isExpand)
    setConfirmSheetDetail(clone);
  };
  const resetData = () => {
    setConfirmSheetDetail([]);
  };
  const onSubmitApproveReq = async () => {
    if (feedBack.length === 0) {
      return;
    }
    const res = await dispatch(
      approveReqTimeSheet(confirmSheetDetail[0].timesheet_week_id),
    );
    if (res) {
      Toast.show({
        type: 'success',
        text1: `Hệ thống`,
        text2: `Duyệt thành công`,
        visibilityTime: 2000,
      });
      // reset
      const clone = [...confirmSheetDetail];
      clone[0].isApproved = true;
      setConfirmSheetDetail(clone);
    } else {
      Toast.show({
        type: 'error',
        text1: `Hệ thống`,
        text2: `Duyệt thất bại`,
        visibilityTime: 2000,
      });
    }
  };
  const onRejectApproveReq = async () => {
    const res = await dispatch(
      rejectReqTimeSheet(confirmSheetDetail[0].timesheet_week_id),
    );
    if (res) {
      Toast.show({
        type: 'success',
        text1: `Hệ thống`,
        text2: `Từ chối thành công`,
        visibilityTime: 2000,
      });
    } else {
      Toast.show({
        type: 'error',
        text1: `Hệ thống`,
        text2: `Từ chối thất bại`,
        visibilityTime: 2000,
      });
    }
  };

  //useEffect zone
  useEffect(() => {
    setNumberWeekOfYear(props?.numberOfWeek);
    fetchUserInfoData();
  }, []);

  useEffect(() => {
    numberWeekOfYear &&
      fetchConfirmTimeSheetDetail(props.userId, numberWeekOfYear, props.year);
  }, [numberWeekOfYear]);
  useEffect(() => {
    confirmSheetDetail && onChangeTime();
  }, [confirmSheetDetail]);

  const confirmShiftDetailProps = {
    numberWeekOfYear,
    managerDate,
    confirmSheetDetail,
    userInfo,
    totalTime,
    feedBack,
    nextWeek,
    prevWeek,
    getNumberWeekOfYear,
    onCollapseView,
    onExpandView,
    setFeedback,
    onSubmitApproveReq,
    onRejectApproveReq,
  };
  return <ConfirmedShiftDetailScreen {...confirmShiftDetailProps} />;
};

export default ConfirmedShiftDetailContainer;
