import { useState } from "react";
import { motion } from "framer-motion";
import BoxContainer from "./components/BoxContainer";
import VideoWrapper from "@/components/VideoWrapper.tsx";
import ResultContainer from "@/components/ResultContainer.tsx";
import DarkVideoWrapper from "@/components/DarkVideoWrapper.tsx";

export type fetchResult = "Valid" | "Not Valid" | "Fetching" | "Error";

enum StepType {
  takeId,
  verifyId,
  takeFrontPic,
  verifyProfile,
  result,
}

const stepsArray: StepType[] = [
  StepType.takeId,
  StepType.verifyId,
  StepType.takeFrontPic,
  StepType.verifyProfile,
  StepType.result,
];

export default function VerificationScene() {
  const [currentStep, setCurrentStep] = useState<StepType>(StepType.takeId);
  const [idCardPicture, setIdCardPicture] = useState<string>();
  const [profilePicture, setProfilePicture] = useState<string>();

  const handleNextStep = () => {
    if (currentStep === StepType.result) return;
    setCurrentStep((currentStep + 1) % stepsArray.length);
  };

  const handlePrevStep = () => {
    if (currentStep === StepType.takeId) return;
    setCurrentStep((currentStep - 1) % stepsArray.length);
  };

  const sendImageToServer = async (
    idCard: string,
    profileImage: string,
    setLoading: (n: fetchResult) => void,
  ) => {
    try {
      const response = await fetch("https://0.0.0.0:7860/uploadids", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify({ idCard: idCard, profileImage: profileImage }),
      });

      if (!response.ok) {
        throw new Error("Erreur lors de l'envoi de l'image");
      }

      const data = await response.json();
      console.log("Image envoyée avec succès:", data);
      setLoading(data.message === "Valid" ? "Valid" : "Not Valid");
    } catch (error) {
      console.error("Erreur:", error);
      setLoading("Error");
    }
  };

  // Animation settings for Framer Motion
  const animationProps = {
    initial: { opacity: 0, y: 50 },
    animate: { opacity: 1, y: 0 },
    exit: { opacity: 0, y: -50 },
    transition: { duration: 0.5 },
  };

  let stepContent = undefined;

  if (currentStep === StepType.takeId) {
    stepContent = (
      <motion.div
        key="takeId"
        {...animationProps}
        className="flex flex-col items-center"
      >
        <h1 className="text-black text-2xl mt-20 text-center px-28">
          Take a picture of the Capture the front side of your ID Card
        </h1>
        <VideoWrapper
          handleNextStep={handleNextStep}
          setImage={setIdCardPicture}
          className="shadow-lg mt-20"
          height="250px"
          width="400px"
        />
      </motion.div>
    );
  }
  if (currentStep === StepType.verifyId) {
    stepContent = (
      <motion.div
        key="verifyId"
        {...animationProps}
        className="flex flex-col items-center"
      >
        <div className="overflow-hidden w-2/3 h-2/4 mt-10">
          <img src={idCardPicture} alt="captured" />
        </div>
        <h1 className="text-2xl font-bold mt-10">Is This Picture Correct?</h1>
        <div className="mt-32 space-x-20">
          <button
            onClick={handlePrevStep}
            className="bg-red-600 transition text-white rounded-2xl text-xl hover:bg-red-800 w-40 h-16"
          >
            No
          </button>
          <button
            onClick={handleNextStep}
            className="bg-blue-600 transition text-white rounded-2xl text-xl hover:bg-gray-800 w-40 h-16"
          >
            Yes
          </button>
        </div>
      </motion.div>
    );
  }

  if (currentStep === StepType.takeFrontPic) {
    stepContent = (
      <motion.div
        key="takeFrontPic"
        {...animationProps}
        className="flex flex-col items-center"
      >
        <h1 className="mt-5 font-bold text-lg">Center your face</h1>
        <DarkVideoWrapper
          setImage={setProfilePicture}
          className="mt-12 w-3/4 h-3/5 overflow-hidden"
          handleNextStep={handleNextStep}
        />
      </motion.div>
    );
  }
  if (currentStep === StepType.verifyProfile) {
    stepContent = (
      <motion.div
        key="verifyProfile"
        {...animationProps}
        className="flex flex-col items-center"
      >
        <div className="overflow-hidden w-2/3 h-2/4 mt-10">
          <img src={profilePicture} alt="captured" />
        </div>
        <h1 className="text-2xl font-bold mt-10">Is This Picture Correct?</h1>
        <div className="mt-32 space-x-20">
          <button
            onClick={handlePrevStep}
            className="bg-red-600 transition text-white rounded-2xl text-xl hover:bg-red-800 w-40 h-16"
          >
            No
          </button>
          <button
            onClick={handleNextStep}
            className="bg-blue-600 transition text-white rounded-2xl text-xl hover:bg-gray-800 w-40 h-16"
          >
            Yes (Submit)
          </button>
        </div>
      </motion.div>
    );
  }

  if (currentStep === StepType.result) {
    stepContent = (
      <motion.div
        key="result"
        {...animationProps}
        className="flex flex-col items-center"
      >
        <ResultContainer
          sendImageToServer={sendImageToServer}
          idCardPicture={idCardPicture ?? ""}
          profileImage={profilePicture ?? ""}
        />
      </motion.div>
    );
  }

  return (
    <>
      <div className="bg-gray-100">
        <BoxContainer headerName="Identity Verification Required">
          <div className="h-full w-full flex flex-col items-center justify-center overflow-hidden">
            {stepContent}
          </div>
        </BoxContainer>
      </div>
    </>
  );
}
