All files / components/forms contact-form.tsx

34.28% Statements 12/35
28.57% Branches 4/14
60% Functions 3/5
35.29% Lines 12/34

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 1961x           1x   1x 6x                 6x 6x   6x 2x     6x                                                                                                                                                                                 6x                                                       1x 1x                                                                                                        
"use client";
import React, { useState } from "react";
import { Container } from "./container";
 
import { Button } from "@/components/ui/button";
 
const adminEmail = process.env.NEXT_PUBLIC_ADMIN_EMAIL || "amitnandileo@gmail.com";
 
export const ContactForm = () => {
  const [formData, setFormData] = useState({
    name: "",
    email: "",
    phone: "",
    message: "",
    referralSource: "",
    honeypot: "", // Honeypot field
  });
 
  const [loading, setLoading] = useState(false);
  const [success, setSuccess] = useState<string | null>(null);
 
  const handleChange = (e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement>) => {
    setFormData({ ...formData, [e.target.name]: e.target.value });
  };
 
  const handleSubmit = async (e: React.FormEvent<HTMLFormElement>) => {
    e.preventDefault();
 
    // Check honeypot field
    if (formData.honeypot) {
      console.warn("Spam detected! Submission blocked.");
      return; // Stop form submission
    }
 
    setLoading(true);
 
    try {
      console.log(process.env.NEXT_PUBLIC_STRAPI_BASE_URL);
      // Save form data to backend
      const response = await fetch(
        `${process.env.NEXT_PUBLIC_STRAPI_BASE_URL}/api/contact-form-submissions`,
        {
          method: "POST",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify({
            data: {
              name: formData.name,
              email: formData.email,
              phone: formData.phone,
              referralSource: formData.referralSource,
              message: formData.message,
            },
          }),
        });
 
      if (!response.ok) {
        throw new Error("Failed to save message");
      }
 
      // Send confirmation email to user
      const emailResponse = await fetch(`/api/email`, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          to: formData.email,
          subject: "Thank You for contacting Bitmutex",
          message: `Hi <b>${formData.name}</b>,<br><br>
          Thank you for reaching out to Bitmutex Technologies! We have received your message and will get back to you as soon as possible.<br><br>
          In the meantime, feel free to download our brochure <a href="https://bitmutex.in/brochure">here</a>.<br><br>
          Best Regards,<br>
          Team Bitmutex `,
        }),
      });
 
      if (!emailResponse.ok) {
        throw new Error("Failed to send email to user");
      }
 
      // Delay before sending admin email
      await new Promise((resolve) => setTimeout(resolve, 2000));
 
      // Send email notification to admin
      const emailResponseAdmin = await fetch(`/api/email`, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          to: adminEmail,
          subject: "New Contact Form Submission",
          message: `πŸš€ New Contact Form Submission πŸš€ <br>
          πŸ“Œ **Name:** ${formData.name}<br>
          πŸ“Œ **Email:** ${formData.email}<br>
          πŸ“Œ **Phone:** ${formData.phone}<br>
          πŸ“Œ **Referral Source:** ${formData.referralSource}<br>
          πŸ“Œ **Message:**<br>${formData.message}<br>
          πŸ” Please review and take necessary action.<br>
          Best Regards,<br> BitMutex Bot πŸ€–`,
        }),
      });
 
      if (!emailResponseAdmin.ok) {
        throw new Error("Failed to send email to admin");
      }
 
      setSuccess("Your submission is successful!");
      setFormData({ name: "", email: "", phone: "", referralSource: "", message: "", honeypot: "" });
 
    } catch (error) {
      console.error(error);
      setSuccess("Oops! Something went wrong");
    }
 
    setLoading(false);
  };
 
  return (
    <Container className="h-full max-w-lg mx-auto flex flex-col ">
      <h1 className="text-lg md:text-xl my-4 text-slate-800 dark:text-slate-400">We won’t spam you.</h1>
      <form className="w-full my-4" onSubmit={handleSubmit}>
        <input
          type="text"
          name="name"
          placeholder="Your Name"
          value={formData.name}
          onChange={handleChange}
          required
          className="h-10 pl-4 w-full mb-4 rounded-md text-sm bg-charcoal border border-neutral-400 text-slate-600 dark:text-slate-200 placeholder-neutral-500 outline-none focus:ring-2 focus:ring-neutral-800 dark:focus:ring-neutral-300"
        />
        <input
          type="email"
          name="email"
          placeholder="Your Email"
          value={formData.email}
          onChange={handleChange}
          required
          className="h-10 pl-4 w-full mb-4 rounded-md text-sm bg-charcoal border border-neutral-400 text-slate-600 dark:text-slate-200 placeholder-neutral-500 outline-none focus:ring-2 focus:ring-neutral-800 dark:focus:ring-neutral-300"
        />
        <input
          type="tel"
          name="phone"
          placeholder="Your Contact Number"
          value={formData.phone}
          onChange={(e) => {
            const numericValue = e.target.value.replace(/\D/g, ""); // Remove non-numeric characters
            setFormData({ ...formData, phone: numericValue });
          }}
          required
          inputMode="numeric"
          pattern="[0-9]*"
          maxLength={10}
          className="h-10 pl-4 w-full mb-4 rounded-md text-sm bg-charcoal border border-neutral-400  text-slate-600 dark:text-slate-200 placeholder-neutral-500 outline-none focus:ring-2 focus:ring-neutral-800 dark:focus:ring-neutral-300"
        />
 
        <label htmlFor="referralSource" className="block mb-2 text-sm font-medium text-slate-600 dark:text-slate-400">Where did you hear about us?</label>
        <select
          id="referralSource"
          name="referralSource"
          value={formData.referralSource}
          onChange={handleChange}
          required
          className="h-10 pl-4 w-full mb-4 rounded-md text-sm bg-charcoal border border-neutral-400 text-slate-600 dark:text-slate-200 placeholder-neutral-500 outline-none focus:ring-2 focus:ring-neutral-800 dark:focus:ring-neutral-300"
        >
 
          <option value="google">Google</option>
          <option value="social_media">Social Media</option>
          <option value="friend">Friend</option>
          <option value="advertisement">Advertisement</option>
          <option value="other">Other</option>
        </select>
        <textarea
          name="message"
          placeholder="Your Message"
          value={formData.message}
          onChange={handleChange}
          required
          className="h-28 pl-4 pt-2 w-full mb-4 rounded-md text-sm bg-charcoal border border-neutral-400 text-slate-600 dark:text-slate-200  placeholder-neutral-500 outline-none focus:ring-2 focus:ring-neutral-800 dark:focus:ring-neutral-300"
        />
 
        {/* Honeypot Field */}
        <input
          type="text"
          name="honeypot"
          value={formData.honeypot}
          onChange={handleChange}
          className="hidden"
          autoComplete="off"
          aria-hidden="true"
        />
 
        <Button variant="default" type="submit" className="w-full py-3" disabled={loading}>
          <span className="text-sm">{loading ? "Sending..." : "Send Message"}</span>
        </Button>
      </form>
      {success && <p className="text-sm text-green-500">{success}</p>}
    </Container>
  );
};