import Moment from 'moment';
import React, {useEffect, useState} from 'react';
import {useDispatch, useSelector} from 'react-redux';
import RootNavigation from '../../navigation/RootNavigation';
import {
  getAbsentChart,
  getApproveConfirmDay,
  getUserConfirmDay,
} from '../../store/actions/UserAction';
import {APP_NAVIGATE_SCREEN} from '../../utils/constant';
import ConfirmModalAddNew from './confirm-modals/ConfirmModalAddNew';
import ConfirmModalDetails from './confirm-modals/ConfirmModalDetails';
import ConfirmDateScreen from './ConfirmDateScreen';
const ConfirmDateContainer = props => {
  const dispatch = useDispatch();
  const {userDetails} = props;
  const confirmDay = useSelector(state => state.ConfirmDay.confirmDay);
  const approveConfirmList = useSelector(
    state => state.ApproveDay.approveConfirm,
  );
  const [requestApproveArr, setRequestApproveArr] = useState([]);
  const [confirmList, setConfirmList] = useState([]);
  const [totalArr, setTotalArr] = useState({
    totalRequestApproveArr: 0,
    totalConfirmArr: 0,
  });
  const [showAlert, setShowAlert] = useState({
    isError: false,
    title: '',
    message: '',
  });
  // approveConfirmList payload
  const [approveReqPayload, setApproveReqPayload] = useState({
    type: 'Tất cả',
    filter: '',
    page: 1,
    pageSize: 5,
    sorts: '',
    isRefresh: false,
  });
  // user confirm payload
  const [userConfirmPayload, setUserConfirmPayload] = useState({
    page: 1,
    pageSize: 5,
    isRefresh: false,
  });
  const [isDisableLoadMore, setDisableLoadMore] = useState({
    approveRequestBtn: false,
    confirmBtn: false,
  });
  const [dataChart, setDataChart] = useState({
    month: new Date().getMonth() + 1,
    data: {},
  });
  const [modalContent, setModalContent] = useState(null);

  const [dayPress, setDayPress] = useState();
  // open the modal
  const onOpenDetailModal = detailItem => {
    setModalContent(
      <ConfirmModalDetails
        onClose={onCloseModal}
        alertMessage={alertMessage}
        userDetails={userDetails}
        detailItem={detailItem}
        setApproveReqPayload={setApproveReqPayload}
      />,
    );
  };

  const onOpenAddModal = () => {
    setModalContent(
      <ConfirmModalAddNew
        userDetails={userDetails}
        onClose={onCloseModal}
        alertMessage={alertMessage}
      />,
    );
  };

  const onCloseModal = () => {
    setModalContent(null);
  };
  // main function
  const navigateToDayWage = () => {
    RootNavigation.navigate(APP_NAVIGATE_SCREEN.DAY_WAGE);
  };

  const alertMessage = message => {
    // Toast.show({
    //   type: 'success',
    //   text1: `Thông báo`,
    //   text2: `${message}`,
    //   style: {zIndex: 1001},
    //   visibilityTime: 2000,
    // });
    setShowAlert({
      isError: true,
      title: 'Hệ thống',
      message: message,
    });
  };

  const onHideAlert = () => {
    setShowAlert({
      isError: false,
      title: '',
      message: '',
    });
  };

  const loadDataRequestApprove = async () => {
    const res = await dispatch(
      getApproveConfirmDay(
        approveReqPayload.filter,
        approveReqPayload.sorts,
        approveReqPayload.page,
        approveReqPayload.pageSize,
      ),
    );
    if (res.success) {
      //console.log(res);

      const {collection, total} = res.data;
      // check if refresh
      if (!collection || collection.length === 0) {
        return;
      }
      if (approveReqPayload.isRefresh) {
        setTotalArr(prev => ({...prev, totalRequestApproveArr: total}));
        return;
      }
      setTotalArr(prev => ({...prev, totalRequestApproveArr: total}));
    }
  };
  const loadDataConfirmDay = async () => {
    //console.log('loadDataConfirmDay');
    const res = await dispatch(
      getUserConfirmDay(userConfirmPayload.page, userConfirmPayload.pageSize),
    );
    if (res.success) {
      //console.log(res);
      const {collection, total} = res.data;
      if (!collection || collection.length === 0) {
        return;
      }
      if (userConfirmPayload.isRefresh) {
        setTotalArr(prev => ({...prev, totalConfirmArr: total}));
        return;
      }
      setTotalArr(prev => ({...prev, totalConfirmArr: total}));
    }
  };

  const onLoadMoreRequestApprove = () => {
    setApproveReqPayload(prev => ({
      ...prev,
      page: approveReqPayload.page + 1,
      isRefresh: false,
    }));
  };
  const onLoadMoreConfirmList = () => {
    setUserConfirmPayload(prev => ({
      ...prev,
      page: userConfirmPayload.page + 1,
      isRefresh: false,
    }));
  };
  // check avoid btn load more
  const checkVisibleLoadMore = () => {
    if (
      requestApproveArr.length > 0 &&
      requestApproveArr.length == totalArr.totalRequestApproveArr
    ) {
      //console.log('checkVisibleLoadMore');
      setDisableLoadMore(prev => ({
        ...prev,
        approveRequestBtn: true,
      }));
    } else if (
      requestApproveArr.length > 0 &&
      requestApproveArr.length < totalArr.totalRequestApproveArr
    ) {
      //console.log('checkVisibleLoadMore');
      setDisableLoadMore(prev => ({
        ...prev,
        approveRequestBtn: false,
      }));
    } else if (
      confirmList.length > 0 &&
      confirmList.length == totalArr.totalConfirmArr
    ) {
      //console.log('checkVisibleLoadMore');
      setDisableLoadMore(prev => ({
        ...prev,
        confirmBtn: true,
      }));
    } else if (
      confirmList.length > 0 &&
      confirmList.length == totalArr.totalConfirmArr
    ) {
      //console.log('checkVisibleLoadMore');
      setDisableLoadMore(prev => ({
        ...prev,
        confirmBtn: false,
      }));
    }
  };
  // refresh onClick event
  const onRefreshApproveList = () => {
    //console.log('onRefreshApproveList');
    setApproveReqPayload({
      filter: 'extend_approved_status_name==PENDING',
      page: 1,
      pageSize: 5,
      type: '',
      sorts: '-start',
      isRefresh: true,
    });
  };
  const onRefreshConfirmList = () => {
    //console.log('onRefreshConfirmList');
    setUserConfirmPayload({
      page: 1,
      pageSize: 5,
      isRefresh: true,
    });
  };
  const onChangeSelectFilter = selectedItem => {
    if (selectedItem == 'Tất cả') {
      setApproveReqPayload({
        type: 'Tất cả',
        filter: '',
        sorts: '',
        page: 1,
        pageSize: 5,
        isRefresh: true,
      });
    } else if (selectedItem == 'Chưa duyệt') {
      setApproveReqPayload({
        type: 'Chưa duyệt',
        filter: 'extend_approved_status_name==PENDING',
        sorts: '-start',
        page: 1,
        pageSize: 5,
        isRefresh: true,
      });
    } else if (selectedItem == 'Đã từ chối') {
      setApproveReqPayload({
        type: 'Đã duyệt',
        filter: 'extend_approved_status_name==REJECTED',
        sorts: '-start',
        page: 1,
        pageSize: 5,
        isRefresh: true,
      });
    } else {
      setApproveReqPayload({
        type: 'Đã duyệt',
        filter: 'extend_approved_status_name==APPROVED',
        sorts: '-start',
        page: 1,
        pageSize: 5,
        isRefresh: true,
      });
    }
  };
  const onChangeMonthFilter = selectedItem => {
    const arr = selectedItem.split('Tháng');
    // fetchDataChart(parseInt(arr[1], 10));
    setDataChart(prev => ({
      ...prev,
      month: parseInt(arr[1]) < 10 ? '0' + parseInt(arr[1]) : parseInt(arr[1]),
    }));
  };
  const onChangeDayPressInChart = selectedItem => {
    setDayPress(selectedItem);
  };
  const formatDataConfirmListFromApi = () => {
    if (userConfirmPayload.isRefresh) {
      setConfirmList(confirmDay);
      return;
    }
    let merge = [...confirmList, ...confirmDay];
    //console.log(merge);
    let format = merge.filter(
      (
        set => f =>
          !set.has(f.id) && set.add(f.id)
      )(new Set()),
    );
    format.sort((a, b) => Moment(a.created_at) < Moment(b.created_at));
    setConfirmList(format);
    //setConfirmList(prev => [...prev, ...confirmDay]);
  };
  const formatDataApproveConfirmListFromApi = () => {
    if (approveReqPayload.isRefresh) {
      setRequestApproveArr(approveConfirmList);
      return;
    }
    let merge = [...requestApproveArr, ...approveConfirmList];

    let format = merge.filter(
      (
        set => f =>
          !set.has(f.id) && set.add(f.id)
      )(new Set()),
    );
    format.sort((a, b) => Moment(a.created_at) < Moment(b.created_at));
    setRequestApproveArr(format);
  };
  const fetchDataChart = async month => {
    //console.log('fetchDataChart')
    const res = await dispatch(getAbsentChart());
    if (res && res.length > 0) {
      let filterByMonth = res.filter(
        item => new Date(item.date).getMonth() + 1 === parseInt(month) && item,
      );
      let formatData = [];
      filterByMonth.forEach(item => {
        //console.log(Moment(item.date).format('YYYY-MM-DD'));
        const objDay = Moment(item.date).format('YYYY-MM-DD');
        if (parseInt(item.absent_hours) > 0) {
          formatData.push({
            [objDay]: {
              selected: true,
              selectedColor:
                (parseInt(item.absent_hours) > 8 && '#7d93ff') ||
                (parseInt(item.absent_hours) >= 6 &&
                  parseInt(item.absent_hours) <= 8 &&
                  '#7d93ff') ||
                (parseInt(item.absent_hours) >= 4 &&
                  parseInt(item.absent_hours) <= 6 &&
                  '#7d93ff') ||
                '#dfe4ff',
            },
          });
        }
      });

      // const monthArr = filterByMonth.filter(
      //   item => item.absent_hours > 0 && item,
      //   //console.log((item.date = Moment(item.date).format('dddd')));
      // );
      //console.log('month', month);
      const convertObj = Object.assign({}, ...formatData);
      //console.log('filterByMonth', ...formatData);
      setDataChart(prev => ({
        ...prev,
        data: filterByMonth,
      }));
    }
  };
  const minutesToHours = (start, finish) => {
    //console.log(start, finish);
    let time = Moment(finish).diff(Moment(start), 'minutes');
    var Hours = Math.floor(time / 60);
    var minutes = time % 60;
    return `${Hours}:${minutes} giờ`;
  };
  // useEffect
  {
    /*load init data*/
  }
  useEffect(() => {
    confirmDay && formatDataConfirmListFromApi();
  }, [confirmDay]);

  useEffect(() => {
    dataChart.month && fetchDataChart(dataChart.month);
  }, [dataChart.month]);

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

  useEffect(() => {
    approveConfirmList &&
      formatDataApproveConfirmListFromApi(approveConfirmList);
  }, [approveConfirmList]);

  useEffect(() => {
    approveReqPayload && loadDataRequestApprove();
  }, [approveReqPayload]);
  useEffect(() => {
    userConfirmPayload && loadDataConfirmDay();
  }, [userConfirmPayload]);
  useEffect(() => {
    checkVisibleLoadMore();
  }, [requestApproveArr, confirmList, totalArr]);

  const confirmProps = {
    approveConfirmList,
    userDetails,
    showAlert,
    requestApproveArr,
    confirmList,
    isDisableLoadMore,
    dataChart,
    modalContent,
    approveReqPayload,
    dayPress,
    onChangeDayPressInChart,
    onOpenDetailModal,
    onOpenAddModal,
    onLoadMoreConfirmList,
    onHideAlert,
    navigateToDayWage,
    alertMessage,
    onLoadMoreRequestApprove,
    onRefreshApproveList,
    onRefreshConfirmList,
    onChangeSelectFilter,
    onChangeMonthFilter,
    minutesToHours,
  };
  return <ConfirmDateScreen {...confirmProps} />;
};

export default ConfirmDateContainer;
