import React, { useContext, useEffect, useState } from "react";
import { ConfigureContext } from "./contex/configureContext/ConfigureContext";
import { DataContext } from "./contex/dataContext/DataContex";
import { Render } from "./components/Render";
import { FormattedText } from "./components/FormattedText";
import { getEmployees, getEmployeesYearly } from "./helpers/getEmployees";
import { filterEmployees } from "./helpers/filterEmployees";
import moment from "moment";
import { getMonth } from "./helpers/utils";
import localforage from "localforage";

type Props = {
  data: VixonicData;
  start: boolean;
};

type Msj =
  | 'Ningún ingreso que mostrar'
  | 'Cargando Empleados...'
  | 'Missing google sheets'
  | ""
  | 'Invalid URL';

export const App = ({ data, start }: Props) => {
  const { addConfiguration, configureState } = useContext(ConfigureContext);
  const { addEmployee } = useContext(DataContext);
  const [dataState, setDataState] = useState(data)
  const [msj, setMsj] = useState<Msj>("");
  const { apiDomain, dataMode, excludePast } = configureState.parameters;
  let updateTimer : any


  useEffect(()=> {
    if(apiDomain){
      localforage.config({
        name: `url_request_${apiDomain}`
      })
    }
  },[apiDomain])

  useEffect(() => {
    addConfiguration(data);
    setDataState(configureState);
  }, [data]);


  const setUpdateTime =(updatedTime: number) => {
    clearTimeout(updateTimer)
    updateTimer = setTimeout(getData, updatedTime)
  }

  useEffect(() => {
    const { updateTime } = configureState.parameters

    if (apiDomain && dataMode) {
      localforage.getItem<{ items: any[], date: number, mode: string }>('anniversary-docs').then((data) => {  
        if(!data || dataMode !== data.mode ) {
          getData()
          setUpdateTime(updateTime!)
          return  
        }
      
        const now = Date.now()
        const targetDate = data?.date! + updateTime!

        if(now >= targetDate){
          getData()
          setUpdateTime(updateTime!)
        }else {
          data && addEmployee(data.items)
          setMsj("");
          setUpdateTime(targetDate-now)
        }
      })
    }
    if (!apiDomain) setMsj("Missing google sheets");
  }, [dataState]);

  const getData = async () => {
    const urlValid = "https://docs.google.com/spreadsheets/d/";
    let contractEmployees: any
    let employee: any = []
    try {
      if (apiDomain !== undefined && apiDomain.includes(urlValid)) {
        let month = Number(moment().format("M")) - 1;
        let nextMonth = (month === 11) ?  0 : (month + 1); 
        let monthTab = getMonth(month);
        let nextMonthTab = getMonth(nextMonth);
        if (dataMode !== 'yearly') {
          contractEmployees = await getEmployees(apiDomain, dataMode, monthTab);
          const { values } = contractEmployees.data
          employee.push(...filterEmployees(values, dataMode, excludePast, month))
          if( dataMode === 'weekly') {
            contractEmployees = await getEmployees(apiDomain, dataMode, nextMonthTab);
            const { values: valuesnextMonth } = contractEmployees.data
            employee.push(...filterEmployees(valuesnextMonth, dataMode, excludePast, nextMonth))
          }
        }

        if (dataMode === 'yearly') {
          setMsj('Cargando Empleados...')
          for (let numberMonth: number = 0; numberMonth <= 11; numberMonth++) {
            contractEmployees = await getEmployeesYearly(apiDomain, numberMonth);
            const { values } = contractEmployees.data
            employee.push(...filterEmployees(values, dataMode, excludePast, numberMonth))
          }
        }

        if (contractEmployees) {
          addEmployee(employee);
          setMsj("");
          localforage.setItem('anniversary-docs', {
            items: employee,
            date: Date.now() + updateTimer,
            mode: dataMode
          })
        } else {
          setMsj("Ningún ingreso que mostrar");
        }
      } else {
        setMsj("Invalid URL");
      }
    } catch (error) {
      console.log(error);
    }
  };

  return msj !== "" ? (
    <FormattedText
      text={msj}
      format={
        configureState.parameters.nameFormat ||
        configureState.parameters.descriptionFormat
      }
    />
  ) : (
    <Render start={start} />
  );
};
