"use client";

import React, { CSSProperties, useEffect } from "react";
import styles from "./FormSection.module.css";
import Image from "next/image";
import * as Yup from "yup";
import { useFormik } from "formik";
import { loadStripe } from "@stripe/stripe-js";
import { v4 as uuidv4 } from "uuid";
import axios from 'axios';

interface StartupFormValues {
  startupName: string;
  startupDescription: string;
  problem: string;
  targetAudience: string;
  uniqueSellingPoint: string;
  traction: string;
  funding: string;
  email: string;
  firstName: string;
}

const validationSchema = Yup.object().shape({
  startupName: Yup.string()
    .required("Startup name is required")
    .min(2, "Startup name must be at least 2 characters")
    .max(30, "Startup name must be at most 30 characters"),
  startupDescription: Yup.string()
    .required("Startup description is required")
    .min(10, "Description must be at least 10 characters")
    .max(500, "Description must be at most 500 characters"),
  problem: Yup.string()
    .required("Problem description is required")
    .min(10, "Problem description must be at least 10 characters")
    .max(500, "Problem description must be at most 500 characters"),
  targetAudience: Yup.string()
    .required("Target audience is required")
    .min(10, "Target audience description must be at least 10 characters")
    .max(500, "Target audience description must be at most 500 characters"),
  uniqueSellingPoint: Yup.string()
    .required("Unique selling point is required")
    .min(10, "Unique selling point must be at least 10 characters")
    .max(500, "Unique selling point must be at most 500 characters"),
  traction: Yup.string()
    .required("Traction information is required")
    .min(10, "Traction description must be at least 10 characters")
    .max(500, "Traction description must be at most 500 characters"),
  funding: Yup.string()
    .required("Funding information is required")
    .min(5, "Funding description must be at least 5 characters")
    .max(500, "Funding description must be at most 500 characters"),
  email: Yup.string()
    .required("Email is required")
    .test(
      "no-spaces",
      "Email cannot contain spaces",
      (value) => !value.includes(" ")
    )
    .email("Invalid email address")
    .matches(/\.[a-zA-Z]{2,62}$/, "Please input a valid email address."),
  firstName: Yup.string()
    .required("Name is required")
    .matches(
      /^[a-zA-Z]+( [a-zA-Z]+)*$/,
      "Name must contain only alphabets with optional space"
    )
    .min(3, "Name must be at least 3 characters")
    .max(30, "Name must be at most 30 characters")
    .test(
      "no-leading-trailing-space",
      "Name cannot have leading or trailing spaces",
      (value) => (value ? value === value.trim() : true)
    ),
});

interface FormSectionProps {
  style?: CSSProperties;
}
const stripeKey = process.env.NEXT_PUBLIC_STRIPE_PUBLIC_KEY;
const stripePromise = loadStripe(stripeKey!);

const FormSection: React.FC<FormSectionProps> = ({ style }) => {
  const [paymentError, setPaymentError] = React.useState<string | null>(null);

  const formik = useFormik<StartupFormValues>({
    initialValues: {
      startupName: "",
      startupDescription: "",
      problem: "",
      targetAudience: "",
      uniqueSellingPoint: "",
      traction: "",
      funding: "",
      email: "",
      firstName: "",
    },
    validationSchema,
    validateOnBlur: true,
    validateOnChange: true,
    onSubmit: async (values) => {
      const details = `Briefly describe what your startup does: ${values.startupDescription}
      \nBriefly explain the core problem your startup addresses: ${values.problem}
       \nWho are your primary users or customers ?: ${values.targetAudience}
       \nWhat makes your solution stand out from competitors ?: ${values.uniqueSellingPoint}
       \nDescribe your startup's traction: ${values.traction}
       \nDescribe Funding amount and usage: ${values.funding}`;
      try {
        const res = await axios.post(`${process.env.NEXT_PUBLIC_IDEA_API_URL}/data/mypitchsavedata`, { name: values.firstName, email: values.email, startup: values.startupName, details: details });
        setPaymentError(null);
        sessionStorage.setItem("entryId", res?.data);

        const hubspotdata = {
          email: values.email,
          firstName: values.firstName,
          startupName: values.startupName,
          details: details,
        };

        const hubspot = await fetch("/api/hubspot", {
          method: "POST",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify(hubspotdata),
        });

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

        const response = await fetch("/api/stripe/payment", {
          method: "POST",
          headers: {
            "Content-Type": "application/json",
          },
          body: JSON.stringify(values),
        });
        if (response.ok) {
          const responseData = await response.json();
          const stripe = await stripePromise;
          let userId = sessionStorage.getItem("userId");
          if (!userId) {
            userId = uuidv4();
            sessionStorage.setItem("userId", userId);
          }
          sessionStorage.setItem("sessionId", responseData.session.id);
          Object.entries(values).forEach(([key, value]) => {
            sessionStorage.setItem(key, value);
          });

          const { error }: any = await stripe?.redirectToCheckout({
            sessionId: responseData.session.id,
          });

          if (error) {
            console.error("Error redirecting to checkout:", error);
            setPaymentError("Error redirecting to checkout. Please try again.");
          }
        } else {
          throw new Error("Failed to submit form");
        }
      } catch (error) {
        console.error("Error submitting form:", error);
        setPaymentError("Error redirecting to checkout. Please try again.");
      }
    },
  });

  useEffect(() => {
    sessionStorage.clear();
  }, []);

  return (
    <form
      className={styles.formSection}
      style={style}
      onSubmit={formik.handleSubmit}
    >
      {(
        Object.keys(formik.initialValues) as Array<keyof StartupFormValues>
      ).map((key) => (
        <div key={key} className={styles.inputContainer}>
          <input
            type="text"
            name={key}
            placeholder={
              key === "startupName"
                ? "Enter your Startup's Name"
                : key === "startupDescription"
                  ? "Briefly describe what your startup does"
                  : key === "problem"
                    ? "Briefly explain the core problem your startup addresses"
                    : key === "targetAudience"
                      ? "Who are your primary users or customers ?"
                      : key === "uniqueSellingPoint"
                        ? "What makes your solution stand out from competitors ?"
                        : key === "traction"
                          ? "Describe your startup's traction"
                          : key === "funding"
                            ? "Describe Funding amount and usage"
                            : key === "email"
                              ? "Email"
                              : key === "firstName"
                                ? "What is your name ?"
                                : "What is your name ?"
            }
            value={formik.values[key] as string}
            onChange={formik.handleChange}
            onBlur={formik.handleBlur}
            className={styles.input}
          />
          {formik.touched[key] && formik.errors[key] && (
            <div className={styles.errorMessage}>{formik.errors[key]}</div>
          )}
        </div>
      ))}

      <button
        type="submit"
        className={styles.submitButton}
        disabled={!formik.isValid || formik.isSubmitting}
      >
        {formik.isSubmitting ? (
          <span>Submitting your data ...</span>
        ) : (
          <>
            <span>Get your custom pitch deck template ($29)</span>
            <Image
              src="https://dashboard.codeparrot.ai/api/image/Z-KLq94gt92eP1Ul/icon-b-2-a.png"
              alt="arrow"
              className={styles.buttonIcon}
              width={20}
              height={50}
            />
          </>
        )}
      </button>

      {paymentError && (
        <div
          className={styles.errorMessage}
          style={{ marginTop: "10px", textAlign: "center" }}
        >
          {paymentError}
        </div>
      )}
    </form>
  );
};

export default FormSection;
