import Moment from 'moment';
import React, {useCallback, useEffect, useState} from 'react';
import {useDispatch} from 'react-redux';
import RootNavigation from '../../navigation/RootNavigation';
import {APP_NAVIGATE_SCREEN} from '../../utils/constant';
import ConfirmModalAddNew from './confirm-modals/ConfirmModalAddNew';
import ConfirmModalDetails from './confirm-modals/ConfirmModalDetails';
import {
  getAbsentChart,
  getConfirmApprovedDate,
  getMyAbsentRequests,
  getUserConfirmDay,
  handleSelectManagersConfirmWorkingDayRequest,
  postConfirmWorkingDay,
  postSubmitApproveConfirmWorkingDayRequest,
} from './confirmDateSlice';
import ConfirmDateMainView from './template/ConfirmMainView';
import confirmDatePropsProvider from './confirmDatePropsProvider';
import Utils from '../../utils';
import {launchImageLibrary} from 'react-native-image-picker';
import {handleSelectManagersLeaveRequest} from '../onleave/onLeaveSlice';
import {ToastMessage} from '../../utils/MessageUtil';
import moment from 'moment';
const ConfirmDateContainer = props => {
  const {
    confirmDateList,
    confirmApprovedDateList,
    userInfo,
    directManagersList,
    myAbsentRequests,
  } = props;
  const dispatch = useDispatch();

  const [requestApproveArr, setRequestApproveArr] = useState([]);
  const [confirmList, setConfirmList] = useState([]);
  const [totalArr, setTotalArr] = useState({
    totalRequestApproveArr: 0,
    totalConfirmArr: 0,
  });

  // 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 [dataChart, setDataChart] = useState({
    month: new Date().getMonth() + 1,
    data: {},
  });
  const [modalRequestConfirmWorkingDays, setModalRequestConfirmWorkingDays] =
    useState({
      visible: false,
      userInfo: null,
      isRequest: false,
    });

  const [dayPress, setDayPress] = useState();

  const [openTimePicker, setOpenTimePicker] = useState({
    startDate: false,
    finishDate: false,
    startTime: false,
    finishTime: false,
  });
  const [confirmDateRequestImage, setConfirmDateRequestImage] = useState([]);
  const [confirmDateRequestTicket, setConfirmDateRequestTicket] = useState({
    startDate: new Date(),
    finishDate: new Date(),
    reason: '',
  });

  // open the modal
  const onOpenModalRequestConfirmWorkingDays = userDetails => {
    const user = {
      id: userDetails?.staff_id,
      avatar: userDetails?.extend_creator_avatar,
      full_name: userDetails?.extend_creator_full_name,
      employee_code: userDetails?.extend_creator_employee_code,
      position: userDetails?.extend_creator_position,
      isApprover: userDetails?.approver_id === userInfo?.id,
      confirmStatus: userDetails?.extend_approved_status_name !== 'APPROVED',
      confirm_working_id: userDetails?.id,
    };
    setModalRequestConfirmWorkingDays({
      userInfo: userDetails ? user : userInfo,
      visible: true,
      isRequest: !userDetails ? true : false,
    });
    if (userDetails) {
      setConfirmDateRequestTicket({
        startDate: new Date(userDetails?.start),
        finishDate: new Date(userDetails?.finish),
        reason: userDetails?.reason,
      });
    }
  };

  const onCloseModalRequestConfirmWorkingDays = () => {
    setModalRequestConfirmWorkingDays({
      userInfo: null,
      visible: false,
      isRequest: false,
    });
  };

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

  const onLoadMoreRequestApprove = () => {
    setApproveReqPayload(prev => ({
      ...prev,
      page: approveReqPayload.page + 1,
      isRefresh: false,
    }));
  };
  const onLoadMoreConfirmList = () => {
    setUserConfirmPayload(prev => ({
      ...prev,
      page: userConfirmPayload.page + 1,
      isRefresh: 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) < 10
          ? '0' + parseInt(arr[1], 10)
          : parseInt(arr[1], 10),
    }));
  };
  const onChangeDayPressInChart = selectedItem => {
    setDayPress(selectedItem);
  };
  const formatDataConfirmListFromApi = () => {
    if (userConfirmPayload.isRefresh) {
      setConfirmList(confirmDateList);
      return;
    }
    let merge = [...confirmList, ...confirmDateList];
    //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(confirmApprovedDateList);
      return;
    }
    let merge = [...requestApproveArr, ...confirmApprovedDateList];

    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);
  };

  //=============================== FETCH DATA ================================//
  const fetchAbsentApprovalRequests = async () => {
    const res = await dispatch(
      getConfirmApprovedDate({
        filter: approveReqPayload.filter,
        sort: approveReqPayload.sorts,
        page: approveReqPayload.page,
        pageSize: 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 fetchStatisticsConfirmWorkingDays = useCallback(() => {
    dispatch(getAbsentChart()).then(response => {
      const {success} = Utils.getValues(response, 'payload', false);
      if (success) {
        const {data} = Utils.getValues(response, 'payload', []);
        let filterByMonth =
          data.length > 0
            ? data.filter(
                item =>
                  new Date(item.date).getMonth() + 1 ===
                  parseInt(dataChart.month, 10),
              )
            : [];
        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, 10) > 0) {
            formatData.push({
              [objDay]: {
                selected: true,
                selectedColor:
                  (parseInt(item.absent_hours, 10) > 8 && '#7d93ff') ||
                  (parseInt(item.absent_hours, 10) >= 6 &&
                    parseInt(item.absent_hours, 10) <= 8 &&
                    '#7d93ff') ||
                  (parseInt(item.absent_hours, 10) >= 4 &&
                    parseInt(item.absent_hours, 10) <= 6 &&
                    '#7d93ff') ||
                  '#dfe4ff',
              },
            });
          }
        });
        setDataChart(prev => ({
          ...prev,
          data: filterByMonth,
        }));
      }
    });
  }, [dataChart.month, dispatch]);
  const fetchMyAbsentRequests = () => {
    dispatch(getMyAbsentRequests({page: 1, pageSize: 5}));
  };
  //============================= REQUEST CONFIRM WORKING DAYS =============================//
  const openGallery = () => {
    launchImageLibrary(
      {
        mediaType: 'photo',
        includeBase64: true,
      },
      response => {
        if (!response.didCancel) {
          //console.log('AAA');
          const {assets} = response;
          setConfirmDateRequestImage(prev => [...prev, ...assets]);
          //console.log(response.assets[0].uri)
        }
      },
    );
  };
  const onDeleteConfirmDateRequestImage = index => {
    const clone = [...confirmDateRequestImage];
    clone.splice(index, 1);
    setConfirmDateRequestImage([...clone]);
  };
  const onSelectManagerConfirmWorkingDayRequest = (index, value) => {
    dispatch(handleSelectManagersLeaveRequest({index, value}));
  };
  const onSubmitConfirmWorkingDayRequest = () => {
    if (handleSubmitConfirmWorkingDayRequest()) {
      const approver = directManagersList.filter(item => item.isChecked);
      const payload = {
        start: confirmDateRequestTicket.startDate,
        finish: confirmDateRequestTicket.finishDate,
        approver_id: approver.length > 0 ? approver[0].id : null,
        reason: confirmDateRequestTicket.reason,
        timeStart: moment(confirmDateRequestTicket.startDate).format('HH:mm'),
        timeFinish: moment(confirmDateRequestTicket.finishDate).format('HH:mm'),
      };
      dispatch(postConfirmWorkingDay(payload)).then(response => {
        const {success} = Utils.getValues(response, 'payload', false);
        success && fetchAbsentApprovalRequests();
        ToastMessage({
          title: 'Hệ thống',
          message: `Đã gửi yêu cầu xác nhận ${
            success ? 'thành công' : 'thất bại'
          }`,
          type: success ? 'success' : 'error',
        });
        onCloseModalRequestConfirmWorkingDays();
      });
    }
  };
  const handleSubmitConfirmWorkingDayRequest = () => {
    if (directManagersList?.length === 0) {
      ToastMessage({
        title: 'Hệ thống',
        message: 'Bạn đã là cấp trên không thể gửi yêu cầu !!!',
        type: 'error',
      });
      return false;
    }
    const isSelectedManager = directManagersList.filter(item => item.isChecked);
    if (confirmDateRequestTicket.reason.length === 0) {
      ToastMessage({
        title: 'Hệ thống',
        message: 'Vui lòng nhập lý do',
        type: 'error',
      });
      return false;
    } else if (
      moment(confirmDateRequestTicket.startDate) >
      moment(confirmDateRequestTicket.finishDate)
    ) {
      ToastMessage({
        title: 'Hệ thống',
        message: 'Vui lòng chọn ngày bắt đầu nhỏ hơn ngày 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 onSubmitApproveConfirmWorkingDaysRequest = confirm_working_id => {
    try {
      dispatch(
        postSubmitApproveConfirmWorkingDayRequest({id: confirm_working_id}),
      ).then(response => {
        const {success} = Utils.getValues(response, 'payload', false);
        if (success) {
          fetchAbsentApprovalRequests();
          onCloseModalRequestConfirmWorkingDays();
        }
        ToastMessage({
          title: 'Hệ thống',
          message: `Duyệt xác nhận ngày công ${
            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(() => {
    fetchMyAbsentRequests();
  }, []);

  useEffect(() => {
    confirmDateList && formatDataConfirmListFromApi();
  }, [confirmDateList]);

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

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

  useEffect(() => {
    approveReqPayload && fetchAbsentApprovalRequests();
  }, [approveReqPayload]);

  useEffect(() => {
    userConfirmPayload && loadDataConfirmDay();
  }, [userConfirmPayload]);

  const confirmProps = {
    userInfo,
    requestApproveArr,
    confirmList,
    dataChart,
    approveReqPayload,
    dayPress,
    modalRequestConfirmWorkingDays,
    confirmDateRequestImage,
    confirmDateRequestTicket,
    openTimePicker,
    directManagersList,
    myAbsentRequests,
    setOpenTimePicker,
    setConfirmDateRequestTicket,
    openGallery,
    onChangeDayPressInChart,
    onLoadMoreConfirmList,
    navigateToDayWage,
    onLoadMoreRequestApprove,
    onRefreshApproveList,
    onRefreshConfirmList,
    onChangeSelectFilter,
    onChangeMonthFilter,
    onCloseModalRequestConfirmWorkingDays,
    onOpenModalRequestConfirmWorkingDays,
    onDeleteConfirmDateRequestImage,
    onSelectManagerConfirmWorkingDayRequest,
    onSubmitConfirmWorkingDayRequest,
    onSubmitApproveConfirmWorkingDaysRequest,
  };
  return <ConfirmDateMainView {...confirmDatePropsProvider(confirmProps)} />;
};

export default ConfirmDateContainer;
