import React, { useGlobal } from "reactn";
import { View, Text, Pressable } from "react-native";
import { capitalize } from "lodash";
import moment from "moment";
import { Motion } from "@legendapp/motion";
import { validateDate } from "react-native-minuit/src/actions/dateActions";

import { Fonts, Palette, Style } from "../styles";
import { projectsRef } from "../config/firebase";

export default ({ actionList = [] }) => {
  const [currentProjectID] = useGlobal("currentProjectID");

  const onCheck = async ({ todoID, isChecked = false }) => {
    try {
      const updatedObject = {
        isChecked: !isChecked,
        completionTimestamp: !isChecked ? new Date() : null,
      };

      await projectsRef
        .doc(currentProjectID)
        .collection("todoList")
        .doc(todoID)
        .update(updatedObject);
    } catch (error) {
      console.log("error", error);
    }
  };

  if (!actionList.length) {
    return (
      <Text style={Fonts({ type: "default", style: {} })}>
        Vous n'avez pas d'actions en attente.
      </Text>
    );
  }

  return actionList.map(
    (
      {
        title = "",
        requestedCompletionTimestamp = null,
        isChecked = false,
        todoID = null,
      },
      index
    ) => {
      return (
        <React.Fragment key={index}>
          <Pressable
            style={Style.containerRow}
            onPress={() => onCheck({ todoID, isChecked })}
          >
            <View style={[Style.containerRadio, { marginRight: 20 }]}>
              {isChecked && (
                <Motion.View
                  initial={{ opacity: 0, scale: 0 }}
                  animate={{ opacity: 1, scale: 1 }}
                  style={Style.circleRadio}
                />
              )}
            </View>

            <View>
              <Text
                style={Fonts({
                  type: "default",
                  style: isChecked
                    ? { textDecorationLine: "line-through" }
                    : {},
                })}
              >
                {capitalize(title)}
              </Text>

              <Text
                style={Fonts({
                  type: "default",
                  color: Palette.transparentWhite,
                })}
              >
                {capitalize(
                  moment(validateDate(requestedCompletionTimestamp)).fromNow()
                )}
              </Text>
            </View>
          </Pressable>

          {index !== actionList.length - 1 && (
            <View
              style={[
                Style.separatorHorizontal,
                Style.containerRevertGutter,
                { width: "112%" },
              ]}
            />
          )}
        </React.Fragment>
      );
    }
  );
};
