"use client"

import { useForm } from "react-hook-form"
import { zodResolver } from "@hookform/resolvers/zod"
import { z } from "zod"
import { useState } from "react"

const schema = z.object({
  email: z.string().email("Please enter a valid email address"),
})

type FormData = z.infer<typeof schema>

interface NewsletterFormProps {
  variant?: "light" | "dark"
}

export default function NewsletterForm({ variant = "dark" }: NewsletterFormProps) {
  const [status, setStatus] = useState<"idle" | "success" | "error">("idle")
  const isDark = variant === "dark"

  const {
    register,
    handleSubmit,
    formState: { errors, isSubmitting },
    reset,
  } = useForm<FormData>({
    resolver: zodResolver(schema),
  })

  const onSubmit = async (data: FormData) => {
    try {
      await new Promise((resolve) => setTimeout(resolve, 800))
      console.log("Newsletter subscription:", data.email)
      setStatus("success")
      reset()
    } catch {
      setStatus("error")
    }
  }

  if (status === "success") {
    return (
      <div className={`success-message-wrapper w-form-done`} style={{ display: "block" }}>
        <div className={`success-message-inside-input ${isDark ? "dark-mode" : ""}`}>
          <svg xmlns="http://www.w3.org/2000/svg" width="100%" viewBox="0 0 20 20" fill="none" className="squared-icon _14px">
            <path d="M7.20658 10.9311L9.24116 12.1209L12.7928 7.20696M1 10C1 5.02944 5.02944 1 10 1C14.9706 1 19 5.02944 19 10C19 14.9706 14.9706 19 10 19C5.02944 19 1 14.9706 1 10Z" stroke="currentColor" strokeWidth="1.5" strokeLinecap="square" />
          </svg>
          <div>Thanks for subscribing to our newsletter!</div>
        </div>
      </div>
    )
  }

  return (
    <div className={`form-block _465px w-form`}>
      <form onSubmit={handleSubmit(onSubmit)}>
        <div className="position-relative">
          <input
            className={`input ${isDark ? "dark-mode" : ""} w-input`}
            maxLength={256}
            placeholder="Enter your email"
            type="email"
            {...register("email")}
          />
          <div className={`button-inside-input-wrapper ${isDark ? "dark-mode" : ""} left-mbp`}>
            <button
              type="submit"
              className={`form-button inside-input ${isDark ? "dark-mode" : ""} w-button`}
              disabled={isSubmitting}
            >
              {isSubmitting ? "Please wait..." : "Subscribe"}
            </button>
          </div>
        </div>
        {errors.email && (
          <div className="error-message w-form-fail" style={{ display: "block" }}>
            <div>{errors.email.message}</div>
          </div>
        )}
      </form>
      {status === "error" && (
        <div className="error-message w-form-fail" style={{ display: "block" }}>
          <div>Oops! Something went wrong while submitting the form.</div>
        </div>
      )}
    </div>
  )
}
