import React, { useEffect, useState } from "react";
import styles from "./TableComponent.module.css";
import { useRouter } from "next/navigation";
import LoaderIcon from "@/components/Loader";
import Image from "next/image";

const TableComponent = () => {
  const [sessionData, setSessionData] = useState<any>("");
  const router = useRouter();
  // const [slideUrl, setSlideUrl] = useState("");
  const [isLoading, setIsLoading] = useState(true);
  // const [isSlideLoading, setIsSlideLoading] = useState(true);
  // const [userId, setUserId] = useState<string | null>(null);

  useEffect(() => {
    const fetchSessionData = async () => {
      setIsLoading(true);
      try {
        const sessionId = sessionStorage.getItem("sessionId");
        if (sessionId) {
          const data = [
            {
              field: "Startup name",
              entry: sessionStorage.getItem("startupName") || "N/A",
            },
            {
              field: "Describe Startup",
              entry: sessionStorage.getItem("startupDescription") || "N/A",
            },
            {
              field: "Describe the problem you solve",
              entry: sessionStorage.getItem("problem") || "N/A",
            },
            {
              field: "Target customer(s)",
              entry: sessionStorage.getItem("targetAudience") || "N/A",
            },
            {
              field: "Unique Selling Point",
              entry: sessionStorage.getItem("uniqueSellingPoint") || "N/A",
            },
            {
              field: "Traction",
              entry: sessionStorage.getItem("traction") || "N/A",
            },
            {
              field: "How much funds and use of it",
              entry: sessionStorage.getItem("funding") || "N/A",
            },
          ];

          setSessionData(data);
          // const existingSlideUrl = sessionStorage.getItem("slide");
          // if (existingSlideUrl) {
          // setSlideUrl(existingSlideUrl as string);
          // setIsSlideLoading(false);
          // } else {
          const zapierdata = {
            UserName: sessionStorage.getItem("firstName"),
            Startup: sessionStorage.getItem("startupName") || "N/A",
            Email: sessionStorage.getItem("email") || "N/A",
            "Startup Description":
              sessionStorage.getItem("startupDescription") || "N/A",
            "Problem Solution": sessionStorage.getItem("problem") || "N/A",
            "Target Audience":
              sessionStorage.getItem("targetAudience") || "N/A",
            "Unique Selling Point":
              sessionStorage.getItem("uniqueSellingPoint") || "N/A",
            Traction: sessionStorage.getItem("traction") || "N/A",
            Fundsuse: sessionStorage.getItem("funding") || "N/A",
            userId: sessionStorage.getItem("userId") || "N/A",
            entryId: sessionStorage.getItem("entryId") || "N/A",
            readURL: `${process.env.NEXT_PUBLIC_IDEA_API_URL}/data/readpitchdeck/${sessionStorage.getItem("entryId")}` || "N/A",
          };
          // setUserId(sessionStorage.getItem("userId"));
          await sendDataToZapier(zapierdata);
          setIsLoading(false);
          // setIsSlideLoading(true);
          // }
        }else{
          router.push("/");
        }
      } catch (error) {
        console.error("Error fetching session data:", error);
      }
      //   setIsLoading(false);
      // }
    };

    fetchSessionData();
  }, [router]);

  // useEffect(() => {
  //   const pollSlideUrl = async () => {
  //     if (isSlideLoading && !sessionStorage.getItem("slide")) {
  //       await fetchGoogleSlideUrl();
  //     }
  //   };

  //   if (isSlideLoading && !sessionStorage.getItem("slide")) {
  //     const initialTimeout = setTimeout(pollSlideUrl, 80000);
  //     const intervalId = setInterval(pollSlideUrl, 60000);

  //     return () => {
  //       clearTimeout(initialTimeout);
  //       clearInterval(intervalId);
  //     };
  //   }
  // }, [isSlideLoading]);

  const sendDataToZapier = async (data: any) => {
    try {
      const response = await fetch("/api/zapier", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify(data),
      });

      if (response.ok) {
        const formattedresponse = await response.json();
        console.log(formattedresponse, "resp");
        console.log("Data successfully sent to Zapier");
        return true;
      } else {
        console.error("Failed to send data to Zapier");
        // setIsSlideLoading(false);
        return false;
      }
    } catch (error) {
      console.error("Error sending data to Zapier:", error);
      return false;
    }
  };

  // const fetchGoogleSlideUrl = async () => {
  //   setIsSlideLoading(true);
  //   try {
  //     const userId = sessionStorage.getItem("userId");
  //     const response = await fetch(`/api/googleslide?userId=${userId}`);
  //     if (response.ok) {
  //       const data = await response.json();
  //       if (data.slideUrl) {
  //         // setSlideUrl(data.slideUrl);
  //         sessionStorage.setItem("slide", data.slideUrl);
  //         setIsSlideLoading(false);
  //         const hubspotdata = {
  //           email: sessionStorage.getItem("email"),
  //           name: sessionStorage.getItem("firstName"),
  //           startupName: sessionStorage.getItem("startupName"),
  //           url: data.slideUrl,
  //         };
  //         const hubspot = await fetch("/api/hubspot", {
  //           method: "POST",
  //           headers: { "Content-Type": "application/json" },
  //           body: JSON.stringify(hubspotdata),
  //         });

  //         const res = await hubspot.json();
  //         console.log("HubSpot submission successful:", res);

  //       } else {
  //         console.log("No slide URL found for this session");
  //       }
  //     } else {
  //       console.error("Failed to retrieve Google Slide URL");
  //     }
  //   } catch (error) {
  //     console.error("Error fetching Google Slide URL:", error);
  //   }
  // };

  // const handleRetry = async () => {
  //   setIsSlideLoading(true);

  //   const zapierdata = {
  //     UserName: sessionStorage.getItem("firstName"),
  //     Startup: sessionStorage.getItem("startupName") || "N/A",
  //     Email: sessionStorage.getItem("email") || "N/A",
  //     "Startup Description":
  //       sessionStorage.getItem("startupDescription") || "N/A",
  //     "Problem Solution": sessionStorage.getItem("problem") || "N/A",
  //     "Target Audience": sessionStorage.getItem("targetAudience") || "N/A",
  //     "Unique Selling Point":
  //       sessionStorage.getItem("uniqueSellingPoint") || "N/A",
  //     Traction: sessionStorage.getItem("traction") || "N/A",
  //     Fundsuse: sessionStorage.getItem("funding") || "N/A",
  //     userId: sessionStorage.getItem("userId") || "N/A",
  //   };

  //   sessionStorage.removeItem("slide");
  //   setSlideUrl("");
  //   await sendDataToZapier(zapierdata);
  //   await fetchGoogleSlideUrl();
  // };

  if (isLoading) {
    return <LoaderIcon></LoaderIcon>;
  }

  if (!sessionData || sessionData.length === 0) {
    return (
      <div className="flex flex-col items-center justify-center min-h-screen p-6 text-center">
        <h2 className="text-2xl font-bold text-gray-800 mb-4">
          Session Completed
        </h2>
        <p className="text-gray-600 mb-6">
          Check your email for your customized pitch deck
        </p>
        <button 
          onClick={() => router.push("/")}
          className="bg-green-500 hover:bg-green-600 text-white font-medium py-2 px-4 rounded-md transition duration-300 ease-in-out"
        >
          Return to Homepage
        </button>
      </div>
    );
  }
  return (
    <div className={styles.tableContainer}>
      {/* <table className={styles.table}>
        <thead>
          <tr>
            <th className={styles.headerCell}>Field</th>
            <th className={styles.headerCell}>Entry</th>
          </tr>
        </thead>
        <tbody>
          {sessionData.map((row: any, index: any) => (
            <tr key={index} className={styles.tableRow}>
              <td className={styles.fieldCell}>
                {row.field.split("\n").map((line: any, i: any) => (
                  <React.Fragment key={i}>
                    {line}
                    {i < row.field.split("\n").length - 1 && <br />}
                  </React.Fragment>
                ))}
              </td>
              <td className={styles.entryCell}>
                {row.entry.split("\n").map((line: any, i: any) => (
                  <React.Fragment key={i}>
                    {line}
                    {i < row.entry.split("\n").length - 1 && <br />}
                  </React.Fragment>
                ))}
              </td>
            </tr>
          ))}
        </tbody>
      </table> */}
      {/* <div>
        {isSlideLoading ? (
          <div className="flex items-center justify-center my-6">
            <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-gray-900"></div>
            <span className="ml-3 text-gray-600">
              Generating your slide deck...
            </span>
          </div>
        ) : slideUrl ? (
          <div className="mb-6">
            <h3 className="text-xl font-semibold text-gray-800 my-3">
              Your Presentation
            </h3>

            <div className="rounded-lg border border-gray-200 overflow-hidden mb-4">
              <div className="aspect-w-16 aspect-h-9 w-full">
                <iframe
                  src={`${slideUrl.replace("/edit", "/embed")}`}
                  width="100%"
                  height="480"
                  className="w-full"
                ></iframe>
              </div>
            </div>

          </div>
        ) : (
          <div className="text-center text-gray-600 my-6">
            <p className="mb-4">
              Unable to generate slide deck at this moment. Please try again.
            </p>
            {userId && (
              <button
                onClick={handleRetry}
                className="bg-blue-500 hover:bg-blue-600 text-white font-medium py-2 px-4 rounded-md transition duration-300 ease-in-out focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-opacity-50"
              >
                Retry Generation
              </button>
            )}
          </div>
        )}
      </div> */}
      <div className={styles.completionContainer}>
        <div className={styles.gifContainer}>
          {/* <img
      src="/gifgreat.gif"
      width="320"
      height="240"
      className={styles.giphyEmbed}
      alt="GIF Animation"
    /> */}
          <Image
            src="/gifgreat.gif"
            width="450"
            height="300"
            className={styles.giphyEmbed}
            alt="GIF Animation"
          />
        </div>

        <h2 className={styles.completionTitle}>Payment successful ✅</h2>

        <p className={styles.completionMessage}>
          Our AI just got to work! Within a few minutes you will receive a
          download link via email. Make sure to check your spam folder too.
        </p>

        <p className={styles.supportMessage}>
          If you run into any problems, please send an email to{" "}
          <a href="mailto:hello@mypitchdeck.com" className={styles.link}>
            <u>hello@mypitchdeck.com</u>
          </a>
        </p>
        <button onClick={() => router.push("/#form")} className={styles.ctaButton}>
            Create another Pitch Deck
          </button>
      </div>
    </div>
  );
};

export default TableComponent;
