"use client"

import { useState } from "react"
import { z } from "zod"
import { useForm } from "react-hook-form"
import { zodResolver } from "@hookform/resolvers/zod"
import { useSearchParams } from "next/navigation"
import { Loader2 } from "lucide-react"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Form, FormControl, FormField, FormItem, FormMessage } from "@/components/ui/form"
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription } from "@/components/ui/dialog"
import { useToast } from "@/hooks/use-toast"

// Form schema
const formSchema = z.object({
  email: z.string().email("Please enter a valid email address"),
  website: z.string().optional(), // Honeypot field
})

type FormValues = z.infer<typeof formSchema>

export default function WaitlistForm({ className = "" }: { className?: string }) {
  const [isSubmitting, setIsSubmitting] = useState(false)
  const [showSuccessDialog, setShowSuccessDialog] = useState(false)
  const searchParams = useSearchParams()
  const { toast } = useToast()

  // Initialize form
  const form = useForm<FormValues>({
    resolver: zodResolver(formSchema),
    defaultValues: {
      email: "",
      website: "", // Honeypot starts empty
    },
  })

  // Generate a simple HMAC signature (simplified for demo)
  const generateSignature = (data: string) => {
    // In a real app, this would be a proper HMAC
    return btoa(data)
  }

  const onSubmit = async (data: FormValues) => {
    try {
      setIsSubmitting(true)

      // Get UTM parameters
      const utmSource = searchParams.get("utm_source") || ""
      const utmCampaign = searchParams.get("utm_campaign") || ""

      // Generate signature
      const signature = generateSignature(data.email)

      // Submit to API
      const response = await fetch("/api/subscribe", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
          "x-signature": signature,
        },
        body: JSON.stringify({
          email: data.email,
          website: data.website, // Send honeypot
          utmSource,
          utmCampaign,
        }),
      })

      // Try to parse the response as JSON
      let result
      try {
        result = await response.json()
      } catch (e) {
        console.error("Failed to parse response as JSON:", e)
        throw new Error("Failed to process your request. Please try again.")
      }

      if (!response.ok) {
        // Special handling for already subscribed users
        if (response.status === 409) {
          toast({
            title: "Already subscribed",
            description: "You're already on our waitlist!",
            variant: "default",
          })
          form.reset()
          setIsSubmitting(false)
          return
        }

        throw new Error(result.error || "Failed to subscribe")
      }

      // Show success dialog
      setShowSuccessDialog(true)
      form.reset()

      // Fire analytics event
      if (typeof window !== "undefined" && window.gtag) {
        window.gtag("event", "waitlist_signup", {
          event_category: "engagement",
          event_label: data.email,
        })
      }
    } catch (error) {
      console.error("Subscription error:", error)
      toast({
        title: "Error",
        description: error instanceof Error ? error.message : "Failed to join waitlist. Please try again.",
        variant: "destructive",
      })
    } finally {
      setIsSubmitting(false)
    }
  }

  return (
    <div className={className}>
      <Form {...form}>
        <form onSubmit={form.handleSubmit(onSubmit)} className="mx-auto flex max-w-md flex-col gap-2 sm:flex-row">
          {/* Honeypot field - hidden from users but visible to bots */}
          <input
            type="text"
            name="website"
            tabIndex={-1}
            aria-hidden="true"
            style={{ position: "absolute", opacity: 0, pointerEvents: "none" }}
            {...form.register("website")}
          />

          <FormField
            control={form.control}
            name="email"
            render={({ field }) => (
              <FormItem className="flex-1">
                <FormControl>
                  <Input
                    placeholder="Enter your email"
                    type="email"
                    autoComplete="email"
                    data-testid="email"
                    className="h-12"
                    {...field}
                  />
                </FormControl>
                <FormMessage />
              </FormItem>
            )}
          />

          <Button type="submit" size="lg" disabled={isSubmitting} data-testid="submit" className="h-12">
            {isSubmitting ? (
              <>
                <Loader2 className="mr-2 h-4 w-4 animate-spin" />
                Joining...
              </>
            ) : (
              "Join Waitlist"
            )}
          </Button>
        </form>
      </Form>

      {/* Success Dialog */}
      <Dialog open={showSuccessDialog} onOpenChange={setShowSuccessDialog}>
        <DialogContent>
          <DialogHeader>
            <DialogTitle>Thank you for joining!</DialogTitle>
            <DialogDescription>
              Your email has been added to our waitlist. We'll keep you updated on our progress and let you know when
              we're ready to launch.
            </DialogDescription>
          </DialogHeader>
          <div className="mt-4 flex justify-end">
            <Button onClick={() => setShowSuccessDialog(false)}>Close</Button>
          </div>
        </DialogContent>
      </Dialog>
    </div>
  )
}
