Untitled

 avatar
unknown
plain_text
a year ago
16 kB
3
Indexable
import {
  Box,
  Button,
  Flex,
  HStack,
  Heading,
  Highlight,
  Icon,
  SimpleGrid,
  Step,
  StepIcon,
  StepIndicator,
  StepNumber,
  StepSeparator,
  StepStatus,
  Stepper,
  Text,
  Tooltip,
  VStack,
  useSteps,
  Modal,
  ModalOverlay,
  ModalContent,
  ModalHeader,
  ModalFooter,
  ModalBody,
  ModalCloseButton,
} from "@chakra-ui/react";
import React, { useEffect, useState } from "react";
import { AiOutlineInfoCircle } from "react-icons/ai";
import { useNavigate } from "react-router-dom";
import CSVUpload from "../buttons/modalselectbrookerbutton";
import RadioComponent from "../buttons/radiobuttons";
import SelectButton from "../buttons/selectbuttons";
import ImageUpload from "../inputs/imageupload";
import Moodslider from "../inputs/moodslider";
import Textareainput from "../inputs/textareainput";
import EmotionSelector from "../inputs/emotionselector";
import RichTextEditor from "./RichTextEditor";

const Stepsystem = () => {
  const getCurrentDate = () => {
    const today = new Date();
    const dd = String(today.getDate()).padStart(2, "0");
    const mm = String(today.getMonth() + 1).padStart(2, "0");
    const yyyy = today.getFullYear();
    return yyyy + "-" + mm + "-" + dd;
  };

  const [step, setStep] = useState(0);
  const [content1, setContent1] = useState("");
  const [content2, setContent2] = useState("");
  const [better, setBetter] = useState([]);
  const [grade, setGrade] = useState("");
  const [selectedEmoji, setSelectedEmoji] = useState(null);
  const [selectedImages, setSelectedImages] = useState([]);

  const [journalStatus, setJournalStatus] = useState(false);
  const [isModalOpen, setIsModalOpen] = useState(false);

  const convertEntityMapToArray = (entityMap) => {
    const entityArray = Object.keys(entityMap).map((key) => {
      const entity = entityMap[key];
      return {
        ...entity,
      };
    });
    return entityArray;
  };

  const findJournal = async () => {
    try {
      const response = await fetch("http://localhost:8000/stepsystem", {
        method: "GET",
        credentials: "include",
      });
      if (response.ok) {
        const journalStatus = await response.json();
        setJournalStatus(journalStatus.isJournalWritten);
        if (journalStatus.isJournalWritten) {
          setIsModalOpen(true);
        }
      }
    } catch (error) {
      console.error("Kunde inte se om journal redan finns.");
    }
  };

  useEffect(() => {
    findJournal();
  }, []);

  const createJournal = async (journalData) => {
    try {
      const response = await fetch("http://localhost:8000/newpage/journal", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        credentials: "include",
        body: JSON.stringify(journalData),
      });

      if (!response.ok) {
        const data = await response.json(); // Read the response body as JSON
        throw new Error(
          `HTTP error! status: ${response.status} Message: ${data.message}`
        );
      }

      const data = await response.json();
      console.log(data);
    } catch (error) {
      console.error(error);
    }
  };

  const handleSubmit = async () => {
    const content1Array = convertEntityMapToArray(content1);
    const content2Array = convertEntityMapToArray(content2);
    const journalData = {
      beforeToday: content1Array,
      afterToday: content2Array,
      mentality: selectedEmoji,
      better: better,
      grade: grade,
      date: getCurrentDate(),
      image: selectedImages,
    };
    console.log("Sending data:", journalData);

    try {
      await createJournal(journalData);
      // Navigate to a different route after successful journal creation
      navigate("/trender");
    } catch (error) {
      console.error(error);
      // Handle errors if needed
    }
  };

  const steps = [
    { title: "", description: " " },
    { title: "", description: " " },
    { title: "", description: " " },
  ];

  const { activeStep } = useSteps({
    index: 1,
    count: steps.length,
  });

  const goToNextStep = () => {
    setStep((prevStep) => prevStep + 1);
  };

  const goToPreviousStep = () => {
    if (step > 0) {
      setStep((prevStep) => prevStep - 1);
    }
  };

  const handleBetterClick = (title) => {
    setBetter((prevBetter) => {
      if (prevBetter.includes(title)) {
        return prevBetter.filter((t) => t !== title);
      } else {
        return [...prevBetter, title];
      }
    });
  };
  const [selectedOption, setSelectedOption] = useState(null);
  const handleRadioChange = (index, title) => {
    setSelectedOption(index);
    setGrade(title);
  };
  const colorWhite = "rgba(255, 255, 255, 0.87)";
  const navigate = useNavigate();
  const [isCsvUploadModalOpen, setIsCsvUploadModalOpen] = useState(false);
  const radioOptions = [
    {
      title: "Nöjd",
      index: 0,
      customColor: "#05d8a5",
      customTitleColor: "#0e0f11",
    },
    {
      title: "Lagom",
      index: 1,
      customColor: "#00B0ED",
      customTitleColor: "fff",
    },
    {
      title: "Missnöjd",
      index: 2,
      customColor: "#E53E3E",
      customTitleColor: "fff",
    },
  ];
  const totalSteps = 7; // Total number of steps (from step 1 to step 7)
  const completionPercentage = ((step - 1) / (totalSteps - 1)) * 100;

  // Define the gradient for the button
  const buttonBg = `linear-gradient(to right, #05d8a5 ${completionPercentage}%, white ${completionPercentage}%)`;

  return (
    <Flex
      direction="column"
      width="100%"
      height="720px"
      p={4} // Padding might help your layout breathe a little
    >
      <Flex
        direction="column"
        flex="1"
        justifyContent="center"
        alignItems="center"
      >
        {/* STEG 0 LADDA UPP CSV FRÅN IGÅR */}
        {step === 0 && (
          <>
            <VStack>
              <Heading>Innan vi börjar!</Heading>
              <Box mt={-2} mb={3}>
                <Highlight
                  query="igår"
                  styles={{ px: "1", py: "1", color: "#05d8a5" }}
                >
                  Glöm ej att lägga in handeln från igår.
                </Highlight>
              </Box>
              <Button onClick={() => setIsCsvUploadModalOpen(true)}>
                Ladda upp CSV fil
              </Button>
              <CSVUpload
                isOpen={isCsvUploadModalOpen}
                onClose={() => setIsCsvUploadModalOpen(false)}
              />
            </VStack>
          </>
        )}
        <div>
          {/* ... existing component structure */}
          <Modal isOpen={isModalOpen} onClose={() => setIsModalOpen(false)}>
            <ModalOverlay />
            <ModalContent>
              <ModalHeader>Meddelande</ModalHeader>
              <ModalCloseButton />
              <ModalBody>Journal är redan skriven för dagen.</ModalBody>
              <ModalFooter>
                <Button
                  colorScheme="red"
                  mr={3}
                  onClick={() => setIsModalOpen(false)}
                >
                  Stäng
                </Button>
              </ModalFooter>
            </ModalContent>
          </Modal>
        </div>

        {/* STEG 1 SKRIVA TEXT */}
        {step === 1 && (
          <VStack>
            <Heading>Pre handel</Heading>
            <VStack alignItems="center">
              <Box mb={8}>
                <Text fontSize="14" color="#A0AEC0" opacity={0.87}>
                  Skriv ner påminnelser och mål inför dagen.
                </Text>
              </Box>
              <RichTextEditor
                customWidth="1000px"
                customHeight="400px"
                onChange={(content1) => setContent1(content1)}
              ></RichTextEditor>
            </VStack>
          </VStack>
        )}

        {/* STEG 2 MENTALITET */}
        {step === 2 && (
          <VStack>
            <Heading>Mentalitet Idag</Heading>
            <VStack alignItems="center">
              <Box mb={8}>
                <Text fontSize="14" color="#A0AEC0" opacity={0.87}>
                  Kom ihåg att vara mentalt förberedd.
                </Text>
              </Box>
              <Box mt={5}>
                <EmotionSelector
                  selectedEmoji={selectedEmoji}
                  setSelectedEmoji={setSelectedEmoji}
                ></EmotionSelector>
              </Box>
            </VStack>
          </VStack>
        )}

        {/* STEG 3 POST-MARKET TEXT */}
        {step === 3 && (
          <VStack>
            <Heading>Post handel</Heading>
            <VStack alignItems="center">
              <Box mb={8}>
                <Text fontSize="14" color="#A0AEC0" opacity={0.87}>
                  Gick det som du hade tänkt dig? Skriv ner tankar.
                </Text>
              </Box>
              <RichTextEditor
                customWidth="1000px"
                customHeight="400px"
                onChange={(content2) => setContent2(content2)}
              ></RichTextEditor>
            </VStack>
          </VStack>
        )}
        {/* STEG 4 FÖRBÄTTRINGAR */}
        {step === 4 && (
          <VStack>
            <Heading>Vad kunde gått bättre?</Heading>
            <VStack alignItems="center">
              <Box mb={8}>
                <Text fontSize="14" color="#A0AEC0" opacity={0.87}>
                  Vilka moment behöver du förbättra utvärderat från dagens
                  handel?
                </Text>
              </Box>
              <SimpleGrid columns={4} spacing={10}>
                <SelectButton
                  customcolor="#05d8a5"
                  title={"Exits"}
                  onClick={handleBetterClick}
                ></SelectButton>
                <SelectButton
                  customcolor="#05d8a5"
                  title={"Sizing"}
                  onClick={handleBetterClick}
                ></SelectButton>
                <SelectButton
                  customcolor="#05d8a5"
                  title={"Förberedelser"}
                  onClick={handleBetterClick}
                ></SelectButton>
                <SelectButton
                  customcolor="#05d8a5"
                  title={"Mentalt"}
                  onClick={handleBetterClick}
                ></SelectButton>
                <SelectButton
                  customcolor="#05d8a5"
                  title={"Greed & Fomo"}
                  onClick={handleBetterClick}
                ></SelectButton>
                <SelectButton
                  customcolor="#05d8a5"
                  title={"Stops"}
                  onClick={handleBetterClick}
                ></SelectButton>
                <SelectButton
                  customcolor="#05d8a5"
                  title={"Entries"}
                  onClick={handleBetterClick}
                ></SelectButton>
                <SelectButton
                  customcolor="#05d8a5"
                  title={"Orderboken"}
                  onClick={handleBetterClick}
                ></SelectButton>
              </SimpleGrid>
            </VStack>
          </VStack>
        )}

        {/* STEG 5 LADDA UPP BILDER */}
        {step === 5 && (
          <VStack>
            <Heading>Ladda upp bilder</Heading>
            <VStack alignItems="center">
              <Box mb={4}>
                <Text fontSize="14" color="#A0AEC0" opacity={0.87}>
                  Bifoga dina magiska screenshots när du är helt sne.
                </Text>
              </Box>
            </VStack>

            <ImageUpload
              onImagesChange={(images) => setSelectedImages(images)}
            />
          </VStack>
        )}

        {/* STEG 6 NÖJD ELLER INTE */}
        {step === 6 && (
          <VStack>
            <Heading>Betygsättning</Heading>
            <VStack alignItems="center">
              <Box mb={8}>
                <Text fontSize="14" color="#A0AEC0" opacity={0.87}>
                  Är du nöjd eller missnöjd med dagen?
                </Text>
              </Box>

              <SimpleGrid columns={3} spacing={10}>
                {radioOptions.map((option) => (
                  <RadioComponent
                    key={option.index}
                    title={option.title}
                    customColor={option.customColor}
                    customTitleColor={option.customTitleColor}
                    isSelected={selectedOption === option.index}
                    onChange={() =>
                      handleRadioChange(option.index, option.title)
                    }
                  />
                ))}
              </SimpleGrid>
            </VStack>
          </VStack>
        )}

        {/* STEG 7 KLAR! */}
        {step === 7 && (
          <>
            <VStack>
              <Heading color={"#05D8A5"}>Journal klar!</Heading>
              <Text>
                Kom tillbaka imorgon för uppladdning av statistik, eller ladda
                upp ikväll.
              </Text>
              <HStack spacing={4}>
                <Button onClick={() => setIsCsvUploadModalOpen(true)}>
                  Ladda upp CSV idag
                </Button>
                <Button colorScheme="pink" onClick={handleSubmit}>
                  {/* UPPLADDNING CSV*/}
                  Spara & Analysera
                </Button>
              </HStack>

              <Button
                background={"none"}
                color={colorWhite}
                mt={4}
                onClick={goToPreviousStep}
                size={"sm"}
                _hover={{ background: "#1C1E22" }}
              >
                Tillbaka
              </Button>

              <CSVUpload
                isOpen={isCsvUploadModalOpen}
                onClose={() => setIsCsvUploadModalOpen(false)}
              />
            </VStack>
          </>
        )}
      </Flex>

      {/* FOOTER */}
      <Flex direction="column" align="center">
        {/* Navigation Buttons */}
        <HStack spacing={4}>
          {step !== 0 && step !== 7 ? (
            <>
              <Button
                background={"none"}
                color={colorWhite}
                onClick={goToPreviousStep}
                _hover={{ background: "#1C1E22" }}
              >
                Tillbaka
              </Button>
              <Button style={{ background: buttonBg }} onClick={goToNextStep}>
                Nästa
              </Button>
            </>
          ) : null}

          {step === 0 && (
            <Button
              background={"none"}
              color={colorWhite}
              onClick={goToNextStep}
              size={"sm"}
              _hover={{ background: "#1C1E22" }}
            >
              Hoppa över
            </Button>
          )}
        </HStack>
      </Flex>
    </Flex>
  );
};

export default Stepsystem;

{
  /* STEPPER 
        <Box marginBottom="4">
          <Stepper
            width={"500px"}
            colorScheme="whiteAlpha"
            // Removed width constraint to allow natural width
            index={step}
          >
            {steps.map((step, index) => (
              <Step key={index}>
                <StepIndicator>
                  <StepStatus
                    complete={<StepIcon />}
                    incomplete={<StepNumber />}
                    active={<StepNumber />}
                  />
                </StepIndicator>
                <StepSeparator />
              </Step>
            ))}
          </Stepper>
        </Box>*/
}
Editor is loading...
Leave a Comment