"use client";
import React, { useState } from "react";
import "react-phone-number-input/style.css";
import PhoneInput from "react-phone-number-input";
import { useToast } from "@/lib/toast-hook";

export default function ReportContent() {
  const { showLoading, dismissToast, showSuccess, showError } = useToast();
  const [formData, setFormData] = useState({
    name: "",
    emailAddress: "",
    phoneNumber: "",
    subject: "",
    message: "",
    checkbox: false,
  });

  const handleChange = (e) => {
    const { name, value, type, checked } = e.target;
    setFormData((prevState) => ({
      ...prevState,
      [name]: type === "checkbox" ? checked : value,
    }));
  };

  const handlePhoneChange = (value) => {
    setFormData((prevState) => ({
      ...prevState,
      phoneNumber: value,
    }));
  };

  const handleSubmit = async (e) => {
    const loadingToastId = showLoading("Submitting form...");
    e.preventDefault();
    try {
      const response = await fetch("/api/contact-send", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify(formData),
      });

      if (response.ok) {
        dismissToast(loadingToastId);
        showSuccess("Your form has been successfully submitted.");
        document.cookie = `prospectClient=true; path=/; max-age=31536000`;
      } else {
        dismissToast(loadingToastId);
        showError(
          error instanceof Error ? error.message : "Something went wrong"
        );
        throw new Error("Form submission failed");
      }
    } catch (error) {
      console.error("Error:", error);
      dismissToast(loadingToastId);
      showError(
        error instanceof Error ? error.message : "Something went wrong"
      );
    }
  };

  return (
    <div className="contact__form-wrap">
      <h2 className="title">Get In Touch</h2>
      <form id="contact-form" onSubmit={handleSubmit}>
        <div className="row">
          <div className="col-md-6">
            <div className="form-grp">
              <input
                type="text"
                name="name"
                placeholder="Your Name"
                value={formData.name}
                onChange={handleChange}
                required
              />
            </div>
          </div>
          <div className="col-md-6">
            <div className="form-grp">
              <input
                type="text"
                name="emailAddress"
                placeholder="Email Address"
                value={formData.emailAddress}
                onChange={handleChange}
                required
              />
            </div>
          </div>
          <div className="col-md-6">
            <div className="form-grp">
              <PhoneInput
                international
                defaultCountry="US"
                value={formData.phoneNumber}
                onChange={handlePhoneChange}
              />
            </div>
          </div>
          <div className="col-md-6">
            <div className="form-grp">
              <input
                type="text"
                name="subject"
                placeholder="Subject"
                value={formData.subject}
                onChange={handleChange}
                required
              />
            </div>
          </div>
        </div>
        <div className="form-grp">
          <textarea
            name="message"
            placeholder="Write Message"
            value={formData.message}
            onChange={handleChange}
            required
          />
        </div>
        <div className="form-grp checkbox-grp">
          <input
            type="checkbox"
            name="checkbox"
            id="checkbox"
            checked={formData.checkbox}
            onChange={handleChange}
          />
          <label htmlFor="checkbox">
            Save my name, email and phone number for future messages
          </label>
        </div>
        <button type="submit" className="btn">
          Submit Request
        </button>
      </form>
      <p className="ajax-response mb-0" />
    </div>
  );
}
