"use client";
import Countdown from '@/components/elements/Countdown';
import Layout from "@/components/layout/Layout";
import Link from "next/link";
import { useState, useEffect, ChangeEvent, FormEvent } from "react";
import ReCAPTCHA from "react-google-recaptcha";
import axios from "axios";

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

interface FormErrors {
	name?: string;
	phone?: string;
	email?: string;
	subject?: string;
	message?: string;
	captcha?: string;
}

export default function Contact() {
	const [formData, setFormData] = useState<FormData>({
		name: "",
		phone: "",
		email: "",
		subject: "",
		message: "",
	});

	const [captchaToken, setCaptchaToken] = useState<string | null>(null);
	const [formErrors, setFormErrors] = useState<FormErrors>({});
	const [alert, setAlert] = useState<{ show: boolean; type: string; message: string }>({
		show: false,
		type: "",
		message: "",
	});

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

	const handleCaptchaChange = (token: string | null) => {
		setCaptchaToken(token);
	};

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

		const errors: FormErrors = {};
		if (!formData.name.trim()) errors.name = "Name is required.";
		if (!formData.phone.trim()) errors.phone = "Phone number is required.";
		if (!formData.email.trim()) errors.email = "Email is required.";
		if (!formData.subject.trim()) errors.subject = "Subject is required.";
		if (!formData.message.trim()) errors.message = "Message is required.";
		if (!captchaToken) errors.captcha = "Please verify the CAPTCHA.";

		setFormErrors(errors);
		if (Object.keys(errors).length > 0) return;

		const emailData = {
			...formData,
			message: `Subject: ${formData.subject}<br /><br />Message: ${formData.message}`,
			to: "lead@metatroncube.in",
			senderName: "Tamil Culture Waterloo Contact Page",
			recaptchaToken: captchaToken,
		};

		try {
			const res = await axios.post("https://mailserver.metatronnest.com/send", emailData, {
				headers: { "Content-Type": "application/json" },
			});

			setAlert({
				show: true,
				type: "success",
				message: res?.data?.message || "Message sent successfully!",
			});

			setFormData({ name: "", phone: "", email: "", subject: "", message: "" });
			setCaptchaToken(null);
			setFormErrors({});
		} catch {
			setAlert({
				show: true,
				type: "danger",
				message: "Failed to send message. Please try again later.",
			});
		}
	};

	useEffect(() => {
		if (alert.show) {
			const timer = setTimeout(() => setAlert({ ...alert, show: false }), 5000);
			return () => clearTimeout(timer);
		}
	}, [alert.show]);

	return (
		<Layout headerStyle={1} footerStyle={1}>
			<div>
				<div className="inner-page-header" style={{ backgroundImage: 'url(/assets/img/all-images/contact/contact-banner.webp)' }}>
					<div className="container">
						<div className="row">
							<div className="col-lg-6 m-auto">
								<div className="heading1 text-center">
									<h1>Contact Us</h1>
									<div className="space20" />
									<Link href="/">Home <i className="fa-solid fa-angle-right" /> <span>Contact Us</span></Link>
								</div>
							</div>
						</div>
					</div>
				</div>

				<div className="space80" />
				<div className="contact-bg-section">
					<div className="container">
						<div className="row">
							<div className="col-lg-4 col-md-6">
								<div className="contact-boxarea2" data-aos="zoom-in" data-aos-duration={900}>
									<div className="icons">
										<img src="/assets/img/icons/mail1.svg" alt="" />
									</div>
									<div className="text">
										<h5>Email</h5>
										<div className="space14" />
										<Link href="mailto:mail@tamilculturewaterloo.org">mail@tamilculturewaterloo.org</Link>
									</div>
								</div>
							</div>
							<div className="col-lg-4 col-md-6">
								<div className="contact-boxarea" data-aos="zoom-in" data-aos-duration={1000}>
									<div className="icons">
										<img src="/assets/img/icons/location1.svg" alt="" />
									</div>
									<div className="text">
										<h5>Location</h5>
										<div className="space14" />
										<Link href="#">P.O. Box No:25068, Kitchener, Ontario, N2A 4A5, Canada.</Link>
									</div>
								</div>
							</div>
							<div className="col-lg-4 col-md-6">
								<div className="contact-boxarea3" data-aos="zoom-in" data-aos-duration={1000}>
									<div className="icons">
										<img src="/assets/img/icons/phn1.svg" alt="" />
									</div>
									<div className="text">
										<h5>Call Us</h5>
										<div className="space14" />
										<Link href="tel:+11234567890">+1 123 456 7890</Link>
									</div>
								</div>
							</div>
						</div>
					</div>
				</div>

				<div className="contact-inner-section sp4">
					<div className="container">
						<div className="row">
							<div className="col-lg-6" data-aos="zoom-in" data-aos-duration={1000}>
								<div className="contact4-boxarea">
									<h3 className="text-anime-style-3">Get In Touch Now</h3>
									<div className="space8" />
									<form onSubmit={handleSubmit}>
										{alert.show && (
											<div className={`alert alert-${alert.type}`}>{alert.message}</div>
										)}
										<div className="row">
											<div className="col-lg-6 col-md-6">
												<div className="input-area">
													<input type="text" name="name" placeholder="Name" value={formData.name} onChange={handleChange} />
													{formErrors.name && <small className="text-danger">{formErrors.name}</small>}
												</div>
											</div>
											<div className="col-lg-6 col-md-6">
												<div className="input-area">
													<input type="text" name="phone" placeholder="Phone" value={formData.phone} onChange={handleChange} />
													{formErrors.phone && <small className="text-danger">{formErrors.phone}</small>}
												</div>
											</div>
											<div className="col-lg-12 col-md-6">
												<div className="input-area">
													<input type="email" name="email" placeholder="Email" value={formData.email} onChange={handleChange} />
													{formErrors.email && <small className="text-danger">{formErrors.email}</small>}
												</div>
											</div>
											<div className="col-lg-12 col-md-6">
												<div className="input-area">
													<input type="text" name="subject" placeholder="Subjects" value={formData.subject} onChange={handleChange} />
													{formErrors.subject && <small className="text-danger">{formErrors.subject}</small>}
												</div>
											</div>
											<div className="col-lg-12">
												<div className="input-area">
													<textarea name="message" placeholder="Message" value={formData.message} onChange={handleChange} />
													{formErrors.message && <small className="text-danger">{formErrors.message}</small>}
												</div>
											</div>
											<div className="col-lg-12 mt-2">
												<ReCAPTCHA
													sitekey="6Ldtl20rAAAAAONa5g1txlhj8XqhLIX5SaKgFATk"
													onChange={handleCaptchaChange}
												/>
												{formErrors.captcha && <small className="text-danger">{formErrors.captcha}</small>}
											</div>
											<div className="col-lg-12">
												<div className="space24" />
												<div className="input-area text-end">
													<button type="submit" className="vl-btn1">Submit Now</button>
												</div>
											</div>
										</div>
									</form>
								</div>
							</div>
							<div className="col-lg-6">
								<div className="img1 image-anime">
									<img
										src="/assets/img/all-images/contact/contact-1.webp"
										alt=""
										style={{ border: 0, width: '100%', height: '620px' }}
									/>
								</div>
							</div>
						</div>
					</div>
				</div>

				<div className="contact2-section">
					<div className="mapouter">
						<div className="gmap_canvas">
							<iframe
								src="https://www.google.com/maps/embed?pb=!1m18!1m12!1m3!1d2886.0622283957745!2d-80.39731242413884!3d43.434476063108!2m3!1f0!2f0!3f0!3m2!1i1024!2i768!4f13.1!3m3!1m2!1s0x882bf3cd7b1f3f11%3A0xc93e0b894c6a8b15!2sKitchener%2C%20ON%20N2A%204A5%2C%20Canada!5e0!3m2!1sen!2sin!4v1720000000000!5m2!1sen!2sin"
								style={{ border: 0, width: '100%', height: '450px' }}
								allowFullScreen
								loading="lazy"
								referrerPolicy="no-referrer-when-downgrade"
							></iframe>
						</div>
					</div>
				</div>
			</div>
		</Layout>
	);
}