/* eslint-disable prettier/prettier */
/* eslint-disable no-lone-blocks */
/* eslint-disable react-hooks/exhaustive-deps */
import Moment from 'moment';
import React, {useEffect, useState} from 'react';
import {useDispatch, useSelector} from 'react-redux';
import RootNavigation from '../../navigation/RootNavigation';
import {
  getApproveReqVoucherList,
  getMyOverTimeStatistic,
  getUserOTVoucher,
} from '../../store/actions/UserAction';
import {APP_NAVIGATE_SCREEN} from '../../utils/constant';
import OvertimeScreen from './OvertimeScreen';

import OverTimeModalAdd from './modal/OvertimeModalAdd';
import OverTimeModalDetail from './modal/OverTimeModalDetail';
const OvertimeContainer = props => {
  // console.log('props', props);
  const {userDetails} = props;
  const dispatch = useDispatch();
  //Reducers
  const otVoucherUserList = useSelector(state => state.OTVoucher.otVoucher);
  const otApproveReqList = useSelector(
    state => state.OTVoucherPending.otVoucherPending,
  );
  //Chart
  const [chartDataDefault, setChartDataDefault] = useState([]);
  const [month, setMonth] = useState(Moment().month() + 1);
  const [chartData, setChartData] = useState({
    labels: [],
    datasets: [
      {
        data: [],
      },
    ],
  });
  // payload
  const [payloadOtList, setPayloadOtList] = useState({
    filter: '',
    sort: '-created_at',
    page: 1,
    pageSize: 5,
    isRefresh: true,
  });
  const [payloadOtApproveList, setPayloadOtApproveList] = useState({
    type: 'Tất cả',
    filter: '',
    sort: '',
    page: 1,
    pageSize: 5,
    isRefresh: true,
  });

  const [isDisableLoadMore, setDisableLoadMore] = useState({
    approveRequestBtn: false,
    overtimeBtn: false,
  });
  const [totalArr, setTotalArr] = useState({
    totalRequestApproveArr: 0,
    totalOtArr: 0,
  });
  //List OT Voucher
  const [otVoucherList, setOTVoucherList] = useState([]);
  const [otApproveReqVoucherList, setOtApproveReqVoucherList] = useState([]);
  //Others
  const [showAlert, setShowAlert] = useState({
    isShow: false,
    title: '',
    message: '',
  });
  const [modalContent, setModalContent] = useState(null);

  //chart config
  const chartConfig = {
    backgroundGradientFrom: '#FFF',
    backgroundGradientFromOpacity: 1,
    backgroundGradientTo: '#FFF',
    backgroundGradientToOpacity: 0.5,
    color: () => '#ed642d',
    labelColor: () => '#3d3737',
    strokeWidth: 2, // optional, default 3
    barPercentage: 1,
    useShadowColorFromDataset: false, // optional
  };
  const onOpenDetailModal = modalId => {
    setModalContent(
      <OverTimeModalDetail
        onClose={onCloseModal}
        modalDetailId={modalId}
        setShowAlert={setShowAlert}
        setPayloadOtApproveList={setPayloadOtApproveList}
      />,
    );
  };

  const onOpenAddModal = () => {
    setModalContent(
      <OverTimeModalAdd onClose={onCloseModal} setShowAlert={setShowAlert} />,
    );
  };

  const onCloseModal = () => {
    setModalContent(null);
  };
  //API
  const getDataOfBarChart = async () => {
    const res = await dispatch(getMyOverTimeStatistic());
    if (res) {
      const newChartDataDefault = [];
      //console.log('res', res);
      for (const key in res) {
        newChartDataDefault.push({
          month: key,
          value: res[key],
        });
      }
      setChartDataDefault(newChartDataDefault);
    }
  };

  // const getOtPending = async () => {
  //   const res = await dispatch(getMyOTVoucherList());
  //   if (res) {
  //     setOTVoucherList(res);
  //   }
  // };
  const loadOtListFromApi = async () => {
    const res = await dispatch(
      getUserOTVoucher(
        payloadOtList.filter,
        payloadOtList.sort,
        payloadOtList.page,
        payloadOtList.pageSize,
      ),
    );
    if (res.success) {
      //console.log(res);

      const {collection, total} = res.data;
      // check if refresh
      if (!collection || collection.length === 0) {
        return;
      }
      if (payloadOtList.isRefresh) {
        setTotalArr(prev => ({...prev, totalOtArr: total}));
        return;
      }
      setTotalArr(prev => ({...prev, totalOtArr: total}));
    }
  };
  const loadOtApproveListFromApi = async () => {
    //console.log('loadOtApproveListFromApi');
    const res = await dispatch(
      getApproveReqVoucherList(
        payloadOtApproveList.filter,
        payloadOtApproveList.sort,
        payloadOtApproveList.page,
        payloadOtApproveList.pageSize,
      ),
    );
    if (res.success) {
      //console.log(res);

      const {collection, total} = res.data;
      // check if refresh
      if (!collection || collection.length === 0) {
        return;
      }
      if (payloadOtApproveList.isRefresh) {
        setTotalArr(prev => ({...prev, totalRequestApproveArr: total}));
        return;
      }
      setTotalArr(prev => ({...prev, totalRequestApproveArr: total}));
    }
  };
  // load more
  const onLoadMoreOtList = () => {
    setPayloadOtList(prev => ({
      ...prev,
      page: payloadOtList.page + 1,
      isRefresh: false,
    }));
  };
  const onLoadMoreOtApproveReqList = () => {
    setPayloadOtApproveList(prev => ({
      ...prev,
      page: payloadOtApproveList.page + 1,
      isRefresh: false,
    }));
  };

  // refresh onClick event
  const onRefreshOtList = () => {
    //console.log('onRefreshConfirmList');
    setPayloadOtList({
      filter: '',
      sort: '',
      page: 1,
      pageSize: 5,
      isRefresh: true,
    });
  };
  const onRefreshApproveList = () => {
    //console.log('onRefreshConfirmList');
    setPayloadOtApproveList({
      page: 1,
      pageSize: 5,
      isRefresh: true,
    });
  };
  // check visible btn load more
  const checkVisibleLoadMore = () => {
    if (
      otApproveReqVoucherList.length > 0 &&
      otApproveReqVoucherList.length == totalArr.totalRequestApproveArr
    ) {
      //console.log('checkVisibleLoadMore');
      setDisableLoadMore(prev => ({
        ...prev,
        approveRequestBtn: true,
      }));
    } else if (
      otApproveReqVoucherList.length > 0 &&
      otApproveReqVoucherList.length < totalArr.totalRequestApproveArr
    ) {
      //console.log('checkVisibleLoadMore');
      setDisableLoadMore(prev => ({
        ...prev,
        approveRequestBtn: false,
      }));
    } else if (
      otVoucherList.length > 0 &&
      otVoucherList.length == totalArr.totalOtArr
    ) {
      //console.log('checkVisibleLoadMore');
      setDisableLoadMore(prev => ({
        ...prev,
        overtimeBtn: true,
      }));
    } else if (
      otVoucherList.length > 0 &&
      otVoucherList.length < totalArr.totalOtArr
    ) {
      //console.log('checkVisibleLoadMore');
      setDisableLoadMore(prev => ({
        ...prev,
        overtimeBtn: false,
      }));
    }
  };
  //OTHERS
  const handleChartDataByMonth = monthParam => {
    const newChartData = {
      labels: [],
      datasets: [
        {
          data: [],
        },
      ],
    };
    chartDataDefault.forEach(el => {
      if (Moment(el.month).month() === monthParam - 1) {
        newChartData.labels.push(Moment(el.month).format('DD/MM/YYYY'));
        newChartData.datasets[0].data.push(el.value);
      }
    });
    setChartData(newChartData);
  };
  // navigation
  const navigateToConfirmDate = () => {
    RootNavigation.navigate(APP_NAVIGATE_SCREEN.CONFIRM_DATE);
  };
  const navigateToOnLeave = () => {
    RootNavigation.navigate(APP_NAVIGATE_SCREEN.ON_LEAVE);
  };

  const onChangeSelectFilter = selectedItem => {
    if (selectedItem === 'Tất cả') {
      setPayloadOtApproveList({
        type: 'Tất cả',
        filter: '',
        sort: '-created_at',
        page: 1,
        pageSize: 5,
        isRefresh: true,
      });
    } else if (selectedItem === 'Chưa duyệt') {
      setPayloadOtApproveList({
        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') {
      setPayloadOtApproveList({
        type: 'Đã từ chối',
        filter: 'extend_approved_status_name==REJECTED',
        sort: 'created_at',
        page: 1,
        pageSize: 5,
        isRefresh: true,
      });
    } else {
      setPayloadOtApproveList({
        type: 'Đã duyệt',
        filter: 'extend_approved_status_name==APPROVED',
        sort: 'created_at',
        page: 1,
        pageSize: 5,
        isRefresh: true,
      });
    }
  };
  const formatOtListFromApi = () => {
    if (payloadOtList.isRefresh) {
      setOTVoucherList(otVoucherUserList);

      return;
    }
    let merge = [...otVoucherUserList, ...otVoucherList];

    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));
    setOTVoucherList(format);
  };
  const formatOtApproveListFromApi = () => {
    //.log('otApproveReqList', otApproveReqList);
    if (payloadOtApproveList.isRefresh) {
      //console.log('bbb',otApproveReqList)
      setOtApproveReqVoucherList(otApproveReqList);
      return;
    }

    let merge = [...otApproveReqVoucherList, ...otApproveReqList];

    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));
    setOtApproveReqVoucherList(merge);
  };

  //useEffect zone
  useEffect(() => {
    otVoucherUserList && formatOtListFromApi();
  }, [otVoucherUserList]);
  useEffect(() => {
    otApproveReqList && formatOtApproveListFromApi();
  }, [otApproveReqList]);

  useEffect(() => {
    //Close all modal
    getDataOfBarChart();
  }, []);

  useEffect(() => {
    handleChartDataByMonth(month);
  }, [chartDataDefault, month]);

  useEffect(() => {
    payloadOtList && loadOtListFromApi();
  }, [payloadOtList]);
  useEffect(() => {
    payloadOtApproveList && loadOtApproveListFromApi();
  }, [payloadOtApproveList]);

  useEffect(() => {
    checkVisibleLoadMore();
  }, [otVoucherList, otApproveReqVoucherList, totalArr]);

  useEffect(() => {
    if (props?.route?.params) {
      const {refId} = props?.route?.params;
      if (refId) {
        //console.log('refId', refId);
        onOpenDetailModal(refId);
      }
    }
  }, [props?.route?.params]);
  const otProps = {
    userDetails,
    otVoucherList,
    otVoucherUserList,
    chartConfig,
    chartData,
    showAlert,
    isDisableLoadMore,
    otApproveReqVoucherList,
    modalContent,
    payloadOtApproveList,
    onRefreshOtList,
    onLoadMoreOtList,
    setShowAlert,
    setMonth,
    navigateToConfirmDate,
    navigateToOnLeave,
    onLoadMoreOtApproveReqList,
    onRefreshApproveList,
    onOpenAddModal,
    onOpenDetailModal,
    onChangeSelectFilter,
  };
  return <OvertimeScreen {...otProps} />;
};

export default OvertimeContainer;
