"use client";

import { useState } from "react";
import { motion, AnimatePresence } from "framer-motion";

import { getSpace } from "@/app/actions";
import { Space as SpaceProps } from "@/utils/types";
import { Space } from "@/components/space";

import { ButtonShuffler } from "./button";
import { Card } from "@/components/animate/card";

export const Shuffler = ({
  space: initialSpace,
  nextSpace: initialNextSpace,
}: {
  space: SpaceProps;
  nextSpace: SpaceProps;
}) => {
  const [index, setIndex] = useState(0);
  const [space, setSpace] = useState<SpaceProps>(
    JSON.parse(JSON.stringify(initialSpace))
  );
  const [nextSpace, setNextSpace] = useState<SpaceProps>(
    JSON.parse(JSON.stringify(initialNextSpace))
  );

  return (
    <motion.div className="grid grid-cols-1 gap-10 relative">
      <div className="relative w-full h-[290px] lg:h-[350px]">
        <AnimatePresence initial={false}>
          <Card key={index + 1} front={false}>
            <Space space={nextSpace} />
          </Card>
          <Card key={index} front={true} index={index} setIndex={setIndex}>
            <Space space={space} />
          </Card>
        </AnimatePresence>
      </div>
      <div className="w-4 h-[1px] bg-white/50 mx-auto hidden lg:block" />
      <footer className="flex items-center justify-center fixed lg:relative bottom-0 left-0 w-full">
        <ButtonShuffler
          onClick={() => {
            getSpace().then((newSpace) => {
              setSpace(nextSpace);
              setNextSpace(newSpace);
              setIndex(index + 1);
            });
          }}
        />
      </footer>
    </motion.div>
  );
};
