import React, {useEffect, useState} from 'react';
import {useDispatch, useSelector} from 'react-redux';
import ShiftScreen from './ShiftScreen';
import {
  getTimeSheetProject,
  getJobNameProject,
  postUserAddJob,
  getUserJob,
  getManagers,
  postSubmitUserAddJob,
} from '../../store/actions/UserAction';
import Moment from 'moment';
import Toast from 'react-native-toast-message';
import {convertTimeToFloat} from '../../components/common/common';
const ShiftContainer = () => {
  const dispatch = useDispatch();
  const userDetails = useSelector(state => state.UserInfo.userInfo);
  const timeSheetProjectInfo = useSelector(
    state => state.TimeSheetProjectInfo.timeSheetProject,
  );
  const loadingGetJobOfUser = useSelector(
    state => state.LoadingJobOfUser.isLoading,
  );
  const userDirectManagersList = useSelector(
    state => state.MyDirectManagers.myDirectManagers,
  );
  //console.log('userDirectManagersList', userDirectManagersList);
  // Week
  const [numberWeekOfYear, setNumberWeekOfYear] = useState();
  const [managerDate, setManagerDate] = useState({
    currentDate: Moment().startOf('week').toDate(),
    theWeekend: Moment().endOf('week').toDate(),
  });
  // init state
  const initJobTicket = {
    timesheet_id: '',
    projectName: '',
    jobName: '',
    taskName: '',
    description: '',
    projectId: '',
    jobId: '',
    isDes: false,
    isSubmit: false,
    calendar: [],
  };
  const [totalTime, setTotalTime] = useState();
  const [dataDropDown, setDataDropDown] = useState({
    projectName: '',
    jobName: '',
    projectId: '',
    jobId: '',
  });
  const [managerDisabled, setDisabled] = useState({
    dropdown: false,
    desInput: false,
    datePicker: false,
  });
  const [jobTicket, setJobTicket] = useState([]);
  const [arrJob, setArrJob] = useState([]);
  const [managerArr, setManager] = useState({
    nameManager: [],
    managerList: [],
    selectManager: [],
  });
  const [isLoading, setLoading] = useState(false);
  const [showAlert, setShowAlert] = useState({
    isError: false,
    title: '',
    message: '',
    deleteItem: '',
    isShowActionBtn: true,
  });
  //error task name handling
  const [error, setError] = useState(false);
  //API
  const loadWorkOfTheWeek = async () => {
    setLoading(true);
    if (timeSheetProjectInfo.length > 0) {
      //console.log('loadWorkOfTheWeek');
      const year = new Date(managerDate.currentDate);
      const arrWork = await dispatch(
        getUserJob(year.getFullYear(), numberWeekOfYear),
      );
      // console.log("arrWork", arrWork)
      const {timesheet, weekInfo} = arrWork;
      //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.isSubmit = weekInfo.submited;
          // 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);
          setArrJob(prevState => [...prevState, job]);
          job = {
            timesheet_id: '',
            projectName: '',
            jobName: '',
            taskName: '',
            description: '',
            projectId: '',
            jobId: '',
            isDes: false,
            isSubmit: false,
            calendar: [],
          };
          // console.log("job", job.calendar)
        });
        //console.log("nameProject", nameProject)
        // if true -> job submitted

        checkIsSubmitJob(weekInfo);
        setLoading(false);
        return;
      }

      // don't have data
      // setDayOfWeek(initialWeek)
      setDisabled({
        dropdown: false,
        desInput: false,
        datePicker: false,
      });
      setInitData();
    }

    setLoading(false);
  };
  const loadManager = async () => {
    const res = await dispatch(getManagers());
    // console.log('loadManager', res);
    if (res.success) {
      if (res.data && res.data.length > 0) {
        let arrManagerName = [];
        res.data.forEach(
          item => item && arrManagerName.push(item.extend_user_full_name),
        );
        //console.log(arrManagerName);
        setManager(prev => ({
          ...prev,
          nameManager: arrManagerName,
          managerList: res.data,
        }));
      }
    }
  };
  //Others
  const loadFirstAndLastDay = () => {
    setManagerDate({
      currentDate: Moment().startOf('week').add(1, 'day').toDate(),
      theWeekend: Moment().endOf('week').add(1, 'day').toDate(),
    });
  };
  const getNumberWeekOfYear = currentDate => {
    setNumberWeekOfYear(Number(Moment(new Date(currentDate)).format('W')));
  };

  const nextWeek = () => {
    //console.log("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 = () => {
    //console.log("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 loadProjectName = async () => {
    const arrProject = await dispatch(getTimeSheetProject());
    if (arrProject.length > 0) {
      //console.log("timeSheetProjectInfo.length > 0", timeSheetProjectInfo.length)
      const projectName = [];
      const projectId = [];
      arrProject.map((item, index) => {
        projectId.push(item.id);
        projectName.push(item.name);
        //console.log("item", item)
      });
      setDataDropDown(prevState => ({
        ...prevState,
        projectName: projectName,
        projectId: projectId,
      }));
    }
  };

  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 checkIsSubmitJob = weekInfo => {
    if (weekInfo.submited) {
      //console.log("isSubmit")
      // disable field
      setDisabled({
        dropdown: true,
        desInput: true,
        datePicker: true,
      });
    } else {
      setDisabled({
        dropdown: false,
        desInput: false,
        datePicker: false,
      });
    }
  };
  const loadJobName = async projectId => {
    if (projectId !== undefined) {
      const resGetJobNameProject = await dispatch(getJobNameProject(projectId));
      //console.log(resGetJobNameProject)
      var arrJobName = [];
      var arrJobId = [];
      resGetJobNameProject.map((item, index) => {
        arrJobName.push(item.name), arrJobId.push(item.id);
      });
      setDataDropDown(prevState => ({
        ...prevState,
        jobName: arrJobName,
        jobId: arrJobId,
      }));
      //console.log("res", res)
    }
  };
  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;
    arrJob.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 onChangeSelectDropDownProjectName = (
    selectedItem,
    projectId,
    index,
  ) => {
    let clone = [...arrJob];
    clone[index].projectName = selectedItem;
    clone[index].projectId = projectId;
    clone[index].jobName = 'Tên công việc';
    // console.log(clone)
    setArrJob(clone);
    loadJobName(projectId);
  };
  const onChangeSelectDropDownJobName = (selectedItem, jobId, index) => {
    let clone = [...arrJob];
    clone[index].jobName = selectedItem;
    clone[index].jobId = jobId;

    // console.log(clone)
    setArrJob(clone);
  };
  const onChangeTextDes = (text, index) => {
    if (text) setError(false);
    let clone = [...arrJob];
    clone[index].taskName = text;
    // console.log(clone)
    setArrJob(clone);
  };
  const onChangeTextNote = (text, index) => {
    let clone = [...arrJob];
    clone[index].description = text;
    // console.log(clone)
    setArrJob(clone);
  };
  const managerTimePicker = (mode, item, index, index_arr) => {
    // console.log("index_arr", index_arr)
    // console.log("index_arr", item)
    let cloneItem = {...item};
    let cloneTicket = [...arrJob];
    //console.log("calendar", cloneTicket[index_arr].calendar[index])
    if (mode === 'open') {
      cloneItem.isOpen = true;
      cloneTicket[index_arr].calendar[index] = cloneItem;
      setArrJob(cloneTicket);
    } else {
      cloneItem.isOpen = false;
      cloneTicket[index_arr].calendar[index] = cloneItem;
      setArrJob(cloneTicket);
    }
  };
  const setTime = (item, index, index_arr, time) => {
    //console.log("item", item)
    let cloneItem = {...item};
    let cloneTicket = [...arrJob];
    cloneItem.isOpen = false;
    cloneItem.time = Moment(time).format('HH:mm');
    cloneTicket[index_arr].calendar[index] = cloneItem;
    setArrJob(cloneTicket);
  };
  const checkValidTicket = () => {
    const arrFilter = arrJob.filter(item => item.jobName === 'Tên công việc');

    return (arrFilter.length > 0 && true) || false;
  };
  const onJustSave = async () => {
    try {
      setLoading(true);
      const isValidTicket = checkValidTicket();
      //console.log("isValidTicket", isValidTicket)
      if (isValidTicket) {
        Toast.show({
          type: 'error',
          text1: 'Hệ thống',
          text2: 'Vui lòng chọn tên công việc 👋',
        });
        return;
      }
      const year = new Date(managerDate.currentDate);
      let ticket = {
        mon: 0,
        tue: 0,
        wed: 0,
        thu: 0,
        fri: 0,
        sat: 0,
        sun: 0,
        project_id: '',
        task_name: '',
        task_notes: '',
        task_type_id: '',
      };
      const payload = [];
      arrJob.map((item, index) => {
        //console.log("item.taskName", item.taskName === '')
        const isValid = validateItem(item);
        if (isValid) {
          //console.log("item.projectId", item.projectId)
          for (let i = 0; i < item.calendar.length; i++) {
            if (item.calendar[i].title === 'T2') {
              ticket.mon = convertTimeToFloat(item.calendar[i].time.toString());
            } else if (item.calendar[i].title === 'T3') {
              ticket.tue = convertTimeToFloat(item.calendar[i].time.toString());
            } else if (item.calendar[i].title === 'T4') {
              ticket.wed = convertTimeToFloat(item.calendar[i].time.toString());
            } else if (item.calendar[i].title === 'T5') {
              ticket.thu = convertTimeToFloat(item.calendar[i].time.toString());
            } else if (item.calendar[i].title === 'T6') {
              ticket.fri = convertTimeToFloat(item.calendar[i].time.toString());
            } else if (item.calendar[i].title === 'T7') {
              ticket.sat = convertTimeToFloat(item.calendar[i].time.toString());
            } else if (item.calendar[i].title === 'CN') {
              ticket.sun = convertTimeToFloat(item.calendar[i].time.toString());
            }
          }
          ticket.project_id = item.projectId;
          ticket.task_name = item.taskName;
          ticket.task_notes = item.description;
          ticket.task_type_id = item.jobId;
          payload.push(ticket);
          ticket = {
            mon: 0,
            tue: 0,
            wed: 0,
            thu: 0,
            fri: 0,
            sat: 0,
            sun: 0,
            project_id: '',
            task_name: '',
            task_notes: '',
            task_type_id: '',
          };
        }
      });
      //console.log('payload', payload);
      if (payload.length > 0) {
        const res = await dispatch(
          postUserAddJob(year.getFullYear(), numberWeekOfYear, payload),
        );
        if (res) {
          Toast.show({
            type: 'success',
            text1: 'Hệ thống',
            text2: 'Lưu công việc thành công 👋',
          });
        } else {
          // // error
          Toast.show({
            type: 'error',
            text1: 'Hệ thống',
            text2: 'Lưu công việc thất bại',
          });
        }
      }
      setLoading(false);
    } catch (err) {
      setLoading(false);
      console.error(err);
    }
  };
  const validateItem = item => {
    if (item.taskName.length < 0 || item.taskName === '') {
      setError(true);
      return false;
    }
    if (item.projectId.length < 0 || item.projectId === '') {
      Toast.show({
        type: 'error',
        text1: 'Hệ thống',
        text2: 'Vui lòng chọn dự án và tên công việc 👋',
      });
      return false;
    }
    if (totalTime <= 0) {
      Toast.show({
        type: 'error',
        text1: 'Hệ thống',
        text2: 'Vui lòng chọn thời gian làm việc tối thiểu 👋',
      });
      return false;
    }
    if (managerArr.selectManager.length === 0) {
      Toast.show({
        type: 'error',
        text1: 'Hệ thống',
        text2: 'Vui lòng chọn người duyệt',
      });
      return false;
    }
    return true;
  };
  const onPressSend = async () => {
    try {
      setLoading(true);
      const year = new Date(managerDate.currentDate);
      let ticket = {
        mon: 0,
        tue: 0,
        wed: 0,
        thu: 0,
        fri: 0,
        sat: 0,
        sun: 0,
        project_id: '',
        task_name: '',
        task_notes: '',
        task_type_id: '',
      };
      const payload = [];
      arrJob.map((item, index) => {
        // console.log("item.projectId", item.projectId)
        const isValid = validateItem(item);
        if (isValid) {
          for (let i = 0; i < item.calendar.length; i++) {
            if (item.calendar[i].title === 'T2') {
              ticket.mon = convertTimeToFloat(item.calendar[i].time);
            } else if (item.calendar[i].title === 'T3') {
              ticket.tue = convertTimeToFloat(item.calendar[i].time);
            } else if (item.calendar[i].title === 'T4') {
              ticket.wed = convertTimeToFloat(item.calendar[i].time);
            } else if (item.calendar[i].title === 'T5') {
              ticket.thu = convertTimeToFloat(item.calendar[i].time);
            } else if (item.calendar[i].title === 'T6') {
              ticket.fri = convertTimeToFloat(item.calendar[i].time);
            } else if (item.calendar[i].title === 'T7') {
              ticket.sat = convertTimeToFloat(item.calendar[i].time);
            } else if (item.calendar[i].title === 'CN') {
              ticket.sun = convertTimeToFloat(item.calendar[i].time);
            }
          }
          ticket.project_id = item.projectId;
          ticket.task_name = item.taskName;
          ticket.task_notes = item.description;
          ticket.task_type_id = item.jobId;
          payload.push(ticket);
          ticket = {
            mon: 0,
            tue: 0,
            wed: 0,
            thu: 0,
            fri: 0,
            sat: 0,
            sun: 0,
            project_id: '',
            task_name: '',
            task_notes: '',
            task_type_id: '',
          };
        }
      });
      //console.log('payload', payload);
      if (managerArr.selectManager.length === 0) {
        Toast.show({
          type: 'error',
          text1: 'Hệ thống',
          text2: 'Vui lòng chọn người duyệt',
        });
        setLoading(false);
        return;
      }
      if (payload.length > 0) {
        const res = await dispatch(
          postUserAddJob(year.getFullYear(), numberWeekOfYear, payload),
        );
        if (res) {
          //console.log("postUserAddJob")
          const resGetUserJob = await dispatch(
            getUserJob(year.getFullYear(), numberWeekOfYear),
          );
          //console.log("resGetUserJob.length > 0", resGetUserJob)
          if (resGetUserJob !== undefined) {
            const {weekInfo} = resGetUserJob;
            const resRequestPostSubmitAddJob = await dispatch(
              postSubmitUserAddJob(
                weekInfo.id,
                managerArr.selectManager[0].id,
                weekInfo.week_notes,
              ),
            );
            if (resRequestPostSubmitAddJob) {
              //console.log("resRequestPostSubmitAddJob")
              setLoading(false);
              Toast.show({
                type: 'success',
                text1: 'Hệ thống',
                text2: 'Nộp công việc thành công 👋',
              });
              checkIsSubmitJob(weekInfo);
              let newArr = [...arrJob];
              newArr[0].isSubmit = true;
              setArrJob(newArr);
              return;
            } else {
              setLoading(false);
              Toast.show({
                type: 'error',
                text1: 'Hệ thống',
                text2: 'Nộp Timesheet thất bại 💔',
              });
            }
          }
        }
      }

      setLoading(false);
    } catch (e) {
      setLoading(false);
      console.error(e);
    }
  };
  const onPressRightIcon = index => {
    let clone = [...arrJob];
    clone[index].isDes = true;
    setArrJob(clone);
  };
  const onPressCloseDesInput = index => {
    let clone = [...arrJob];
    clone[index].isDes = false;
    setArrJob(clone);
  };

  const addMoreJob = () => {
    //console.log(arrJob.length === 0)
    if (arrJob.length === 0) {
      let clone = {...initJobTicket};
      clone.calendar = [
        {
          title: 'T2',
          time: 0,
          isOpen: false,
        },
        {
          title: 'T3',
          time: 0,
          isOpen: false,
        },
        {
          title: 'T4',
          time: 0,
          isOpen: false,
        },
        {
          title: 'T5',
          time: 0,
          isOpen: false,
        },
        {
          title: 'T6',
          time: 0,
          isOpen: false,
        },
        {
          title: 'T7',
          time: 0,
          isOpen: false,
        },
        {
          title: 'CN',
          time: 0,
          isOpen: false,
        },
        {
          title: 'Tổng',
        },
      ];
      setArrJob(prevState => [...prevState, clone]);
      return;
    }
    if (arrJob && !arrJob[0]?.isSubmit) {
      let clone = {...initJobTicket};
      clone.calendar = [
        {
          title: 'T2',
          time: 0,
          isOpen: false,
        },
        {
          title: 'T3',
          time: 0,
          isOpen: false,
        },
        {
          title: 'T4',
          time: 0,
          isOpen: false,
        },
        {
          title: 'T5',
          time: 0,
          isOpen: false,
        },
        {
          title: 'T6',
          time: 0,
          isOpen: false,
        },
        {
          title: 'T7',
          time: 0,
          isOpen: false,
        },
        {
          title: 'CN',
          time: 0,
          isOpen: false,
        },
        {
          title: 'Tổng',
        },
      ];
      setArrJob(prevState => [...prevState, clone]);
    } else {
      Toast.show({
        type: 'error',
        text1: 'Hệ thống',
        text2: 'Timesheet đã nộp không thể thêm mới 💔',
      });
    }
  };
  const resetData = () => {
    setArrJob([]);
  };
  const setInitData = () => {
    let clone = {...initJobTicket};
    clone.calendar = [
      {
        title: 'T2',
        time: 0,
        isOpen: false,
      },
      {
        title: 'T3',
        time: 0,
        isOpen: false,
      },
      {
        title: 'T4',
        time: 0,
        isOpen: false,
      },
      {
        title: 'T5',
        time: 0,
        isOpen: false,
      },
      {
        title: 'T6',
        time: 0,
        isOpen: false,
      },
      {
        title: 'T7',
        time: 0,
        isOpen: false,
      },
      {
        title: 'CN',
        time: 0,
        isOpen: false,
      },
      {
        title: 'Tổng',
      },
    ];
    setArrJob(prevState => [...prevState, clone]);
  };
  const onCollapseView = index => {
    const clone = [...arrJob];
    clone[index].isExpand = false;
    //console.log("id", clone[index].isExpand)
    setArrJob(clone);
  };
  const onExpandView = index => {
    const clone = [...arrJob];
    clone[index].isExpand = true;
    //console.log("id", clone[index].isExpand)
    setArrJob(clone);
  };
  const onDeleteItem = item => {
    setShowAlert({
      isError: true,
      title: 'Hệ thống',
      message: 'Bạn có muốn xóa công việc này không ?',
      isShowActionBtn: true,
      deleteItem: item,
    });
  };
  const hideAlert = () => {
    setShowAlert({
      isError: false,
      title: 'hệ thống',
      message: 'Xóa thành công',
      deleteItem: '',
      isShowActionBtn: false,
    });
  };
  const onConfirmDelete = () => {
    const clone = [...arrJob];
    const res = clone.filter(el => el !== showAlert.deleteItem);
    // console.log("res", res)
    hideAlert();
    setArrJob(res);
  };
  const onSelectManagement = nameManager => {
    const filter = managerArr.managerList.filter(
      item => item.extend_user_full_name == nameManager && item,
    );
    //console.log(filter);
    setManager(prev => ({...prev, selectManager: filter}));
  };
  // useEffect
  useEffect(() => {
    getNumberWeekOfYear(new Date());
    loadProjectName();
    loadFirstAndLastDay();
    loadManager();
  }, []);

  useEffect(() => {
    managerDate &&
      numberWeekOfYear &&
      timeSheetProjectInfo &&
      loadWorkOfTheWeek();
  }, [managerDate, numberWeekOfYear, timeSheetProjectInfo]);

  useEffect(() => {
    arrJob && onChangeTime();
  }, [arrJob]);

  const shiftProps = {
    userDetails,
    managerDate,
    numberWeekOfYear,
    jobTicket,
    dataDropDown,
    totalTime,
    managerDisabled,
    loadingGetJobOfUser,
    isLoading,
    arrJob,
    error,
    showAlert,
    managerArr,
    onConfirmDelete,
    onExpandView,
    onJustSave,
    onPressSend,
    setJobTicket,
    prevWeek,
    nextWeek,
    loadJobName,
    managerTimePicker,
    setTime,
    onPressRightIcon,
    onPressCloseDesInput,
    addMoreJob,
    setArrJob,
    onChangeSelectDropDownProjectName,
    onChangeSelectDropDownJobName,
    onChangeTextDes,
    onChangeTextNote,
    onCollapseView,
    onDeleteItem,
    hideAlert,
    onSelectManagement,
  };
  return <ShiftScreen {...shiftProps} />;
};

export default ShiftContainer;
