/* eslint-disable react-hooks/exhaustive-deps */

import Moment from 'moment';
import React, {useCallback, 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 './template/subViews/RequestLeavesDays';
import OnLeaveModalDetail from './modals/OnLeaveModalDetails';
import {
  getUserLeavesDay,
  getApproveRequestLeavesDays,
  getUserRestDay,
  getLeaveCategory,
  getDirectManagers,
  handleSelectManagersLeaveRequest,
  postLeaveRequest,
  postSubmitApproveLeaveRequest,
} from './onLeaveSlice';
import OnLeaveMainView from './template/OnLeaveMainView';
import onLeavePropsProvider from './onLeavePropsProvider';
import {launchImageLibrary} from 'react-native-image-picker';
import {ToastMessage} from '../../utils/MessageUtil';
import moment from 'moment';
import Utils from '../../utils';

const initPayloadApprove = {
  type: 'Tất cả',
  filter: '',
  sort: '',
  page: 1,
  pageSize: 5,
  isRefresh: false,
};

const OnLeaveContainer = props => {
  const {
    usersLeavesDayList,
    userRestDayList,
    userInfo,
    approveRequestLeavesDaysList,
    leaveCategory,
    directManagersList,
  } = props;

  const dispatch = useDispatch();
  const [dataChart, setDataChart] = useState();

  // get api with payload
  const [payloadApproveRequestLeavesDays, setPayloadApproveRequestLeavesDays] =
    useState(initPayloadApprove);
  const [payloadLeaves, setPayloadLeaves] = useState(initPayloadApprove);

  const [leaveRequestList, setLeaveRequestList] = useState([]);

  const [isDisableLoadMore, setDisableLoadMore] = useState({
    approveReqBtn: false,
    leaveBtn: false,
  });

  const [leavesDaysModal, setLeavesDaysModal] = useState({
    visible: false,
    userInfo: null,
    isRequest: false,
  });

  const [openTimePicker, setOpenTimePicker] = useState({
    startDate: false,
    finishDate: false,
    startTime: false,
    finishTime: false,
  });
  const [timeRequestLeave, setTimeRequestLeave] = useState({
    startDate: new Date(),
    finishDate: new Date(),
    startTime: new Date(),
    finishTime: new Date(),
  });

  const [leaveRequestImage, setLeaveRequestImage] = useState([]);
  const [leaveRequestTicket, setLeaveRequestTicket] = useState({
    leaveCategory: '',
    reason: '',
  });
  // open the modal
  const onOpenDetailModal = useCallback(
    detail => {
      if (detail) {
        const user = {
          id: detail?.staff_id,
          avatar: detail?.extend_creator_avatar,
          full_name: detail?.extend_creator_full_name,
          employee_code: detail?.extend_creator_employee_code,
          position: detail?.extend_creator_position,
          isApprover: detail?.approver_id === userInfo?.id,
          leave_id: detail?.id,
        };
        setLeaveRequestTicket({
          leaveCategory: detail?.extend_category_name,
          reason: detail?.reason,
        });
        setLeavesDaysModal({
          visible: true,
          userInfo: user,
          isRequest: false,
        });
      }
    },
    [userInfo],
  );

  const onOpenRequestLeavesModal = userDetails => {
    setLeavesDaysModal({
      visible: true,
      userInfo: userInfo,
      isRequest: true,
    });
  };

  const onCloseModal = () => {
    setLeavesDaysModal({
      visible: false,
      userInfo: null,
      isRequest: false,
    });
  };
  const formatDataChart = () => {
    // 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 onLoadMoreLeavesTicket = () => {
    setPayloadLeaves(prev => ({
      ...prev,
      page: payloadLeaves.page + 1,
      isRefresh: false,
    }));
  };
  const onLoadMoreLeavesApproveReqTicket = () => {
    setPayloadApproveRequestLeavesDays(prev => ({
      ...prev,
      page: payloadApproveRequestLeavesDays.page + 1,
      isRefresh: false,
    }));
  };
  // refresh onClick event
  const onRefreshLeaveList = () => {
    setPayloadLeaves({
      filter: '',
      sort: '',
      page: 1,
      pageSize: 5,
      isRefresh: true,
    });
    setDisableLoadMore(prev => ({
      ...prev,
      leaveBtn: false,
    }));
  };
  const onRefreshLeaveApproveReqList = () => {
    setPayloadApproveRequestLeavesDays({
      filter: '',
      sort: '',
      page: 1,
      pageSize: 5,
      isRefresh: true,
    });
    setDisableLoadMore(prev => ({
      ...prev,
      approveReqBtn: false,
    }));
  };

  const onChangeSelectFilter = selectedItem => {
    if (selectedItem === 'Tất cả') {
      setPayloadApproveRequestLeavesDays({
        type: 'Tất cả',
        filter: '',
        sort: '',
        page: 1,
        pageSize: 5,
        isRefresh: true,
      });
    } else if (selectedItem === 'Chưa duyệt') {
      setPayloadApproveRequestLeavesDays({
        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') {
      setPayloadApproveRequestLeavesDays({
        type: 'Đã từ chối',
        filter: 'extend_approved_status_name==REJECTED',
        sort: 'created_at',
        page: 1,
        pageSize: 5,
        isRefresh: true,
      });
    } else {
      setPayloadApproveRequestLeavesDays({
        type: 'Đã duyệt',
        filter: 'extend_approved_status_name==APPROVED',
        sort: 'created_at',
        page: 1,
        pageSize: 5,
        isRefresh: true,
      });
    }
  };
  const formatLeaveLstFromApi = () => {
    if (payloadLeaves.isRefresh) {
      setLeaveRequestList(usersLeavesDayList);
      return;
    }
    let merge = [...usersLeavesDayList, ...leaveRequestList];

    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));
    setLeaveRequestList([...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);
    }
  };

  // fetch data
  const fetchLeavesTicket = () => {
    dispatch(
      getUserLeavesDay({
        filter: payloadLeaves.filter,
        sort: payloadLeaves.sort,
        page: payloadLeaves.page,
        pageSize: payloadLeaves.pageSize,
      }),
    );
  };
  const fetchApproveRequestLeavesDays = () => {
    dispatch(
      getApproveRequestLeavesDays({
        filter: payloadApproveRequestLeavesDays.filter,
        sort: payloadApproveRequestLeavesDays.sort,
        page: payloadApproveRequestLeavesDays.page,
        pageSize: payloadApproveRequestLeavesDays.pageSize,
      }),
    );
  };
  const fetchLeavesRestDays = () => {
    dispatch(getUserRestDay());
  };
  const fetchLeaveCategory = () => {
    dispatch(getLeaveCategory());
  };
  const fetchDirectManagers = () => {
    dispatch(getDirectManagers());
  };
  //============================== ADD NEW LEAVES =============================//
  const openGallery = () => {
    launchImageLibrary(
      {
        mediaType: 'photo',
        includeBase64: true,
      },
      response => {
        if (!response.didCancel) {
          //console.log('AAA');
          const {assets} = response;
          setLeaveRequestImage(prev => [...prev, ...assets]);
          //console.log(response.assets[0].uri)
        }
      },
    );
  };
  const onDeleteLeaveRequestImage = index => {
    const clone = [...leaveRequestImage];
    clone.splice(index, 1);
    setLeaveRequestImage([...clone]);
  };

  const onSubmitLeaveRequest = () => {
    if (handleSubmitLeaveRequest()) {
      const selectLeaveCategory = leaveCategory.filter(item =>
        item.name === leaveRequestTicket.leaveCategory.length
          ? leaveRequestTicket.leaveCategory
          : leaveCategory[0].name,
      );
      const approver = directManagersList.filter(item => item.isChecked);
      const payload = {
        start: timeRequestLeave.startDate,
        finish: timeRequestLeave.finishDate,
        leave_category_id:
          selectLeaveCategory.length > 0 ? selectLeaveCategory[0].id : null,
        approver_id: approver.length > 0 ? approver[0].id : null,
        reason: leaveRequestTicket.reason,
      };
      dispatch(postLeaveRequest(payload)).then(response => {
        const {success, message} = Utils.getValues(response, 'payload', false);
        ToastMessage({
          title: 'Hệ thống',
          message: success ? 'Đã gửi yêu cầu nghỉ phép thành công' : message,
          type: success ? 'success' : 'error',
        });
        onCloseModal();
      });
    }
  };
  const handleSubmitLeaveRequest = () => {
    if (directManagersList?.length === 0) {
      return false;
    }
    const isSelectedManager = directManagersList.filter(item => item.isChecked);
    if (leaveRequestTicket.reason.length === 0) {
      ToastMessage({
        title: 'Hệ thống',
        message: 'Vui lòng nhập lý do nghỉ',
        type: 'error',
      });
      return false;
    } else if (
      moment(timeRequestLeave.startDate) > moment(timeRequestLeave.finishDate)
    ) {
      ToastMessage({
        title: 'Hệ thống',
        message: 'Vui lòng chọn ngày bắt đầu nghỉ nhỏ hơn ngày kết thúc',
        type: 'error',
        timeVisible: 5000,
      });
      return false;
    } else if (
      moment(timeRequestLeave.startTime) > moment(timeRequestLeave.finishTime)
    ) {
      ToastMessage({
        title: 'Hệ thống',
        message: 'Vui lòng chọn giờ bắt đầu nghỉ nhỏ hơn giờ kết thúc',
        type: 'error',
        timeVisible: 5000,
      });
      return false;
    } else if (isSelectedManager.length === 0) {
      ToastMessage({
        title: 'Hệ thống',
        message: 'Vui lòng chọn người duyệt!!!',
        type: 'error',
        timeVisible: 5000,
      });
      return false;
    } else {
      return true;
    }
  };
  const onSelectManagerLeaveRequest = (index, value) => {
    dispatch(handleSelectManagersLeaveRequest({index, value}));
  };
  const onSubmitApproveLeaveRequest = leave_id => {
    try {
      dispatch(postSubmitApproveLeaveRequest({id: leave_id})).then(response => {
        const {success} = Utils.getValues(response, 'payload', false);
        if (success) {
          fetchApproveRequestLeavesDays();
          onCloseModal();
        }
        ToastMessage({
          title: 'Hệ thống',
          message: `Duyệt nghỉ phép ${success ? 'thành công' : 'thất bại'}`,
          type: success ? 'success' : 'error',
        });
      });
    } catch (err) {
      ToastMessage({
        title: 'Hệ thống',
        message: 'Đã có lỗi xảy ra !!!',
        type: 'error',
      });
    }
  };

  // useEffect
  useEffect(() => {
    usersLeavesDayList && formatLeaveLstFromApi();
  }, [usersLeavesDayList]);

  useEffect(() => {
    fetchLeavesRestDays();
    fetchLeaveCategory();
    fetchDirectManagers();
  }, []);

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

  useEffect(() => {
    payloadLeaves && fetchLeavesTicket();
  }, [payloadLeaves]);
  useEffect(() => {
    payloadApproveRequestLeavesDays && fetchApproveRequestLeavesDays();
  }, [payloadApproveRequestLeavesDays]);

  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,
    userInfo,
    dataChart,
    isDisableLoadMore,
    leaveRequestList,
    payloadApproveRequestLeavesDays,
    approveRequestLeavesDaysList,
    leavesDaysModal,
    leaveCategory,
    directManagersList,
    openTimePicker,
    timeRequestLeave,
    leaveRequestImage,
    leaveRequestTicket,
    setLeaveRequestTicket,
    openGallery,
    onDeleteLeaveRequestImage,
    setLeaveRequestImage,
    setTimeRequestLeave,
    setOpenTimePicker,
    onLoadMoreLeavesApproveReqTicket,
    onRefreshLeaveList,
    onRefreshLeaveApproveReqList,
    navigateToConfirmDate,
    navigateToOverTime,
    onLoadMoreLeavesTicket,
    onOpenDetailModal,
    onOpenRequestLeavesModal,
    onCloseModal,
    onChangeSelectFilter,
    minutesToHours,
    onSubmitLeaveRequest,
    onSelectManagerLeaveRequest,
    onSubmitApproveLeaveRequest,
  };
  return <OnLeaveMainView {...onLeavePropsProvider(leaveProps)} />;
};

export default OnLeaveContainer;
