"use client";

import React, { useState, useEffect } from "react";
import { useRouter } from "next/navigation";
import { apiCall } from "@/utils/callApi";
import {
  MapPin,
  Phone,
  Mail,
  Clock,
  Send,
  CheckCircle,
  AlertCircle,
} from "lucide-react";
import { toast } from "sonner";
import Newsletter from "@/components/frontend-pages/home/Newsletter";

interface FormData {
  name: string;
  email: string;
  phone: string;
  message: string;
}

interface FormErrors {
  name?: string;
  email?: string;
  phone?: string;
  message?: string;
}
interface response {
  success?: boolean;
  data?: any;
  error?: any;
}

export default function ContactPage() {
  const [formData, setFormData] = useState<FormData>({
    name: "",
    email: "",
    phone: "",
    message: "",
  });
  const [loading, setLoading] = useState(false);
  const [success, setSuccess] = useState(false);
  const [errorMessage, setErrorMessage] = useState("");
  const [generalsettings, setGeneralSettings] = useState<any>(null);
  const [validationError, setValidationError] = useState({
    name: null,
    email: null,
    phone: null,
    message: null,
  });

  useEffect(() => {
    const settings = localStorage.getItem("Generalsettings");

    if (settings) {
      setGeneralSettings(JSON.parse(settings));
    }
  }, []);

  const checkValidation = (key: string, value: string) => {
    let error: string | null = null;

    switch (key) {
      case "phone":
        const phoneRegex = /^[6-9]\d{9}$/;

        if (!phoneRegex.test(value)) {
          error = "Invalid Indian phone number";
        }
        break;

      case "name":
        const usernameRegex = /^[A-Za-z][A-Za-z ]{1,49}$/;

        if (value.length < 2 || value.length > 50) {
          error = "Username must be 2–50 characters";
        } else if (!usernameRegex.test(value)) {
          error = "Name must start with a letter and contain only letters";
        }
        break;

      case "message":
        if (value?.trim()?.length < 20) {
          error = "Message must be at of 20 characters";
        } else if (value?.trim()?.length > 1000) {
          error = "Message must be less than 1000 characters";
        }
        break;

      case "email":
        const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;

        if (!emailRegex.test(value)) {
          error = "Invalid email address";
        }
        break;

      default:
        error = null;
    }

    setValidationError((prev) => ({
      ...prev,
      [key]: error,
    }));

    return error;
  };

  const handleChange = (
    e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>,
  ) => {
    const { name } = e.target;
    let { value } = e.target;

    // Name: allow only letters and spaces
    if (name === "name") {
      value = value.replace(/[^a-zA-Z\s]/g, "");
    }

    // Phone: allow only numbers and max 10 digits
    if (name === "phone") {
      value = value.replace(/\D/g, "").slice(0, 10);
    }

    // Message: max 1000 chars
    if (name === "message") {
      value = value.slice(0, 1000);
    }

    setFormData((prev) => ({ ...prev, [name]: value }));
    checkValidation(name, value);

    if (success) {
      setSuccess(false);
      setErrorMessage("");
    }
  };

  const router = useRouter();

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    const { name, phone, email, message } = formData || {};
    if (!name || !phone || !email || !message) {
      toast.error("Empty required fields");
      return;
    }

    const nameInvalid = checkValidation("name", formData.name);
    if (nameInvalid) {
      toast.error(validationError.name);
      return;
    }

    const emailInvalid = checkValidation("email", formData.email);
    if (emailInvalid) {
      toast.error(validationError.email);
      return;
    }

    const phoneInvalid = checkValidation("phone", formData.phone);
    if (phoneInvalid) {
      toast.error(validationError.phone);
      return;
    }

    const messageInvalid = checkValidation("message", formData.message);
    if (messageInvalid) {
      toast.error(validationError.message);
      return;
    }

    try {
      setLoading(true);
      setErrorMessage("");

      const response = await apiCall("/clientapi/contact-us", {
        method: "POST",
        body: {
          name: formData.name.trim(),
          email: formData.email.trim().toLowerCase(),
          phone: formData.phone.trim(),
          message: formData.message.trim(),
        },
      });

      console.log("API Response:", response); // Debug log

      let isSuccess = false;

      if (response) {
        const responseAny = response as any;
        if (responseAny.success || response.data) {
          isSuccess = true;
        } else if (response.data && !response.error) {
          isSuccess = true;
        }
      }

      if (isSuccess) {
        toast.success("Message sent successfully!");
        setFormData({
          name: "",
          email: "",
          phone: "",
          message: "",
        });
        router.push("/thankingyou");
      } else {
        const errorMsg =
          response?.error || "Failed to send message. Please try again.";
        setErrorMessage(errorMsg);
        setTimeout(() => setErrorMessage(""), 5000);
      }
    } catch (error: any) {
      console.error("Contact form error:", error);
      setErrorMessage(
        error?.message || "Failed to send message. Please try again.",
      );
      setTimeout(() => setErrorMessage(""), 5000);
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="">
      {/* Breadcrumb */}
      <section className="breadcrumbcontainer">
        <div className="container mx-auto px-3">
          <ol className="breadcrumb">
            <li className="breadcrumb-item">
              <a href="/">Home</a>
            </li>
            <li className="breadcrumb-item active">Contact Us</li>
          </ol>
        </div>
      </section>

      <section className="contactcontainer py-8 pt-4 md:py-12 md:pt-12">
        <div className="container px-3">
          <div className="-mx-3 flex flex-wrap justify-center xl:-mx-8 2xl:-mx-10">
            {/* Contact Information */}
            <div className="mb-lg-0 mb-6 w-full px-3 sm:w-full md:w-6/12 lg:w-5/12 xl:w-5/12 xl:px-8 2xl:w-5/12 2xl:px-10">
              <div className="h-full rounded-xl border border-[rgba(var(--primary),0.3)] bg-white p-6 md:p-12">
                <div className="section-heading">
                  <h2>Get in Touch</h2>
                </div>
                <div className="space-y-4 md:space-y-8">
                  <div className="relative flex items-center gap-4">
                    <div className="flex h-12 min-w-12 items-center justify-center rounded-[50px] rounded-br-[10px] bg-[rgba(var(--primary),1)] text-white xl:h-14 xl:min-w-14 2xl:h-16 2xl:min-w-16">
                      <MapPin className="h-4 w-4 xl:h-6 xl:w-6 2xl:h-8 2xl:w-8" />
                    </div>
                    <div className="p-0">
                      <h4 className="mb-0 break-all text-base font-semibold uppercase text-[rgba(var(--primary),1)] md:text-lg 2xl:text-xl">
                        Visit Us
                      </h4>
                      <p className="break-all text-sm text-gray-600 2xl:text-base">
                        {generalsettings?.location || ""}
                      </p>
                    </div>
                  </div>

                  <div className="relative flex items-center gap-4">
                    <div className="flex h-12 min-w-12 items-center justify-center rounded-[50px] rounded-br-[10px] bg-[rgba(var(--primary),1)] text-white xl:h-14 xl:min-w-14 2xl:h-16 2xl:min-w-16">
                      <Phone className="h-4 w-4 xl:h-6 xl:w-6 2xl:h-8 2xl:w-8" />
                    </div>
                    <div className="p-0">
                      <h4 className="mb-0 break-all text-base font-semibold uppercase text-[rgba(var(--primary),1)] md:text-lg 2xl:text-xl">
                        Call Us
                      </h4>
                      <p className="break-all text-sm text-gray-600 2xl:text-base">
                        +{generalsettings?.phoneNumber || ""}
                      </p>
                    </div>
                  </div>

                  <div className="relative flex items-center gap-4">
                    <div className="flex h-12 min-w-12 items-center justify-center rounded-[50px] rounded-br-[10px] bg-[rgba(var(--primary),1)] text-white xl:h-14 xl:min-w-14 2xl:h-16 2xl:min-w-16">
                      <Mail className="h-4 w-4 xl:h-6 xl:w-6 2xl:h-8 2xl:w-8" />
                    </div>
                    <div className="p-0">
                      <h4 className="mb-0 text-base font-semibold uppercase text-[rgba(var(--primary),1)] md:text-lg 2xl:text-xl">
                        Email Us
                      </h4>
                      <p className="break-all text-sm text-gray-600 2xl:text-base">
                        {generalsettings?.email || ""}
                      </p>
                    </div>
                  </div>
                </div>
              </div>
            </div>

            {/* Contact Form */}
            <div className="mb-lg-0 mb-4 w-full px-3 sm:w-full md:w-6/12 lg:w-6/12 xl:w-6/12 xl:px-8 2xl:w-6/12 2xl:px-10">
              <div className="p-0">
                {/* Success Message */}
                {success && (
                  <div className="animate-fadeIn mx-auto mb-3 flex max-w-4xl items-center gap-3 rounded-lg border border-green-400 bg-green-50 p-4">
                    <CheckCircle className="text-green-500" size={20} />
                    <p className="text-green-700">
                      Thank you for contacting us! We'll get back to you soon.
                    </p>
                  </div>
                )}

                {/* Error Message */}
                {errorMessage && (
                  <div className="animate-fadeIn mx-auto mb-3 flex max-w-4xl items-center gap-3 rounded-lg border border-red-400 bg-red-50 p-4">
                    <AlertCircle className="text-red-500" size={20} />
                    <p className="text-red-700">{errorMessage}</p>
                  </div>
                )}
                <div className="section-heading">
                  <h2 className="text-xl font-semibold text-gray-800">
                    Send Us a Message
                  </h2>
                  <p>
                    Tell us what you need — our team will reply as soon as
                    possible.
                  </p>
                </div>
                <form onSubmit={handleSubmit} className="space-y-4">
                  <div className="-mx-2 flex flex-wrap xl:-mx-3">
                    <div className="mb-4 w-full px-2 sm:w-full md:w-6/12 lg:w-6/12 xl:w-6/12 xl:px-3 2xl:w-6/12">
                      {/* Name Field */}
                      <div className="form-group">
                        <label className="mb-1 block text-sm font-medium text-gray-700">
                          Full Name <span className="text-red-500">*</span>
                        </label>
                        <input
                          type="text"
                          name="name"
                          value={formData.name}
                          onChange={handleChange}
                          placeholder="Enter your full name"
                          className={`form-control w-full ${
                            validationError.name
                              ? "border-red-500"
                              : "border-gray-300"
                          }`}
                        />
                        {validationError.name && (
                          <p className="mt-1 flex items-center gap-1 text-xs text-red-500">
                            <AlertCircle size={12} /> {validationError.name}
                          </p>
                        )}
                      </div>
                    </div>
                    <div className="mb-4 w-full px-2 sm:w-full md:w-6/12 lg:w-6/12 xl:w-6/12 xl:px-3 2xl:w-6/12">
                      {/* Email Field */}
                      <div className="form-group">
                        <label className="mb-1 block text-sm font-medium text-gray-700">
                          Email Address <span className="text-red-500">*</span>
                        </label>
                        <input
                          type="email"
                          name="email"
                          value={formData.email}
                          onChange={handleChange}
                          placeholder="Enter your email address"
                          className={`form-control w-full ${
                            validationError.email
                              ? "border-red-500"
                              : "border-gray-300"
                          }`}
                        />
                        {validationError.email && (
                          <p className="mt-1 flex items-center gap-1 text-xs text-red-500">
                            <AlertCircle size={12} /> {validationError.email}
                          </p>
                        )}
                      </div>
                    </div>
                    <div className="mb-4 w-full px-2 sm:w-full md:w-full lg:w-full xl:w-full xl:px-3 2xl:w-full">
                      {/* Phone Field */}
                      <div className="form-group">
                        <label className="mb-1 block text-sm font-medium text-gray-700">
                          Phone Number <span className="text-red-500">*</span>
                        </label>
                        <input
                          type="tel"
                          inputMode="numeric"
                          name="phone"
                          value={formData.phone}
                          onChange={handleChange}
                          placeholder="Enter 10-digit mobile number"
                          maxLength={10}
                          className={`form-control w-full ${
                            validationError.phone
                              ? "border-red-500"
                              : "border-gray-300"
                          }`}
                        />
                        {validationError.phone && (
                          <p className="mt-1 flex items-center gap-1 text-xs text-red-500">
                            <AlertCircle size={12} /> {validationError.phone}
                          </p>
                        )}
                      </div>
                    </div>
                    <div className="mb-4 w-full px-2 sm:w-full md:w-full lg:w-full xl:w-full xl:px-3 2xl:w-full">
                      {/* Message Field */}
                      <div className="form-group">
                        <label className="mb-1 block text-sm font-medium text-gray-700">
                          Message <span className="text-red-500">*</span>
                        </label>
                        <textarea
                          name="message"
                          rows={5}
                          value={formData.message}
                          onChange={handleChange}
                          placeholder="Tell us how we can help you..."
                          className={`form-control w-full ${
                            validationError.message
                              ? "border-red-500"
                              : "border-gray-300"
                          }`}
                        />
                        {validationError.message && (
                          <p className="mt-1 flex items-center gap-1 text-xs text-red-500">
                            <AlertCircle size={12} /> {validationError.message}
                          </p>
                        )}
                        <p className="mt-1 text-xs text-gray-400">
                          {formData.message.length}/1000 characters
                        </p>
                      </div>
                    </div>
                  </div>
                  {/* Submit Button */}
                  <button
                    type="submit"
                    disabled={loading}
                    className="theme-btn w-full"
                  >
                    {loading ? (
                      <>
                        <svg
                          className="h-5 w-5 animate-spin"
                          xmlns="http://www.w3.org/2000/svg"
                          fill="none"
                          viewBox="0 0 24 24"
                        >
                          <circle
                            className="opacity-25"
                            cx="12"
                            cy="12"
                            r="10"
                            stroke="currentColor"
                            strokeWidth="4"
                          ></circle>
                          <path
                            className="opacity-75"
                            fill="currentColor"
                            d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"
                          ></path>
                        </svg>
                        Sending...
                      </>
                    ) : (
                      <>
                        <Send size={18} />
                        Send Message
                      </>
                    )}
                  </button>
                </form>
              </div>
            </div>
          </div>
        </div>
      </section>
      <Newsletter />

      <style jsx>{`
        @keyframes fadeIn {
          from {
            opacity: 0;
            transform: translateY(-10px);
          }
          to {
            opacity: 1;
            transform: translateY(0);
          }
        }
        .animate-fadeIn {
          animation: fadeIn 0.3s ease-out;
        }
      `}</style>
    </div>
  );
}
