
"use client";

import { useForm } from "react-hook-form";
import { useActionState } from "react"; // Changed from "react-dom" and useFormState
import { zodResolver } from "@hookform/resolvers/zod";
import { z } from "zod";
import { useEffect } from "react";

import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { useToast } from "@/hooks/use-toast";
import { subscribeToNewsletter, type NewsletterFormState } from "@/lib/actions";
import { Mail } from "lucide-react";

const NewsletterSchema = z.object({
  email: z.string().email({ message: "Please enter a valid email address." }),
});
type NewsletterFormValues = z.infer<typeof NewsletterSchema>;

const initialState: NewsletterFormState = {
  message: "",
};

export function NewsletterForm() {
  const { toast } = useToast();
  const [state, formAction] = useActionState(subscribeToNewsletter, initialState); // Changed to useActionState
  const form = useForm<NewsletterFormValues>({
    resolver: zodResolver(NewsletterSchema),
    defaultValues: { email: "" },
  });

  useEffect(() => {
    if (state.message) {
      if (state.success) {
        toast({
          title: "Success!",
          description: state.message,
        });
        form.reset();
      } else {
        toast({
          title: "Error",
          description: state.message || state.errors?.email?.[0] || "An unexpected error occurred.",
          variant: "destructive",
        });
      }
    }
  }, [state, toast, form]);

  return (
    <form
      action={formAction}
      onSubmit={form.handleSubmit(() => { /* Client-side validation runs, then action prop takes over */ })}
      className="flex flex-col sm:flex-row gap-2 w-full max-w-md"
    >
      <div className="relative flex-grow">
        <Mail className="absolute left-3 top-1/2 -translate-y-1/2 h-5 w-5 text-muted-foreground" />
        <Input
          {...form.register("email")}
          type="email"
          name="email"
          placeholder="Enter your email address"
          aria-label="Email address for newsletter"
          className="pl-10 h-12 text-base"
        />
      </div>
      <Button type="submit" size="lg" className="h-12 text-base" disabled={form.formState.isSubmitting}>
        {form.formState.isSubmitting ? "Subscribing..." : "Subscribe"}
      </Button>
      {form.formState.errors.email && (
        <p className="text-sm text-destructive mt-1 sm:col-span-2">
          {form.formState.errors.email.message}
        </p>
      )}
      {/* Display server-side error message for email if exists from useFormState */}
      {state.errors?.email && !form.formState.errors.email && (
         <p className="text-sm text-destructive mt-1 sm:col-span-2">
           {state.errors.email[0]}
         </p>
       )}
    </form>
  );
}
