/* eslint-disable prettier/prettier */
import Moment from 'moment';
import React, {useEffect, useState} from 'react';
import {useDispatch} from 'react-redux';
import RootNavigation from '../../navigation/RootNavigation';
import {
  getUserLeaveDayApproveReq,
  getUserLeavesById,
} from '../../store/actions/UserAction';
import {APP_NAVIGATE_SCREEN} from '../../utils/constant';

import OnLeaveModalAddNew from './modals/OnLeaveModalAddNew';
import OnLeaveModalDetail from './modals/OnLeaveModalDetails';
import {getUserLeavesDay} from './onLeaveSlice';
import OnLeaveMainView from './template/OnLeaveMainView';

const OnLeaveContainer = props => {
  const {usersLeavesDayList, userRestDayList, userDetails} = props;
  const dispatch = useDispatch();
  // const userLeaveDaysPending = useSelector(
  //   state => state.UserLeavesPending.userLeavesPending,
  // );

  const [dataChart, setDataChart] = useState();
  const initPayloadApprove = {
    type: 'Tất cả',
    filter: '',
    sort: '',
    page: 1,
    pageSize: 5,
    isRefresh: false,
  };
  // get api with payload
  const [payloadApproveLeaves, setPayloadApproveLeaves] =
    useState(initPayloadApprove);
  const [payloadLeaves, setPayloadLeaves] = useState(initPayloadApprove);

  const [leaveList, setLeaveList] = useState([]);
  const [leaveApproveReqList, setLeaveApproveReqList] = useState([]);

  const [showAlert, setShowAlert] = useState({
    isError: false,
    title: '',
    message: '',
  });

  const [totalArr, setTotalArr] = useState({
    totalApproveReqLeaves: 0,
    totalLeaveList: 0,
  });
  const [isDisableLoadMore, setDisableLoadMore] = useState({
    approveReqBtn: false,
    leaveBtn: false,
  });

  const [modalContent, setModalContent] = useState(null);

  // open the modal
  const onOpenDetailModal = detailItem => {
    setModalContent(
      <OnLeaveModalDetail
        onClose={onCloseModal}
        alertMessage={alertMessage}
        userDetails={userDetails}
        detailItem={detailItem}
        setPayloadApproveLeaves={setPayloadApproveLeaves}
      />,
    );
  };

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

  const onCloseModal = () => {
    setModalContent(null);
  };
  const loadDataChart = () => {
    // console.log('userRestDays', userRestDays);
    if (userRestDayList.length > 0) {
      let arrDataChart = [];
      userRestDayList.map((item, index) => {
        arrDataChart.push({
          name: item.name,
          from: Number(parseFloat(item.take_days).toFixed(1)),
          to: Number(parseFloat(item.rest_days).toFixed(1)),
        });
      });
      //console.log('arrDataChart', arrDataChart);
      setDataChart(arrDataChart);
    }
  };

  const navigateToConfirmDate = () => {
    RootNavigation.navigate(APP_NAVIGATE_SCREEN.CONFIRM_DATE);
  };
  const navigateToOverTime = () => {
    RootNavigation.navigate(APP_NAVIGATE_SCREEN.OVERTIME);
  };

  const alertMessage = message => {
    setShowAlert({
      isError: true,
      title: 'Thông báo',
      message: `${message} 👍`,
    });
  };
  const onHideAlert = () => {
    setShowAlert({
      isError: false,
      title: '',
      message: '',
    });
  };

  const onLoadMoreLeavesTicket = () => {
    setPayloadLeaves(prev => ({
      ...prev,
      page: payloadLeaves.page + 1,
      isRefresh: false,
    }));
  };
  const onLoadMoreLeavesApproveReqTicket = () => {
    setPayloadApproveLeaves(prev => ({
      ...prev,
      page: payloadApproveLeaves.page + 1,
      isRefresh: false,
    }));
  };

  const checkVisibleLoadMore = () => {
    // console.log(
    //   leaveApproveReqList.length == totalArr.totalApproveReqLeaves,
    //   leaveApproveReqList.length,
    //   totalArr.totalApproveReqLeaves,
    // );
    if (
      leaveApproveReqList.length > 0 &&
      leaveApproveReqList.length == totalArr.totalApproveReqLeaves
    ) {
      setDisableLoadMore(prev => ({
        ...prev,
        approveReqBtn: true,
      }));
    } else if (
      leaveApproveReqList.length > 0 &&
      leaveApproveReqList.length < totalArr.totalApproveReqLeaves
    ) {
      setDisableLoadMore(prev => ({
        ...prev,
        approveReqBtn: false,
      }));
    } else if (
      leaveList.length > 0 &&
      leaveList.length == totalArr.totalLeaveList
    ) {
      //.log('checkVisibleLoadMore');
      setDisableLoadMore(prev => ({
        ...prev,
        leaveBtn: true,
      }));
    } else if (
      leaveList.length > 0 &&
      leaveList.length < totalArr.totalLeaveList
    ) {
      //.log('checkVisibleLoadMore');
      setDisableLoadMore(prev => ({
        ...prev,
        leaveBtn: false,
      }));
    }
  };
  const loadLeavesTicketsFromApi = async () => {
    const response = await dispatch(
      getUserLeavesDay({
        filter: payloadLeaves.filter,
        sort: payloadLeaves.sort,
        page: payloadLeaves.page,
        pageSize: payloadLeaves.pageSize,
      }),
    );
    if (response.success) {
      const {collection, total} = response.data;
      if (!collection || collection.length === 0) {
        return;
      }
      //console.log('loadLeavesTicketsFromApi', collection);
      if (payloadLeaves.isRefresh) {
        setTotalArr(prev => ({...prev, totalLeaveList: total}));
        return;
      }

      setTotalArr(prev => ({...prev, totalLeaveList: total}));
    }
  };
  const loadLeavesApproveReqTicketsFromApi = async () => {
    const response = await dispatch(
      getUserLeaveDayApproveReq(
        payloadApproveLeaves.filter,
        payloadApproveLeaves.sort,
        payloadApproveLeaves.page,
        payloadApproveLeaves.pageSize,
      ),
    );
    if (response.success) {
      const {collection, total} = response.data;
      if (!collection || collection.length === 0) {
        return;
      }
      //console.log('loadLeavesApproveReqTicketsFromApi', collection);
      if (payloadApproveLeaves.isRefresh) {
        setTotalArr(prev => ({...prev, totalApproveReqLeaves: total}));
        return;
      }

      setTotalArr(prev => ({...prev, totalApproveReqLeaves: total}));
    }
  };
  // refresh onClick event
  const onRefreshLeaveList = () => {
    setPayloadLeaves({
      filter: '',
      sort: '',
      page: 1,
      pageSize: 5,
      isRefresh: true,
    });
    setDisableLoadMore(prev => ({
      ...prev,
      leaveBtn: false,
    }));
  };
  const onRefreshLeaveApproveReqList = () => {
    setPayloadApproveLeaves({
      filter: '',
      sort: '',
      page: 1,
      pageSize: 5,
      isRefresh: true,
    });
    setDisableLoadMore(prev => ({
      ...prev,
      approveReqBtn: false,
    }));
  };

  const onChangeSelectFilter = selectedItem => {
    if (selectedItem == 'Tất cả') {
      setPayloadApproveLeaves({
        type: 'Tất cả',
        filter: '',
        sort: '',
        page: 1,
        pageSize: 5,
        isRefresh: true,
      });
    } else if (selectedItem == 'Chưa duyệt') {
      setPayloadApproveLeaves({
        type: 'Chưa duyệt',
        filter: 'extend_approved_status_name==PENDING',
        sort: 'created_at',
        page: 1,
        pageSize: 5,
        isRefresh: true,
      });
    } else if (selectedItem == 'Đã từ chối') {
      setPayloadApproveLeaves({
        type: 'Đã từ chối',
        filter: 'extend_approved_status_name==REJECTED',
        sort: 'created_at',
        page: 1,
        pageSize: 5,
        isRefresh: true,
      });
    } else {
      setPayloadApproveLeaves({
        type: 'Đã duyệt',
        filter: 'extend_approved_status_name==APPROVED',
        sort: 'created_at',
        page: 1,
        pageSize: 5,
        isRefresh: true,
      });
    }
  };
  const formatLeaveLstFromApi = () => {
    if (payloadLeaves.isRefresh) {
      setLeaveList(usersLeavesDayList);
      return;
    }
    let merge = [...usersLeavesDayList, ...leaveList];

    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));
    setLeaveList(format);
  };
  // const formatLeaveApproveLstFromApi = () => {
  //   //console.log('formatLeaveApproveLstFromApi');
  //   if (payloadApproveLeaves.isRefresh) {
  //     setLeaveApproveReqList(userLeaveDaysPending);

  //     return;
  //   }
  //   let merge = [...leaveApproveReqList, ...userLeaveDaysPending];

  //   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));
  //   setLeaveApproveReqList(format);
  // };

  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ờ`;
  };

  const getAndOpenModal = async id => {
    const res = await dispatch(getUserLeavesById(id));
    if (res) {
      onOpenDetailModal(res);
    }
  };

  const fetchLeavesTicket = () => {
    dispatch(
      getUserLeavesDay({
        filter: payloadLeaves.filter,
        sort: payloadLeaves.sort,
        page: payloadLeaves.page,
        pageSize: payloadLeaves.pageSize,
      }),
    );
  };
  const fetchRestDay = () => {
    dispatch(
      getUserLeaveDayApproveReq(
        payloadApproveLeaves.filter,
        payloadApproveLeaves.sort,
        payloadApproveLeaves.page,
        payloadApproveLeaves.pageSize,
      ),
    );
  };
  // useEffect
  useEffect(() => {
    usersLeavesDayList && formatLeaveLstFromApi();
  }, [usersLeavesDayList]);
  // useEffect(() => {
  //   userLeaveDaysPending && formatLeaveApproveLstFromApi();
  // }, [userLeaveDaysPending]);

  useEffect(() => {
    usersLeavesDayList && userRestDayList && loadDataChart();
  }, [usersLeavesDayList, userRestDayList]);

  useEffect(() => {
    payloadLeaves && fetchLeavesTicket();
  }, [payloadLeaves]);
  useEffect(() => {
    payloadApproveLeaves && fetchRestDay();
  }, [payloadApproveLeaves]);

  useEffect(() => {
    checkVisibleLoadMore();
  }, [leaveList, leaveApproveReqList, totalArr]);

  useEffect(() => {
    if (props?.route?.params) {
      const {refId} = props?.route?.params;
      if (refId) {
        //console.log('refId', refId);
        getAndOpenModal(refId);
      }
    }
  }, [props?.route?.params]);
  // props
  const leaveProps = {
    usersLeavesDayList,
    userDetails,
    dataChart,
    showAlert,
    totalArr,
    isDisableLoadMore,
    leaveList,
    leaveApproveReqList,
    modalContent,
    payloadApproveLeaves,
    onLoadMoreLeavesApproveReqTicket,
    onRefreshLeaveList,
    onRefreshLeaveApproveReqList,
    navigateToConfirmDate,
    navigateToOverTime,
    alertMessage,
    onHideAlert,
    onLoadMoreLeavesTicket,
    onOpenDetailModal,
    onOpenAddModal,
    onCloseModal,
    onChangeSelectFilter,
    minutesToHours,
  };
  return <OnLeaveMainView {...leaveProps} />;
};

export default OnLeaveContainer;
