// app/enquiry/page.jsx
"use client";

import React, { useState, useEffect } from "react";
import Link from "next/link";
import {
  Home,
  ChevronRight,
  Send,
  Mail,
  Phone,
  User,
  FileText,
  CheckCircle,
  AlertCircle,
  Package,
  MapPin,
} from "lucide-react";
import { insertEnquiry } from "@/utils/enquiry";
import { usePathname, useSearchParams } from "next/navigation";

export const metadata = {
  title: "Send Enquiry - Hariom Group | Epoxy Coated Steel Products",
  description:
    "Send your enquiry for Epoxy Coated TMT Bars, Dowel Bars, and other steel products. Get best quotes and offers from Hariom Group.",
  authors: [{ name: "Hariom Group" }],
};

export default function EnquiryPage() {

    const pathname = usePathname();
  const searchParams = useSearchParams();

  const [formData, setFormData] = useState({
    fullname: "",
    email: "",
    mobile: "",
    product: "",
    city: "",
    remark: "",
    captcha: "",
    website: "",
  });
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [submitStatus, setSubmitStatus] = useState(null);
  const [captchaValue, setCaptchaValue] = useState(null);

  // Generate random CAPTCHA on component mount
  useEffect(() => {
    generateCaptcha();
  }, []);

  const generateCaptcha = () => {
    const num1 = Math.floor(Math.random() * 10);
    const num2 = Math.floor(Math.random() * 10);
    setCaptchaValue({ num1, num2, result: num1 + num2 });
  };

  const products = [
    "Select Product",
    "Epoxy Coated Dowel Bars",
    "Epoxy Coated Reinforcement Bars",
    "Epoxy Coated TMT Bars",
    "Fusion Bonded Epoxy Coated TMT Bars",
    "Fusion Bonded Epoxy Coated Dowel Bar",
    "Dowel Bars",
    "Mild Steel Dowel Bars",
    "PVC Coated Binding Wires",
    "MS Binding Wires",
    "GI Binding Wires",
  ];

  const handleChange = (e) => {
    setFormData({
      ...formData,
      [e.target.name]: e.target.value,
    });
  };

  const validateContactInfo = () => {
    const errors = {};
    const hasEmail = formData.email && formData.email.trim() !== "";
    const hasPhone = formData.mobile && formData.mobile.trim() !== "";

    if (!hasEmail && !hasPhone) {
      errors.contact = "Please provide either Email Address or Mobile Number";
    }

    if (hasEmail) {
      const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
      if (!emailRegex.test(formData.email)) {
        errors.email = "Please enter a valid email address";
      }
    }

    if (hasPhone) {
      const mobileRegex = /^\d{10}$/;
      if (!mobileRegex.test(formData.mobile)) {
        errors.mobile = "Please enter a valid 10-digit mobile number";
      }
    }

    return errors;
  };

  const handleSubmit = async (e) => {
    e.preventDefault();
    setIsSubmitting(true);
    setSubmitStatus(null);

      const fullPageUrl =
        typeof window !== "undefined"
          ? window.location.href 
          : pathname;

    // 🔥 HONEYPOT CHECK - If this field has any value, it's a bot
    if (formData.website) {
      console.log("Bot detected - form rejected");
      // Return success message to bot (they won't know it was rejected)
      setSubmitStatus({
        type: "success",
        message: "Thank you! Our team will get back to you within 24 hours.",
      });
      setIsSubmitting(false);
      // Clear form
      setFormData({
        fullname: "",
        email: "",
        mobile: "",
        product: "",
        remark: "",
        city: "",
        captcha: "",
        website: "",
      });
      generateCaptcha();
      return; // Stop execution here
    }

    // Validate CAPTCHA
    const userCaptcha = parseInt(formData.captcha);
    if (userCaptcha !== captchaValue?.result) {
      setSubmitStatus({
        type: "error",
        message: "Invalid CAPTCHA. Please try again.",
      });
      setIsSubmitting(false);
      generateCaptcha();
      setFormData({ ...formData, captcha: "" });
      return;
    }

    // Validate required fields (name, product, remark)
    if (!formData.fullname || !formData.product || !formData.remark) {
      setSubmitStatus({
        type: "error",
        message: "Please fill in all required fields (Name, Product, Message).",
      });
      setIsSubmitting(false);
      return;
    }

    // Check if either email OR mobile is provided
    const hasEmail = formData.email && formData.email.trim() !== "";
    const hasMobile = formData.mobile && formData.mobile.trim() !== "";

    if (!hasEmail && !hasMobile) {
      setSubmitStatus({
        type: "error",
        message: "Please provide either Email Address or Mobile Number.",
      });
      setIsSubmitting(false);
      return;
    }

    // Validate email format if provided
    if (hasEmail) {
      const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
      if (!emailRegex.test(formData.email)) {
        setSubmitStatus({
          type: "error",
          message: "Please enter a valid email address.",
        });
        setIsSubmitting(false);
        return;
      }
    }

    // Validate mobile number if provided (10 digits)
    if (hasMobile) {
      const mobileRegex = /^\d{10}$/;
      if (!mobileRegex.test(formData.mobile)) {
        setSubmitStatus({
          type: "error",
          message: "Please enter a valid 10-digit mobile number.",
        });
        setIsSubmitting(false);
        return;
      }
    }

    // Get userId from localStorage
    const userId = localStorage.getItem("userId");

    // Prepare data for API
    const enquiryData = {
      fullname: formData.fullname,
      email: formData.email || "",
      mobile: formData.mobile || "",
      product: formData.product,
      city: formData.city,
      cookieUser: userId,
      remark: formData.remark,
      website: formData.website,
      page_url: fullPageUrl,
    };

    try {
      const response = await insertEnquiry(enquiryData);

      setSubmitStatus({
        type: "success",
        message: "Thank you! Our team will get back to you within 24 hours.",
      });

      // Reset form after successful submission
      setFormData({
        fullname: "",
        email: "",
        mobile: "",
        product: "",
        remark: "",
        city: "",
        captcha: "",
        website: "",
      });
      generateCaptcha();
    } catch (error) {
      setSubmitStatus({
        type: "error",
        message:
          error.message || "Something went wrong. Please try again later.",
      });
    } finally {
      setIsSubmitting(false);
    }
  };

  return (
    <div className="w-full bg-white">
      {/* Hero Section */}
      <div className="relative bg-gray-900 text-white py-10 lg:py-10 overflow-hidden">
        <div className="absolute inset-0 bg-gray-900 bg-linear-to-r from-red-900/20 to-transparent" />
        <div className="relative max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
          <div className="flex items-center gap-2 text-sm mb-6 md:mt-20">
            <Link
              href="/"
              className="text-gray-400 hover:text-white transition-colors flex items-center gap-1"
            >
              <Home className="w-4 h-4" />
              Home
            </Link>
            <ChevronRight className="w-4 h-4 text-gray-500" />
            <span className="text-white">Send Enquiry</span>
          </div>
          <h2 className="text-3xl md:text-4xl lg:text-5xl font-bold mb-4">
            Send <span className="text-red-500">Enquiry</span>
          </h2>
          <p className="text-gray-300 text-sm md:text-base max-w-2xl">
            Get best quotes and offers for our premium quality steel products
          </p>
        </div>
      </div>

      {/* Enquiry Form Section */}
      <div className="bg-white py-12 lg:py-16">
        <div className="max-w-4xl mx-auto px-4 sm:px-6 lg:px-8">
          {/* Success/Error Message */}
          {submitStatus && (
            <div
              className={`mb-6 p-4 rounded-lg flex items-center gap-3 ${
                submitStatus.type === "success"
                  ? "bg-green-50 border border-green-200 text-green-700"
                  : "bg-red-50 border border-red-200 text-red-700"
              }`}
            >
              {submitStatus.type === "success" ? (
                <CheckCircle className="w-5 h-5 flex-shrink-0" />
              ) : (
                <AlertCircle className="w-5 h-5 flex-shrink-0" />
              )}
              <p className="text-sm">{submitStatus.message}</p>
            </div>
          )}

          {/* Form */}
          <form onSubmit={handleSubmit} className="space-y-6">
            {/* Full Name */}
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-2">
                Full Name <span className="text-red-500">*</span>
              </label>
              <div className="relative">
                <User className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400" />
                <input
                  type="text"
                  name="fullname"
                  value={formData.fullname}
                  onChange={handleChange}
                  required
                  className="w-full pl-10 pr-4 py-2.5 border border-gray-300 focus:border-red-500 focus:ring-1 focus:ring-red-500 outline-none transition-colors"
                  placeholder="Enter your full name"
                />
              </div>
            </div>

            {/* Email */}
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-2">
                Email Address
              </label>
              <div className="relative">
                <Mail className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400" />
                <input
                  type="email"
                  name="email"
                  value={formData.email}
                  onChange={handleChange}
                  className="w-full pl-10 pr-4 py-2.5 border border-gray-300 focus:border-red-500 focus:ring-1 focus:ring-red-500 outline-none transition-colors"
                  placeholder="your@email.com"
                />
              </div>
            </div>

            {/* Mobile Number */}
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-2">
                Mobile Number
              </label>
              <div className="relative">
                <Phone className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400" />
                <input
                  type="tel"
                  name="mobile"
                  value={formData.mobile}
                  onChange={handleChange}
                  maxLength="10"
                  className="w-full pl-10 pr-4 py-2.5 border border-gray-300 focus:border-red-500 focus:ring-1 focus:ring-red-500 outline-none transition-colors"
                  placeholder="9876543210"
                />
              </div>
            </div>

            <div>
              <label className="block text-sm font-medium text-gray-700 mb-2">
                City <span className="text-red-500">*</span>
              </label>
              <div className="relative">
                <MapPin className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400" />
                <input
                  type="text"
                  name="city"
                  value={formData.city}
                  onChange={handleChange}
                  required
                  className="w-full pl-10 pr-4 py-2.5 border border-gray-300 focus:border-red-500 focus:ring-1 focus:ring-red-500 outline-none transition-colors"
                  placeholder="Enter your city"
                />
              </div>
            </div>

            {/* Product Selection */}
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-2">
                Product Interest <span className="text-red-500">*</span>
              </label>
              <div className="relative">
                <Package className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400" />
                <select
                  name="product"
                  value={formData.product}
                  onChange={handleChange}
                  required
                  className="w-full pl-10 pr-4 py-2.5 border border-gray-300 focus:border-red-500 focus:ring-1 focus:ring-red-500 outline-none transition-colors appearance-none bg-white"
                >
                  {products.map((product, idx) => (
                    <option
                      key={idx}
                      value={product === "Select Product" ? "" : product}
                    >
                      {product}
                    </option>
                  ))}
                </select>
              </div>
            </div>

            {/* Message/Requirements */}
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-2">
                Message / Requirements <span className="text-red-500">*</span>
              </label>
              <div className="relative">
                <FileText className="absolute left-3 top-3 w-4 h-4 text-gray-400" />
                <textarea
                  name="remark"
                  value={formData.remark}
                  onChange={handleChange}
                  required
                  rows="5"
                  className="w-full pl-10 pr-4 py-2.5 border border-gray-300 focus:border-red-500 focus:ring-1 focus:ring-red-500 outline-none transition-colors resize-none"
                  placeholder="Tell us about your requirements, quantity, delivery location, etc."
                />
              </div>
            </div>

            <div className="hidden">
              <label htmlFor="website">Leave this field empty</label>
              <input
                type="text"
                name="website"
                id="website"
                value={formData.website}
                onChange={handleChange}
                tabIndex="-1"
                autoComplete="off"
              />
            </div>

            {/* CAPTCHA */}
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-2">
                CAPTCHA <span className="text-red-500">*</span>
              </label>
              <div className="flex items-center gap-3">
                <div className="bg-gray-100 p-3 rounded-lg border border-gray-300">
                  <span className="text-lg font-bold text-gray-800">
                    {captchaValue?.num1} + {captchaValue?.num2} = ?
                  </span>
                </div>
                <input
                  type="text"
                  name="captcha"
                  value={formData.captcha}
                  onChange={handleChange}
                  required
                  className="w-24 px-3 py-2.5 border border-gray-300 focus:border-red-500 focus:ring-1 focus:ring-red-500 outline-none transition-colors text-center"
                  placeholder="?"
                />
                <button
                  type="button"
                  onClick={generateCaptcha}
                  className="text-sm text-red-600 hover:text-red-700"
                >
                  Refresh
                </button>
              </div>
            </div>

            {/* Submit Button */}
            <button
              type="submit"
              disabled={isSubmitting}
              className="w-full inline-flex items-center justify-center gap-2 px-6 py-3 bg-red-600 text-white text-sm font-semibold hover:bg-red-700 transition-colors disabled:opacity-70 disabled:cursor-not-allowed"
            >
              {isSubmitting ? (
                <>
                  <div className="w-4 h-4 border-2 border-white border-t-transparent rounded-full animate-spin" />
                  Sending Enquiry...
                </>
              ) : (
                <>
                  <Send className="w-4 h-4" />
                  Submit Enquiry
                </>
              )}
            </button>
          </form>
        </div>
      </div>
    </div>
  );
}
