"use client";

import { useRef } from "react";
import { motion, useInView } from "framer-motion";
import { Button, Input, Textarea } from "@heroui/react";
import { ArrowUpRight } from "lucide-react";
import { zodResolver } from "@hookform/resolvers/zod";
import { Controller, type SubmitHandler, useForm } from "react-hook-form";
import { z } from "zod";

const EASE_OUT_EXPO = [0.16, 1, 0.3, 1] as const;

const containerVariants = {
  hidden: {},
  visible: {
    transition: {
      staggerChildren: 0.1,
      delayChildren: 0.1,
    },
  },
};

const wrapperVariants = {
  hidden: { opacity: 0, y: 40, scale: 0.97 },
  visible: {
    opacity: 1,
    y: 0,
    scale: 1,
    transition: { duration: 0.7, ease: EASE_OUT_EXPO },
  },
};

const headerVariants = {
  hidden: { opacity: 0, y: 20, filter: "blur(6px)" },
  visible: {
    opacity: 1,
    y: 0,
    filter: "blur(0px)",
    transition: { duration: 0.5, ease: EASE_OUT_EXPO },
  },
};

const inputContainerVariants = {
  hidden: {},
  visible: {
    transition: {
      staggerChildren: 0.08,
      delayChildren: 0.2,
    },
  },
};

const inputVariants = {
  hidden: { opacity: 0, y: 20, scale: 0.98 },
  visible: {
    opacity: 1,
    y: 0,
    scale: 1,
    transition: { duration: 0.5, ease: EASE_OUT_EXPO },
  },
};

const buttonVariants = {
  hidden: { opacity: 0, x: 20 },
  visible: {
    opacity: 1,
    x: 0,
    transition: { duration: 0.5, ease: EASE_OUT_EXPO, delay: 0.4 },
  },
};

// Validation schema
const contactFormSchema = z.object({
  name: z.string().min(2, "Name must be at least 2 characters"),
  email: z.string().email("Please enter a valid email address"),
  phone: z.string().min(10, "Please enter a valid phone number"),
  message: z.string().min(10, "Message must be at least 10 characters"),
});

type ContactFormData = z.infer<typeof contactFormSchema>;

export const ContactForm = () => {
  const sectionRef = useRef<HTMLElement | null>(null);
  const isInView = useInView(sectionRef, { once: true, margin: "-80px" });

  // Helper: sanitize phone input
  const sanitizePhone = (v: string) => {
    const only = v.replace(/[^\d+]/g, "");
    const hasLeadingPlus = only.startsWith("+");
    const digits = only.replace(/\D/g, "");
    return (hasLeadingPlus ? "+" : "") + digits;
  };

  const {
    control,
    reset,
    handleSubmit,
    formState: { isSubmitting },
  } = useForm<ContactFormData>({
    defaultValues: {
      name: "",
      email: "",
      phone: "",
      message: "",
    },
    resolver: zodResolver(contactFormSchema),
  });

  const onSubmit: SubmitHandler<ContactFormData> = async (formData) => {
    try {
      await new Promise((resolve) => setTimeout(resolve, 1000));
      console.log("Form data:", formData);
      alert("Message sent successfully! We'll contact you soon.");
      reset();
    } catch (error) {
      console.error("Error sending message:", error);
      alert("Failed to send message. Please try again.");
    }
  };

  return (
    <motion.section
      ref={sectionRef}
      initial="hidden"
      animate={isInView ? "visible" : "hidden"}
      variants={containerVariants}
      className="custom-container mt-5 mb-16 md:mt-10 md:mb-24"
    >
      <motion.div
        variants={wrapperVariants}
        className="rounded-3xl bg-[#F9F9FB] p-6 md:p-8 flex flex-col gap-6"
      >
        <motion.div variants={headerVariants} className="space-y-2">
          <h2 className="h3Text text-primary">Get in Touch</h2>
          <p className="bodyText text-thirdText leading-relaxed">
            Use the contact form below for general inquiries, service requests,
            or booking an appointment to review your fleet.
          </p>
        </motion.div>

        <form onSubmit={handleSubmit(onSubmit)} className="flex flex-col gap-6">
          <motion.div
            variants={inputContainerVariants}
            className="grid md:grid-cols-3 gap-4"
          >
            {/* Name Field */}
            <motion.div variants={inputVariants}>
              <Controller
                name="name"
                control={control}
                render={({ field, fieldState }) => (
                  <Input
                    label="Full Name"
                    variant="bordered"
                    radius="sm"
                    classNames={{
                      label: "smallText",
                      inputWrapper: "bg-white",
                    }}
                    {...field}
                    isInvalid={fieldState?.invalid}
                    errorMessage={fieldState?.error?.message}
                  />
                )}
              />
            </motion.div>

            {/* Email Field */}
            <motion.div variants={inputVariants}>
              <Controller
                name="email"
                control={control}
                render={({ field, fieldState }) => (
                  <Input
                    label="Email Address"
                    type="email"
                    variant="bordered"
                    radius="sm"
                    classNames={{
                      label: "smallText",
                      inputWrapper: "bg-white",
                    }}
                    {...field}
                    isInvalid={fieldState?.invalid}
                    errorMessage={fieldState?.error?.message}
                  />
                )}
              />
            </motion.div>

            {/* Phone Field */}
            <motion.div variants={inputVariants}>
              <Controller
                name="phone"
                control={control}
                render={({ field, fieldState }) => (
                  <Input
                    type="tel"
                    inputMode="tel"
                    dir="ltr"
                    pattern="\+?\d*"
                    label="Phone Number"
                    variant="bordered"
                    radius="sm"
                    classNames={{
                      label: "smallText",
                      inputWrapper: "bg-white",
                    }}
                    value={field.value}
                    onChange={(e) =>
                      field.onChange(sanitizePhone(e.target.value))
                    }
                    onPaste={(e) => {
                      e.preventDefault();
                      const pasted = e.clipboardData.getData("text");
                      field.onChange(sanitizePhone(pasted));
                    }}
                    onKeyDown={(e) => {
                      const allowed = [
                        "Backspace",
                        "Delete",
                        "ArrowLeft",
                        "ArrowRight",
                        "Home",
                        "End",
                        "Tab",
                      ];
                      if (allowed.includes(e.key) || e.ctrlKey || e.metaKey)
                        return;
                      if (/^\d$/.test(e.key)) return;
                      const el = e.currentTarget as HTMLInputElement;
                      const caretAtStart =
                        el.selectionStart === 0 && el.selectionEnd === 0;
                      if (
                        e.key === "+" &&
                        caretAtStart &&
                        !el.value.startsWith("+")
                      )
                        return;
                      e.preventDefault();
                    }}
                    isInvalid={fieldState?.invalid}
                    errorMessage={fieldState?.error?.message}
                  />
                )}
              />
            </motion.div>
          </motion.div>

          {/* Message Field */}
          <motion.div variants={inputVariants}>
            <Controller
              name="message"
              control={control}
              render={({ field, fieldState }) => (
                <Textarea
                  label="Message"
                  minRows={4}
                  variant="bordered"
                  radius="sm"
                  classNames={{ label: "smallText", inputWrapper: "bg-white" }}
                  {...field}
                  isInvalid={fieldState?.invalid}
                  errorMessage={fieldState?.error?.message}
                />
              )}
            />
          </motion.div>

          <motion.div variants={buttonVariants} className="flex justify-end">
            <Button
              type="submit"
              color="primary"
              radius="full"
              className="px-6 hover:bg-[#0A1F2F] primary-transition hover:scale-105 active:scale-95 transition-all duration-300"
              isLoading={isSubmitting}
              isDisabled={isSubmitting}
              endContent={
                !isSubmitting && (
                  <div className="size-6 rounded-full bg-white flex justify-center items-center">
                    <ArrowUpRight className="text-primary size-5" />
                  </div>
                )
              }
            >
              Send Message
            </Button>
          </motion.div>
        </form>
      </motion.div>
    </motion.section>
  );
};
