"use client";

import * as React from "react";
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { z } from "zod";
import { toast } from "sonner";
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 { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Send, Loader2, CheckCircle2 } from "lucide-react";

const schema = z.object({
  name: z.string().min(2, "Please enter your name"),
  phone: z.string().min(6, "Please enter a valid phone number"),
  email: z.string().email("Please enter a valid email").optional().or(z.literal("")),
  service: z.string().optional(),
  subject: z.string().optional(),
  message: z.string().min(10, "Please tell us a bit more (min 10 characters)"),
});

type FormValues = z.infer<typeof schema>;

const SERVICE_OPTIONS = [
  "Industrial & Commercial AC",
  "New AC Installation",
  "AC Repair & Maintenance",
  "Water Chiller Repair",
  "Air Duct Cleaning",
  "Commercial Air Dryer",
  "Water Cooler Repair",
  "Cold Storage Solutions",
  "AMC Contract",
  "AC Sale / Purchase / Exchange",
  "Other",
];

export function ContactForm({ type = "CONTACT" }: { type?: string }) {
  const [submitted, setSubmitted] = React.useState(false);
  const {
    register,
    handleSubmit,
    reset,
    setValue,
    watch,
    formState: { errors, isSubmitting },
  } = useForm<FormValues>({ resolver: zodResolver(schema), defaultValues: { service: "" } });

  const selectedService = watch("service");

  const onSubmit = async (values: FormValues) => {
    try {
      const res = await fetch("/api/leads", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ ...values, type }),
      });
      if (!res.ok) throw new Error("Failed to submit");
      toast.success("Message sent! Our team will get back to you shortly.");
      setSubmitted(true);
      reset();
    } catch (e) {
      toast.error("Something went wrong. Please call us directly.");
    }
  };

  if (submitted) {
    return (
      <div className="text-center py-12 rounded-2xl bg-muted/40 border border-border">
        <div className="grid place-items-center size-14 rounded-full bg-[var(--brand-royal)]/10 text-[var(--brand-royal)] mx-auto mb-4">
          <CheckCircle2 className="size-7" />
        </div>
        <h3 className="text-xl font-bold">Thank You!</h3>
        <p className="mt-2 text-muted-foreground max-w-sm mx-auto">Your message has been received. Our engineering team will contact you within one business day.</p>
        <Button variant="outline" className="mt-5" onClick={() => setSubmitted(false)}>Send another message</Button>
      </div>
    );
  }

  return (
    <form onSubmit={handleSubmit(onSubmit)} className="space-y-5">
      <div className="grid sm:grid-cols-2 gap-4">
        <div className="space-y-1.5">
          <Label htmlFor="name">Full Name *</Label>
          <Input id="name" {...register("name")} placeholder="Your name" />
          {errors.name && <p className="text-xs text-destructive">{errors.name.message}</p>}
        </div>
        <div className="space-y-1.5">
          <Label htmlFor="phone">Phone *</Label>
          <Input id="phone" {...register("phone")} placeholder="03xx-xxxxxxx" />
          {errors.phone && <p className="text-xs text-destructive">{errors.phone.message}</p>}
        </div>
      </div>
      <div className="grid sm:grid-cols-2 gap-4">
        <div className="space-y-1.5">
          <Label htmlFor="email">Email</Label>
          <Input id="email" type="email" {...register("email")} placeholder="you@example.com" />
          {errors.email && <p className="text-xs text-destructive">{errors.email.message}</p>}
        </div>
        <div className="space-y-1.5">
          <Label htmlFor="service">Service Needed</Label>
          <Select value={selectedService} onValueChange={(v) => setValue("service", v)}>
            <SelectTrigger id="service"><SelectValue placeholder="Select a service" /></SelectTrigger>
            <SelectContent>
              {SERVICE_OPTIONS.map((s) => <SelectItem key={s} value={s}>{s}</SelectItem>)}
            </SelectContent>
          </Select>
        </div>
      </div>
      <div className="space-y-1.5">
        <Label htmlFor="subject">Subject</Label>
        <Input id="subject" {...register("subject")} placeholder="Brief subject" />
      </div>
      <div className="space-y-1.5">
        <Label htmlFor="message">Message *</Label>
        <Textarea id="message" rows={5} {...register("message")} placeholder="Tell us about your requirements, facility, timeline..." />
        {errors.message && <p className="text-xs text-destructive">{errors.message.message}</p>}
      </div>
      <Button type="submit" disabled={isSubmitting} className="w-full brand-gradient text-white">
        {isSubmitting ? <><Loader2 className="size-4 mr-2 animate-spin" /> Sending...</> : <><Send className="size-4 mr-2" /> Send Message</>}
      </Button>
    </form>
  );
}
