/* eslint-disable prettier/prettier */
import Moment from 'moment';
import React, {useEffect, useState} from 'react';
import {useDispatch, useSelector} from 'react-redux';
import {
  getDataChartTimekeeping,
  getDescriptionTimekeeping,
} from '../../store/actions/UserAction';
import WorkLoadScreen from './WorkLoadScreen';
const WorkLoadContainer = props => {
  const {userDetails} = props;
  const dispatch = useDispatch();
  const loadingDataChart = useSelector(
    state => state.LoadingDataChart.isLoading,
  );
  const loadingTimeKeeping = useSelector(
    state => state.LoadingTimeKeeping.isLoading,
  );
  //console.log("loadingTimeKeeping", loadingTimeKeeping)

  const [dataChart, setDataChart] = useState();
  const [openTimePicker, setOpenTimePicker] = useState({
    start: false,
    finish: false,
  });
  const [timeFilter, setTimeFilter] = useState({
    start: new Date(),
    finish: new Date(),
  });

  const [toggleCheckBox, setToggleCheckBox] = useState({
    start: false,
    finish: false,
  });
  const [table, setTableData] = useState();
  const [isLoading, setLoading] = useState(false);
  const [payload, setPayload] = useState({
    filter:
      'time_input>=2022-10-15T00:00:00.000+07:00,time_input<=2022-11-15T23:59:59.000+07:00',
    page: 1,
    pageSize: 10,
    type: '',
  });
  const [isPayload, setIsPayload] = useState();
  const [infoTable, setInfoTable] = useState({
    from: 0,
    to: 0,
    total: 0,
    isLastPage: false,
  });
  const [chooseMonth, setChooseMonth] = useState(new Date());

  const showDatePicker = type => {
    if (type === 'start')
      setOpenTimePicker(state => ({
        ...state,
        start: true,
      }));
    else {
      setOpenTimePicker(state => ({
        ...state,
        finish: true,
      }));
    }
  };

  const hideDatePicker = type => {
    if (type === 'start') setOpenTimePicker({start: false});
    else setOpenTimePicker({finish: false});
  };
  const handleConfirm = (type, date) => {
    if (type === 'start') {
      hideDatePicker('start');
      setTimeFilter(prevState => ({
        ...prevState,
        start: date,
      }));
    } else {
      hideDatePicker('finish');
      setTimeFilter(prevState => ({
        ...prevState,
        finish: date,
      }));
    }
  };

  const addTableData = arr => {
    let cloneTable = [];
    arr.forEach((item, index) => {
      //console.log("item", item.time_output)
      let ticketDate = {
        total:
          item.time_for_salary_second !== undefined
            ? parseFloat(item.time_for_salary_second / 60 / 60).toFixed(0)
            : 0,
        date: item.time_input && Moment(item.time_input).format('DD/MM/YYYY'),
        time_input:
          item.time_input && Moment(item.time_input).format('HH:mm:ss'),
        time_output:
          (item.time_ouput && Moment(item.time_ouput).format('HH:mm:ss')) ||
          null,
        time_work_late:
          parseFloat((item.late_input_time_second / 60).toFixed(0)) + ' Phút',
        leave_early:
          parseFloat((item.soon_output_time_second / 60).toFixed(0)) + ' Phút',
        isError:
          parseFloat((item.late_input_time_second / 60).toFixed(0)) > 1 ||
          parseFloat(item.soon_output_time_second / 60).toFixed(0) > 1
            ? true
            : false,
      };

      cloneTable.push(ticketDate);
    });
    //console.log('arr.length', arr.length);
    setTableData(cloneTable);
  };
  const addPagination = (arr, total, pagesize, pageIndex, type) => {
    if (arr.length < 10) {
      setInfoTable({
        from: pageIndex === 1 ? infoTable.from + pageIndex : total - arr.length,
        to: total,
        total: total,
        isLastPage: true,
      });
      return;
    }
    if (type === 'plus') {
      setInfoTable({
        from:
          pageIndex === 1
            ? infoTable.from + pageIndex
            : infoTable.from + pagesize,
        to: infoTable.to + pagesize,
        total: total,
        isLastPage: false,
      });
    } else if (type === 'fstPage') {
      setInfoTable({
        from: 1,
        to: 10,
        total: total,
        isLastPage: false,
      });
    } else {
      if (infoTable.to == total) {
        setInfoTable({
          from: infoTable.from - (infoTable.from % 10) - 10 + 1,
          to: total - (total % 10),
          total: total,
          isLastPage: false,
        });
      } else {
        setInfoTable({
          from: infoTable.from - 10,
          to: infoTable.to - 10,
          total: total,
          isLastPage: false,
        });
      }
    }
  };
  const addDataToChart = arr => {
    let labels = [];
    let datasets = [
      {
        data: [],
        colors: [],
      },
    ];
    let dataChart = {
      labels: '',
      datasets: [],
    };

    arr.map((item, index) => {
      // console.log("item", item.time_input)

      labels.push(Moment(item.date).format('DD/MM'));
      datasets[0].data.push(parseFloat(item.sum / 60).toFixed(1));
      datasets[0].colors.push((opacity = 1) => `#0abb87`);
    });

    // console.log("labels", labels)
    // console.log("datasets", datasets)
    dataChart.labels = labels;
    dataChart.datasets = datasets;
    //console.log("dataChart", dataChart)
    setDataChart(dataChart);
  };

  const dataChartByMonth = async () => {
    setLoading(true);
    const firstDay = new Date(
      Moment(chooseMonth).startOf('month').add(1, 'day').toDate(),
    );
    const lastDay = new Date(
      Moment(chooseMonth).endOf('month').add(1, 'day').toDate(),
    );
    const res = await dispatch(
      getDataChartTimekeeping(firstDay.toISOString(), lastDay.toISOString()),
    );
    if (res.length > 0) {
      addDataToChart(res);
      setLoading(false);
    }
    setLoading(false);
    //console.log("res", res)
  };

  {
    /** load data when payload changed */
  }
  const loadDataTableWithPayload = async () => {
    //console.log("aaa")
    setLoading(true);
    //console.log("formatLtDay", formatFtDay.toISOString())
    const arrTimekeeping = await dispatch(
      getDescriptionTimekeeping(
        payload.filter,
        payload.page,
        payload.pageSize,
        '',
      ),
    );
    //console.log("arrTimekeeping", arrTimekeeping)
    const {collection, total, pagesize, pageIndex} = arrTimekeeping;
    //console.log("collection", collection)
    if (collection && collection.length >= 1) {
      addTableData(collection);
      addPagination(collection, total, pagesize, pageIndex, 'plus');
    }
    setLoading(false);
  };

  // pagination of table
  const onSubmitFilter = async () => {
    setLoading(true);
    setInfoTable({
      from: 0,
      to: 0,
      total: 0,
      isLastPage: false,
    });
    let typeCheckbox = '';
    const formatSince = new Date(
      Moment(timeFilter.start).add(1, 'days').toDate().setHours(0),
    );
    const formatFinish = new Date(
      Moment(timeFilter.finish).add(1, 'days').toDate().setHours(0),
    );
    //console.log('formatSince', formatSince);
    //console.log('formatFinish', formatFinish);
    if (toggleCheckBox.start) {
      typeCheckbox = `,(late_input_time_second%7Csoon_output_time_second)%3E0,`;
    } else if (toggleCheckBox.finish)
      typeCheckbox = `,late_input_time_second%3E0`;
    else {
      typeCheckbox = '';
    }

    const arrTimekeeping = await dispatch(
      getDescriptionTimekeeping(
        `time_input>=${formatSince.toISOString()},time_input<=${formatFinish.toISOString()}${typeCheckbox}`,
        1,
        10,
        '',
      ),
    );
    const {collection, total, pagesize, pageIndex} = arrTimekeeping;
    //console.log('collection', arrTimekeeping);
    if (collection && collection.length >= 1) {
      addTableData(collection);
      addPagination(collection, total, pagesize, pageIndex, 'fstPage');
      setLoading(false);
      return;
    }
    // not have data
    setTableData(null);
    setLoading(false);
  };
  const nextPage = () => {
    let typeCheckbox = '';
    const formatSince = new Date(
      Moment(timeFilter.start).add(1, 'days').toDate().setHours(0),
    );
    const formatFinish = new Date(
      Moment(timeFilter.finish).add(1, 'days').toDate().setHours(0),
    );
    // console.log("formatSince",formatSince)
    //console.log("formatFinish", formatFinish)
    if (toggleCheckBox.start) {
      typeCheckbox = `,(late_input_time_second%7Csoon_output_time_second)%3E0,`;
    } else if (toggleCheckBox.finish)
      typeCheckbox = `,late_input_time_second%3E0`;
    else {
      typeCheckbox = '';
    }
    setPayload({
      filter: `time_input>=${formatSince.toISOString()},time_input<=${formatFinish.toISOString()}${typeCheckbox}`,
      page: payload.page + 1,
      pageSize: 10,
      type: 'plus',
    });
    setIsPayload(true);
  };
  const prevPage = () => {
    let typeCheckbox = '';
    const formatSince = new Date(
      Moment(timeFilter.start).add(1, 'days').toDate().setHours(0),
    );
    const formatFinish = new Date(
      Moment(timeFilter.finish).add(1, 'days').toDate().setHours(0),
    );
    // console.log("formatSince",formatSince)
    //console.log("formatFinish", formatFinish)
    if (toggleCheckBox.start) {
      typeCheckbox = `,(late_input_time_second%7Csoon_output_time_second)%3E0,`;
    } else if (toggleCheckBox.finish)
      typeCheckbox = `,late_input_time_second%3E0`;
    else {
      typeCheckbox = '';
    }
    setPayload({
      filter: `time_input>=${formatSince.toISOString()},time_input<=${formatFinish.toISOString()}${typeCheckbox}`,
      page: payload.page - 1,
      pageSize: 10,
      type: 'subtract',
    });
    setIsPayload(true);
  };
  const lastPage = () => {
    if (infoTable.total >= 10) {
      //infoTable.total % 10
      //console.log(infoTable.total % 10);
      let typeCheckbox = '';
      const formatSince = new Date(
        Moment(timeFilter.start).add(1, 'days').toDate().setHours(0),
      );
      const formatFinish = new Date(
        Moment(timeFilter.finish).add(1, 'days').toDate().setHours(0),
      );
      // console.log("formatSince",formatSince)
      //console.log("formatFinish", formatFinish)
      if (toggleCheckBox.start) {
        typeCheckbox = `,(late_input_time_second%7Csoon_output_time_second)%3E0,`;
      } else if (toggleCheckBox.finish)
        typeCheckbox = `,late_input_time_second%3E0`;
      else {
        typeCheckbox = '';
      }
      setPayload({
        filter: `time_input>=${formatSince.toISOString()},time_input<=${formatFinish.toISOString()}${typeCheckbox}`,
        page:
          (infoTable.total % 10).toFixed(0) != 0
            ? (infoTable.total / 10 + 1).toFixed(0)
            : (infoTable.total / 10).toFixed(0),
        pageSize: infoTable.total % 10,
      });
      setIsPayload(true);
    }
  };
  const firstPage = () => {
    let typeCheckbox = '';
    const formatSince = new Date(
      Moment(timeFilter.start).add(1, 'days').toDate().setHours(0),
    );
    const formatFinish = new Date(
      Moment(timeFilter.finish).add(1, 'days').toDate().setHours(0),
    );
    // console.log("formatSince",formatSince)
    //console.log("formatFinish", formatFinish)
    if (toggleCheckBox.start) {
      typeCheckbox = `,(late_input_time_second%7Csoon_output_time_second)%3E0,`;
    } else if (toggleCheckBox.finish)
      typeCheckbox = `,late_input_time_second%3E0`;
    else {
      typeCheckbox = '';
    }
    setPayload({
      filter: `time_input>=${formatSince.toISOString()},time_input<=${formatFinish.toISOString()}${typeCheckbox}`,
      page: 1,
      pageSize: 10,
      type: 'fstPage',
    });
    setIsPayload(true);
  };

  useEffect(() => {
    chooseMonth && dataChartByMonth();
  }, [chooseMonth]);

  useEffect(() => {
    payload && isPayload && loadDataTableWithPayload();
  }, [payload, isPayload]);

  // useEffect(() => {
  //   infoTable && console.log(infoTable);
  // }, [infoTable]);

  const shiftProps = {
    userDetails,
    openTimePicker,
    timeFilter,
    toggleCheckBox,
    table,
    dataChart,
    loadingDataChart,
    loadingTimeKeeping,
    isLoading,
    chooseMonth,
    infoTable,
    payload,
    setToggleCheckBox,
    showDatePicker,
    hideDatePicker,
    handleConfirm,
    onSubmitFilter,
    setChooseMonth,
    nextPage,
    prevPage,
    lastPage,
    firstPage,
  };
  return <WorkLoadScreen {...shiftProps} />;
};

export default WorkLoadContainer;
