"use client";

import { motion } from "framer-motion";
import { useState } from "react";
import SocialLinks from "@/components/SocialLinks";
import ReCaptcha from "@/components/ui/ReCaptcha";
import Toast, { useToast } from "@/components/ui/Toast";
import { useSectionVisibility } from "@/hooks/useIntersectionObserver";
import { useApiQuery } from "@/hooks/api/useApiQuery";
import type { ContactCard } from "@/types/models";

declare global {
  interface Window {
    gtag: (
      command: string,
      action: string,
      params?: {
        event_category?: string;
        event_label?: string;
        value?: number;
        [key: string]: any;
      },
    ) => void;
  }
}

export default function ContactUsSection() {
  const isVisible = useSectionVisibility("contact-section");
  const [formData, setFormData] = useState({
    name: "",
    email: "",
    subject: "",
    message: "",
  });
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [recaptchaToken, setRecaptchaToken] = useState("");
  const { toast, showToast, hideToast } = useToast();

  const { data: contactCardsData } = useApiQuery<ContactCard[]>("/api/contact-cards", {
    cacheTTL: 5 * 60 * 1000, // 5 minutes
  });
  
  const { data: googleSettings } = useApiQuery<{ recaptchaSiteKey: string }>("/api/google-settings", {
    cacheTTL: 5 * 60 * 1000, // 5 minutes
  });
  
  const contactCards = contactCardsData ?? [];
  const recaptchaSiteKey = googleSettings?.recaptchaSiteKey || "";

  const handleRecaptchaVerify = (token: string) => {
    setRecaptchaToken(token);
  };

  const handleRecaptchaError = (error: Error) => {
    console.error("reCAPTCHA error:", error);
    showToast("Failed to verify reCAPTCHA. Please try again.", "error");
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!recaptchaToken) {
      showToast("Please wait while we verify you are human...", "error");
      return;
    }
    setIsSubmitting(true);

    try {
      const response = await fetch("/api/contact", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
          "X-Requested-With": "XMLHttpRequest",
        },
        body: JSON.stringify({
          ...formData,
          recaptchaToken,
        }),
      });

      const data = await response.json();

      if (!response.ok) {
        throw new Error(data.error || "Failed to send message");
      }

      // Track successful form submission
      if (typeof window !== "undefined" && window.gtag) {
        window.gtag("event", "form_submission", {
          event_category: "Contact",
          event_label: "Contact Form",
          value: 1,
        });
      }

      showToast("Message sent successfully! We will get back to you soon.", "success");
      setFormData({ name: "", email: "", subject: "", message: "" });
      setRecaptchaToken(""); // Reset token after successful submission
    } catch (error) {
      console.error("Error sending message:", error);
      showToast(
        error instanceof Error ? error.message : "Failed to send message. Please try again.",
        "error",
      );
    } finally {
      setIsSubmitting(false);
    }
  };

  const handleInputChange = (e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>) => {
    const { name, value } = e.target;
    setFormData((prev) => ({ ...prev, [name]: value }));
  };

  return (
    <section
      id="contact-section"
      className="relative py-24 overflow-hidden bg-[#020c13]"
      aria-label="Contact us section"
    >
      {/* Gradient border that fades from right to left */}
      <div className="absolute bottom-0 right-0 w-[85%] h-[1px] bg-gradient-to-l from-[#B87333] to-transparent" />
      {/* Background Elements */}
      <div className="absolute inset-0">
        <div className="absolute inset-0 opacity-5"></div>
      </div>
      <div className="max-w-7xl mx-auto px-4 relative z-10">
        {/* Section Header */}
        <motion.div
          initial={{ opacity: 0, y: 20 }}
          animate={isVisible ? { opacity: 1, y: 0 } : {}}
          transition={{ duration: 0.6 }}
          className="text-center mb-16"
        >
          <h2 className="text-4xl md:text-5xl font-bold text-white mb-4">Get in Touch</h2>
          <div className="w-20 h-1 bg-gradient-to-r from-[#B87333] to-[#ff914d] mx-auto rounded-full" />
        </motion.div>

        {/* Contact Cards */}
        <div className="grid grid-cols-1 md:grid-cols-2 gap-8 max-w-4xl mx-auto mb-16">
          {contactCards.map((card, index) => (
            <motion.div
              key={card.id}
              initial={{ opacity: 0, x: index === 0 ? -30 : 30 }}
              animate={isVisible ? { opacity: 1, x: 0 } : {}}
              transition={{ duration: 0.6, delay: 0.2 + index * 0.2 }}
              className="bg-[#030f18] p-8 rounded-md shadow-md hover:shadow-lg transition-shadow duration-300 border border-[#B87333]/20 hover:border-[#B87333]/40"
            >
              <h3 className="text-2xl font-bold text-white mb-4">{card.name}</h3>
              <div className="space-y-4">
                <a
                  href={`tel:${card.phone}`}
                  className="flex items-center text-gray-300 hover:text-[#B87333] transition-colors"
                >
                  <svg className="w-5 h-5 mr-3" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path
                      strokeLinecap="round"
                      strokeLinejoin="round"
                      strokeWidth={2}
                      d="M3 5a2 2 0 012-2h3.28a1 1 0 01.948.684l1.498 4.493a1 1 0 01-.502 1.21l-2.257 1.13a11.042 11.042 0 005.516 5.516l1.13-2.257a1 1 0 011.21-.502l4.493 1.498a1 1 0 01.684.949V19a2 2 0 01-2 2h-1C9.716 21 3 14.284 3 6V5z"
                    />
                  </svg>
                  {card.phone}
                </a>
                <a
                  href={`mailto:${card.email}`}
                  className="flex items-center text-gray-300 hover:text-[#B87333] transition-colors"
                >
                  <svg className="w-5 h-5 mr-3" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path
                      strokeLinecap="round"
                      strokeLinejoin="round"
                      strokeWidth={2}
                      d="M3 8l7.89 5.26a2 2 0 002.22 0L21 8M5 19h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v10a2 2 0 002 2z"
                    />
                  </svg>
                  {card.email}
                </a>
              </div>
            </motion.div>
          ))}
        </div>

        {/* Contact Form (only one, accessible, modern) */}
        <motion.div
          initial={{ opacity: 0, y: 20 }}
          animate={isVisible ? { opacity: 1, y: 0 } : {}}
          transition={{ duration: 0.6, delay: 0.6 }}
          className="max-w-4xl mx-auto"
        >
          {toast && (
            <div aria-live="polite" role="status">
              <Toast message={toast.message} type={toast.type} onClose={hideToast} />
            </div>
          )}
          <div className="bg-[#030f18] p-8 rounded-md shadow-md border border-[#B87333]/20">
            <form onSubmit={handleSubmit} className="space-y-6" aria-labelledby="contact-heading">
              <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                <div>
                  <label htmlFor="name" className="block text-sm font-medium text-gray-300 mb-2">
                    Your Name
                  </label>
                  <input
                    type="text"
                    id="name"
                    name="name"
                    value={formData.name}
                    onChange={handleInputChange}
                    className="w-full px-4 py-3 rounded-md border border-[#B87333]/20 focus:ring-2 focus:ring-[#B87333] focus:border-[#B87333] focus:shadow-[0_0_0_3px_rgba(184,115,51,0.15)] transition-all placeholder-gray-500 text-white bg-[#020c13]"
                    placeholder="John Doe"
                    required
                    maxLength={100}
                    aria-required="true"
                    aria-invalid={!formData.name ? "true" : "false"}
                  />
                </div>
                <div>
                  <label htmlFor="email" className="block text-sm font-medium text-gray-300 mb-2">
                    Email Address
                  </label>
                  <input
                    type="email"
                    id="email"
                    name="email"
                    value={formData.email}
                    onChange={handleInputChange}
                    className="w-full px-4 py-3 rounded-md border border-[#B87333]/20 focus:ring-2 focus:ring-[#B87333] focus:border-[#B87333] focus:shadow-[0_0_0_3px_rgba(184,115,51,0.15)] transition-all placeholder-gray-500 text-white bg-[#020c13]"
                    placeholder="john@example.com"
                    required
                    maxLength={254}
                    aria-required="true"
                    aria-invalid={!formData.email ? "true" : "false"}
                  />
                </div>
              </div>
              <div>
                <label htmlFor="subject" className="block text-sm font-medium text-gray-300 mb-2">
                  Subject
                </label>
                <input
                  type="text"
                  id="subject"
                  name="subject"
                  value={formData.subject}
                  onChange={handleInputChange}
                  className="w-full px-4 py-3 rounded-md border border-[#B87333]/20 focus:ring-2 focus:ring-[#B87333] focus:border-[#B87333] focus:shadow-[0_0_0_3px_rgba(184,115,51,0.15)] transition-all placeholder-gray-500 text-white bg-[#020c13]"
                  placeholder="How can we help you?"
                  required
                  maxLength={200}
                  aria-required="true"
                  aria-invalid={!formData.subject ? "true" : "false"}
                />
              </div>
              <div>
                <label htmlFor="message" className="block text-sm font-medium text-gray-300 mb-2">
                  Message
                </label>
                <textarea
                  id="message"
                  name="message"
                  value={formData.message}
                  onChange={handleInputChange}
                  rows={4}
                  className="w-full px-4 py-3 rounded-md border border-[#B87333]/20 focus:ring-2 focus:ring-[#B87333] focus:border-[#B87333] focus:shadow-[0_0_0_3px_rgba(184,115,51,0.15)] transition-all placeholder-gray-500 text-white bg-[#020c13] resize-none"
                  placeholder="Tell us about your project..."
                  required
                  maxLength={5000}
                  aria-required="true"
                  aria-invalid={!formData.message ? "true" : "false"}
                ></textarea>
                <p className="mt-2 text-xs text-gray-500">
                  This site is protected by reCAPTCHA and the Google{" "}
                  <a
                    href="https://policies.google.com/privacy"
                    target="_blank"
                    rel="noopener noreferrer"
                    className="text-[#B87333] hover:underline"
                  >
                    Privacy Policy
                  </a>{" "}
                  and{" "}
                  <a
                    href="https://policies.google.com/terms"
                    target="_blank"
                    rel="noopener noreferrer"
                    className="text-[#B87333] hover:underline"
                  >
                    Terms of Service
                  </a>{" "}
                  apply.
                </p>
              </div>
              {recaptchaSiteKey && (
                <ReCaptcha
                  siteKey={recaptchaSiteKey}
                  onVerify={handleRecaptchaVerify}
                  onError={handleRecaptchaError}
                />
              )}
              <div className="flex justify-start md:justify-end">
                <button
                  type="submit"
                  disabled={isSubmitting || !recaptchaToken}
                  className="px-8 py-4 rounded-full bg-[#B87333] text-white font-semibold hover:bg-[#A05A2C] hover:shadow-lg hover:shadow-[#B87333]/30 hover:scale-105 transition-all duration-300 disabled:opacity-50 disabled:cursor-not-allowed focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-[#B87333]"
                  aria-label="Send message"
                >
                  {isSubmitting ? "Sending..." : "Send Message"}
                </button>
              </div>
            </form>
          </div>
        </motion.div>

        {/* Social Media Links */}
        <motion.div
          initial={{ opacity: 0, y: 20 }}
          animate={isVisible ? { opacity: 1, y: 0 } : {}}
          transition={{ duration: 0.6, delay: 0.8 }}
          className="flex justify-center gap-6 mt-12"
        >
          <SocialLinks />
        </motion.div>
      </div>
    </section>
  );
}
