"use client"
import LogoIcon from "./assets/LogoIcon"
import LogoText from "./assets/LogoText"
import FinishSection from "./FinishSection"
import React, { useEffect, useState } from "react"
import { SubmitFirstOnboardingPage, SubmitSkipOnboardingPage } from "./SubmitFirstOnboardingPage"
import { useRouter } from "next/navigation"

export default function FirstPage({ className = "" }: FirstPageProps) {
  const [emailInput, setEmailInput] = useState("")
  const [customOption] = useState("")

  const [isSubmitted, setIsSubmitted] = useState(false)
  const [emailInputElement, setEmailInputElement] = useState<HTMLInputElement | null>(null)
  const router = useRouter()

  useEffect(() => {
    setEmailInputElement(document.getElementById("email-input") as HTMLInputElement)
  }, [])

  const submitFirstPage = async () => {
    setIsSubmitted(true)
    if (emailInputElement?.checkValidity() && emailInput.trim() !== "") {
      const selectedLabels: string[] = []
      try {
        await SubmitFirstOnboardingPage(emailInput, selectedLabels, customOption)
        // Only navigate to getting started if the server action didn't redirect
        router.push("/app/gettingstarted")
      } catch {
        console.log("Server handled redirect or error occurred")
      }
    }
  }

  const submitSkip = async () => {
    setIsSubmitted(true)
    try {
      await SubmitSkipOnboardingPage()
      router.push("/app/gettingstarted")
    } catch {
      console.log("Server handled redirect or error occurred")
    }
  }

  return (
    <div
      className={`font-inter z-[3] flex flex-wrap rounded-sm border border-solid border-white bg-[radial-gradient(#FAFAFA1F,_#F6F6F600)] px-8 pb-8 pt-20 text-base
 leading-5 backdrop-blur-md ${className}`}
    >
      <div id="welcometext" className="flex flex-wrap items-start justify-start px-4 mr-4">
        <div className="flex flex-col gap-y-8 self-stretch">
          <div className="flex items-center gap-x-[11px]">
            <LogoIcon className="h-8 w-12 flex-shrink-0" />
            <LogoText className="mb-[2.9px] h-5 w-36" />
          </div>
          <h1 className="text-[28px] font-semibold leading-8 text-white">Welcome to Codeflash!</h1>
          <div className="flex text-white items-center text-xl font-light leading-5 mb-8">
            Ready to upgrade your codebase?
          </div>
        </div>
      </div>
      <div
        id="questions"
        className="flex flex-col items-start justify-start text-white gap-y-6 px-4"
      >
        <div className="flex flex-col items-start gap-y-2">
          <label className="text-white text-base" htmlFor="email-input">
            What email do you want to use for Codeflash?
          </label>
          <div
            className={`flex items-center self-stretch rounded-sm border border-solid ${isSubmitted && !emailInputElement?.checkValidity() ? "border-yellow-400" : "border-white/10"} bg-white/5 px-[11px] py-[7px] focus-within:[box-shadow:0_0_4px_#1e40af]`}
          >
            <input
              className="font-source_code_pro flex-grow leading-tight text-stone-400 [outline:none] placeholder:text-[#B6AFAF]"
              placeholder="Enter email here"
              id="email-input"
              type="email"
              value={emailInput}
              onChange={e => {
                // e.target.setCustomValidity(e.target.value.trim() === "" ? "Email is required" : "")
                setEmailInput(e.target.value)
              }}
            />
          </div>
          {isSubmitted && (emailInput.trim() == "" || !emailInputElement?.checkValidity()) && (
            <label className="text-xs leading-5 text-yellow-400" htmlFor="email-input">
              Please enter a valid email
            </label>
          )}
        </div>
        <FinishSection onClick={submitFirstPage} buttonText="Finish" />
        <div className="font-sora self-stretch pt-1 text-center leading-normal text-yellow-400">
          <a href="#" onClick={submitSkip} className="hover:underline">
            Skip personalizing and continue
          </a>
        </div>
      </div>
    </div>
  )
}

interface FirstPageProps {
  className?: string
}
