
"use client";

import { useForm, Controller } from "react-hook-form";
import { useActionState } from "react";
import { zodResolver } from "@hookform/resolvers/zod";
import { z } from "zod";
import { useEffect } from "react";
import { useSearchParams } from 'next/navigation';

import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Textarea } from "@/components/ui/textarea";
import { Label } from "@/components/ui/label";
import { useToast } from "@/hooks/use-toast";
import { submitContactForm, type ContactFormState } from "@/lib/actions";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Form, FormControl, FormField, FormItem, FormLabel, FormMessage } from "@/components/ui/form"; // Ensure Form, FormItem, FormField, FormMessage are imported
import { CORE_SERVICES } from "@/constants";

const serviceTitles = CORE_SERVICES.map(s => s.title);
const subjectEnumValues = ["General Inquiry", ...serviceTitles] as [string, ...string[]];

const ContactFormSchema = z.object({
  name: z.string().min(2, { message: "Name must be at least 2 characters." }),
  email: z.string().email({ message: "Please enter a valid email address." }),
  subject: z.enum(subjectEnumValues, {
    errorMap: () => ({ message: "Please select a valid subject." }),
  }),
  message: z.string().min(10, { message: "Message must be at least 10 characters." }),
});
type ContactFormValues = z.infer<typeof ContactFormSchema>;

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

export function ContactForm() {
  const { toast } = useToast();
  const [state, formAction] = useActionState(submitContactForm, initialState);
  
  const searchParams = useSearchParams();
  const initialSubjectQuery = searchParams.get("subject");
  
  const validSubjects = ["General Inquiry", ...CORE_SERVICES.map(s => s.title)];
  const defaultSubjectValue = initialSubjectQuery && validSubjects.includes(initialSubjectQuery) 
    ? initialSubjectQuery 
    : "General Inquiry";

  const form = useForm<ContactFormValues>({
    resolver: zodResolver(ContactFormSchema),
    defaultValues: { 
      name: "", 
      email: "", 
      subject: defaultSubjectValue as typeof subjectEnumValues[number], 
      message: "" 
    },
  });

  useEffect(() => {
    if (state.message) {
      if (state.success) {
        toast({
          title: "Message Sent!",
          description: state.message,
        });
        form.reset({ 
            name: "", 
            email: "", 
            subject: "General Inquiry", // Reset subject to default
            message: "" 
        });
      } else {
        toast({
          title: "Error",
          description: state.message || "An unexpected error occurred.",
          variant: "destructive",
        });
        if (state.errors?.name && !form.formState.errors.name) form.setError("name", { message: state.errors.name[0] });
        if (state.errors?.email && !form.formState.errors.email) form.setError("email", { message: state.errors.email[0] });
        if (state.errors?.subject && !form.formState.errors.subject) form.setError("subject", { message: state.errors.subject[0] as string});
        if (state.errors?.message && !form.formState.errors.message) form.setError("message", { message: state.errors.message[0] });
      }
    }
  }, [state, toast, form]);
  
  useEffect(() => {
    const currentSubjectQuery = searchParams.get("subject");
    if (currentSubjectQuery && validSubjects.includes(currentSubjectQuery)) {
      form.setValue("subject", currentSubjectQuery as typeof subjectEnumValues[number]);
    } else if (currentSubjectQuery) { 
        form.setValue("subject", "General Inquiry");
    }
  }, [searchParams, form, validSubjects]);


  return (
    <Card className="w-full max-w-2xl shadow-xl">
      <CardHeader>
        <CardTitle className="text-2xl text-primary text-shadow-primary">Send us a message</CardTitle>
        <CardDescription>We'd love to hear from you. Please fill out the form below.</CardDescription>
      </CardHeader>
      <CardContent>
        <Form {...form}>
          <form
            action={formAction}
            onSubmit={form.handleSubmit(() => { /* Client-side validation runs, then action prop takes over */ })}
            className="space-y-6"
          >
            <FormField
              control={form.control}
              name="name"
              render={({ field }) => (
                <FormItem>
                  <FormLabel htmlFor="name">Full Name</FormLabel>
                  <FormControl>
                    <Input id="name" {...field} placeholder="John Doe" className="mt-1" />
                  </FormControl>
                  <FormMessage />
                  {state.errors?.name && !form.formState.errors.name && <p className="text-sm text-destructive mt-1">{state.errors.name[0]}</p>}
                </FormItem>
              )}
            />
            
            <FormField
              control={form.control}
              name="email"
              render={({ field }) => (
                <FormItem>
                  <FormLabel htmlFor="email">Email Address</FormLabel>
                  <FormControl>
                    <Input id="email" type="email" {...field} placeholder="you@example.com" className="mt-1" />
                  </FormControl>
                  <FormMessage />
                  {state.errors?.email && !form.formState.errors.email && <p className="text-sm text-destructive mt-1">{state.errors.email[0]}</p>}
                </FormItem>
              )}
            />
            
            <FormField
              control={form.control}
              name="subject"
              defaultValue={defaultSubjectValue as typeof subjectEnumValues[number]}
              render={({ field }) => (
                <FormItem>
                  <FormLabel htmlFor="subject">Subject</FormLabel>
                  <Select 
                    onValueChange={field.onChange} 
                    value={field.value}
                    defaultValue={defaultSubjectValue as typeof subjectEnumValues[number]}
                  >
                    <FormControl>
                      <SelectTrigger id="subject" className="mt-1">
                        <SelectValue placeholder="Select a subject" />
                      </SelectTrigger>
                    </FormControl>
                    <SelectContent>
                      <SelectItem value="General Inquiry">General Inquiry</SelectItem>
                      {CORE_SERVICES.map(service => (
                        <SelectItem key={service.id} value={service.title}>
                          {service.title}
                        </SelectItem>
                      ))}
                    </SelectContent>
                  </Select>
                  <FormMessage />
                  {state.errors?.subject && !form.formState.errors.subject && <p className="text-sm text-destructive mt-1">{state.errors.subject[0]}</p>}
                </FormItem>
              )}
            />

            <FormField
              control={form.control}
              name="message"
              render={({ field }) => (
                <FormItem>
                  <FormLabel htmlFor="message">Message</FormLabel>
                  <FormControl>
                    <Textarea id="message" {...field} placeholder="Your message here..." rows={5} className="mt-1" />
                  </FormControl>
                  <FormMessage />
                  {state.errors?.message && !form.formState.errors.message && <p className="text-sm text-destructive mt-1">{state.errors.message[0]}</p>}
                </FormItem>
              )}
            />
            <Button type="submit" className="w-full text-lg py-3" size="lg" disabled={form.formState.isSubmitting}>
              {form.formState.isSubmitting ? "Sending..." : "Send Message"}
            </Button>
          </form>
        </Form>
      </CardContent>
    </Card>
  );
}
