"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: string | null;
    email: string | null;
    phone: string | null;
    message: string | null;
  }>({
    name: null,
    email: null,
    phone: null,
    message: null,
  });

  // Track touched fields
  const [touched, setTouched] = useState({
    name: false,
    email: false,
    phone: false,
    message: false,
  });

  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": {
        if (!value) {
          error = "Phone number is required";
        } else {
          const phoneRegex = /^[6-9]\d{9}$/;
          if (!phoneRegex.test(value)) {
            error = "Invalid Indian phone number (must start with 6-9)";
          }
        }
        break;
      }

      case "name": {
        if (!value || value.trim() === "") {
          error = "Name is required";
        } else {
          const usernameRegex = /^[A-Za-z][A-Za-z ]{1,49}$/;
          if (value.length < 2 || value.length > 50) {
            error = "Name 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 || value.trim() === "") {
          error = "Message is required";
        } else if (value.trim().length < 20) {
          error = "Message must be at least 20 characters";
        } else if (value.trim().length > 1000) {
          error = "Message must be less than 1000 characters";
        }
        break;
      }

      case "email": {
        if (!value || value.trim() === "") {
          error = "Email is required";
        } else {
          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 handleFieldChange = (key: string, value: string) => {
    let processedValue = value;

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

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

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

    setFormData((prev) => ({ ...prev, [key]: processedValue }));
    setTouched((prev) => ({ ...prev, [key]: true }));
    checkValidation(key, processedValue);

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

  const handleBlur = (key: string) => {
    setTouched((prev) => ({ ...prev, [key]: true }));
    checkValidation(key, formData[key as keyof FormData]);
  };

  const validateAllFields = () => {
    const fields = [
      { key: "name", label: "Name" },
      { key: "email", label: "Email" },
      { key: "phone", label: "Phone" },
      { key: "message", label: "Message" },
    ];

    let hasError = false;

    fields.forEach(({ key }) => {
      const value = formData[key as keyof FormData];
      const error = checkValidation(key, value);
      if (error) {
        hasError = true;
      }
      setTouched((prev) => ({ ...prev, [key]: true }));
    });

    return hasError;
  };

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

  const router = useRouter();

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();

    // Validate all fields
    const hasError = validateAllFields();

    if (hasError) {
      toast.error("Please fill all required fields correctly");
      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);

      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: "",
        });
        setTouched({
          name: false,
          email: false,
          phone: false,
          message: false,
        });
        setValidationError({
          name: null,
          email: null,
          phone: null,
          message: null,
        });
        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);
    }
  };

  const getInputClassName = (fieldName: keyof FormData) => {
    const hasError = touched[fieldName] && validationError[fieldName];
    return `w-full rounded-lg border p-3 transition-all duration-200 focus:outline-none focus:ring-2 ${
      hasError
        ? "border-red-500 focus:border-red-500 focus:ring-red-200"
        : "border-gray-300 focus:border-[rgba(var(--primary),1)] focus:ring-[rgba(var(--primary),0.2)]"
    }`;
  };

  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">
                {/* 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">
                    {/* Name Field */}
                    <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">
                      <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}
                          onBlur={() => handleBlur("name")}
                          placeholder="Enter your full name"
                          className={getInputClassName("name")}
                        />
                        {touched.name && validationError.name && (
                          <p className="mt-1 flex items-center gap-1 text-xs text-red-500">
                            <AlertCircle size={12} /> {validationError.name}
                          </p>
                        )}
                      </div>
                    </div>

                    {/* Email Field */}
                    <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">
                      <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}
                          onBlur={() => handleBlur("email")}
                          placeholder="Enter your email address"
                          className={getInputClassName("email")}
                        />
                        {touched.email && validationError.email && (
                          <p className="mt-1 flex items-center gap-1 text-xs text-red-500">
                            <AlertCircle size={12} /> {validationError.email}
                          </p>
                        )}
                      </div>
                    </div>

                    {/* Phone Field */}
                    <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">
                      <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}
                          onBlur={() => handleBlur("phone")}
                          placeholder="Enter 10-digit mobile number"
                          maxLength={10}
                          className={getInputClassName("phone")}
                        />
                        {touched.phone && validationError.phone && (
                          <p className="mt-1 flex items-center gap-1 text-xs text-red-500">
                            <AlertCircle size={12} /> {validationError.phone}
                          </p>
                        )}
                        <p className="mt-1 text-xs text-gray-400">
                          Enter 10-digit Indian phone number (e.g., 9876543210)
                        </p>
                      </div>
                    </div>

                    {/* Message Field */}
                    <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">
                      <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}
                          onBlur={() => handleBlur("message")}
                          placeholder="Tell us how we can help you..."
                          className={getInputClassName("message")}
                        />
                        {touched.message && 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>
  );
}