import React, { useState, useEffect } from 'react';
import axios from 'axios';
import { API_URL } from '@/Constants';
import SuccessMessage from './SuccessMessage';



type FormDataType = {
    name: string;
    email: string;
    ph: string;
    city: string; // Convert to string for URLSearchParams compatibility
    message: string;
};
interface Properties {
    phone: string;
    email: string;
    headerTitle: string;
    sub_title: string;
    admin_email: string;
    address: string;
    opening: string;
    alt_phone: string;
    telephone: string;
    alt_telephone: string;
    banner: string;
    content: string | null;
}
interface FooterProps {
    apiUrl: string;
}
const ContactUs = ({ apiUrl }: FooterProps) => {
    const [formData, setFormData] = useState<FormDataType>({
        name: '',
        email: '',
        ph: '',
        city: '', // Convert city to string
        message: '',
    });

    const [properties, setProperties] = useState<Properties | null>(null);

    const [loading, setLoading] = useState(false);

    const [successNotification, setSuccessNotification] = useState('');
    const [responseMessage, setResponseMessage] = useState('');
    const [errors, setErrors] = useState<Record<string, string>>({}); // For form validation
    useEffect(() => {
        const fetchProperties = async () => {
            try {
                const response = await fetch(apiUrl);
                const data = await response.json();
                setProperties(data); // Assuming the data is in the expected format

            } catch (error) {
                console.error("Error fetching properties:", error);

            }
        };

        fetchProperties();
    }, [apiUrl]);
    const handleInputChange = (e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>) => {
        setSuccessNotification('');
        const { name, value } = e.target;
        setFormData((prevData) => ({
            ...prevData,
            [name]: value,
        }));
        setErrors((prevErrors) => ({
            ...prevErrors,
            [name]: '', // Set the error for the specific field to an empty string
        }));
    };

    const validateForm = () => {
        const formErrors: Record<string, string> = {};
        if (!formData.name.trim()) formErrors.name = 'Name is required';
        if (!formData.email.trim()) formErrors.email = 'Email is required';
        if (!formData.ph.trim()) formErrors.ph = 'Phone is required';
        if (!formData.message.trim()) formErrors.message = 'Message is required';

        setErrors(formErrors);
        return Object.keys(formErrors).length === 0;
    };

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

        if (!validateForm()) {
            return;
        }

        setLoading(true);
        try {
            const params = new URLSearchParams({
                name: formData.name,
                email: formData.email,
                ph: formData.ph,
                city: formData.city, // Ensure city is a string
                message: formData.message
            });

            const response = await axios.get(`${API_URL}send_contact`, { params });

            if (response.data.status === 'success') {
                setSuccessNotification(response.data.message);
                setFormData({
                    name: '',
                    email: '',
                    ph: '',
                    city: '', // Reset city
                    message: ''
                });
            } else {
                setResponseMessage('There was an error with your submission.');
                if (response.data.errors) {
                    setErrors(response.data.errors);
                }
            }
        } catch (error) {
            setResponseMessage('Network error occurred. Please try again later.');
        } finally {
            setLoading(false);
        }
    };

    return (
        <>
            <div className="row">
                <div
                    className={`contact-us head-sect article-main `}
                >
                    <div className="section-dark page-banner list-banner-home   more-height sect-blog half-height" >
                        <div
                            className="full-block page-banner-image as"
                            style={{ backgroundImage: `url(${properties?.banner})` }}
                        >
                        </div>
                        <div className="full-block overlay"></div>
                        {properties?.headerTitle && (
                            <div className="container h-100">
                                <div className="row disp-table h-100">
                                    <div className="col col-md-12 h-100">
                                        <div className="page-banner-content h-100">
                                            <div className="page-banner-content h-100">
                                                <div className="fancy-title-hold text-initial clearfix">
                                                    <h2 className="fancy-title animate animated">
                                                        {properties?.headerTitle}

                                                        {properties.sub_title && (
                                                            <span
                                                                className="sub-title-fnt"

                                                            >
                                                                {properties.sub_title}
                                                            </span>
                                                        )}
                                                    </h2>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        )}

                    </div>
                </div>
                <section className="frm-cnt1">
                    <div className="container">
                        <div className="row">
                            <div className="col-sm-5 contact-us-0 ">
                                {properties?.content ? (
                                    <div dangerouslySetInnerHTML={{ __html: properties.content }} />
                                ) : (
                                    <p> </p>  // You can provide a fallback message or an empty div if preferred
                                )}
                            </div>
                            <div className="col-sm-7 contact-fid">
                                <form
                                    className='pure-form pure-form-aligned main-enquiry-form at-contact-us'

                                    onSubmit={handleSubmit}>
                                    <fieldset className="d-block">
                                        <legend>

                                            <div className="featured-title-hold text-center clearfix">

                                            </div>


                                        </legend>
                                        <div className="division">
                                            {responseMessage && <p>{responseMessage}</p>}
                                            {successNotification &&
                                                (
                                                    <SuccessMessage responseMessage={successNotification} />

                                                )}


                                            <div className="row padd-frm d-flex">
                                                <div className="col-sm-6">
                                                    <div className="pure-control-group form-icon form-icon-person">
                                                        <label htmlFor="">Full Name</label>
                                                        <input
                                                            className="pure-input-1"
                                                            placeholder="Name"
                                                            name="name"
                                                            type="text"
                                                            value={formData.name}
                                                            onChange={handleInputChange}
                                                        />
                                                        {errors.name && <div className="errorMessage">{errors.name}</div>}
                                                    </div>
                                                </div>
                                                <div className="col-sm-6">
                                                    <div className="pure-control-group form-icon form-icon-mail">
                                                        <label htmlFor="">Email Address</label>
                                                        <input
                                                            className="pure-input-1"
                                                            placeholder="Email"
                                                            name="email"
                                                            type="text"
                                                            value={formData.email}
                                                            onChange={handleInputChange}
                                                        />
                                                        {errors.email && <div className="errorMessage">{errors.email}</div>}
                                                    </div>
                                                </div>
                                            </div>

                                            <div className="row padd-frm d-flex">
                                                <div className="col-sm-6">
                                                    <div className="pure-control-group form-icon form-icon-mobile">
                                                        <label htmlFor="">Phone Number</label>
                                                        <input
                                                            className="pure-input-1"
                                                            placeholder="Phone"
                                                            name="ph"
                                                            type="text"
                                                            value={formData.ph}
                                                            onChange={handleInputChange}
                                                        />
                                                        {errors.ph && <div className="errorMessage">{errors.ph}</div>}
                                                    </div>
                                                </div>
                                                <div className="col-sm-6">
                                                    <div className="pure-control-group form-icon form-icon-mobile">
                                                        <label htmlFor="">Community/City</label>
                                                        <input
                                                            className="pure-input-1"
                                                            placeholder="Community/City"
                                                            name="city"
                                                            type="text"
                                                            value={formData.city}
                                                            onChange={handleInputChange}
                                                        />
                                                        {errors.ph && <div className="errorMessage">{errors.city}</div>}
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                        <div className="row padd-frm d-flex">
                                            <div className="col-sm-12">
                                                <div className="division">
                                                    <div className="pure-control-group  ">
                                                        <label htmlFor="">Short Description</label>
                                                        <textarea
                                                            className="pure-input-1"
                                                            placeholder="Message"
                                                            name="message"
                                                            value={formData.message}
                                                            onChange={handleInputChange}
                                                        />
                                                        {errors.message && <div className="errorMessage">{errors.message}</div>}
                                                    </div>
                                                    <div className="pure-control-group">
                                                        <button className="button button-primary" type="submit">
                                                            {loading ? 'Processing...' : <><span className="icon-mail-3"></span> Send Message</>}
                                                        </button>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                    </fieldset>
                                </form>
                            </div>
                        </div>
                    </div>
                </section>
                <section className="contact-us-1">
                    <div className="container">
                    <h2 className="section-title-28 with-line-2 mb-15 new">our head office</h2>
                    <iframe
                        src="https://www.google.com/maps/embed?pb=!1m18!1m12!1m3!1d3613.1361003130996!2d55.1782885752598!3d25.097253835741835!2m3!1f0!2f0!3f0!3m2!1i1024!2i768!4f13.1!3m3!1m2!1s0x3e5f6bb088ca6bb7%3A0x7ea961b8ac7b6af6!2sI%20Rise%20Tower%20-%20hassa%20street%20-%20barsha%20heights%20-%20Dubai%20-%20uae!5e0!3m2!1sen!2sin!4v1745390905970!5m2!1sen!2sin"
                        width="100%"
                        height="600"
                        //style={{ border: 0, filter: 'grayscale(100%)' }}
                        allowFullScreen
                        className="iframe-background1"
                        loading="lazy"
                    ></iframe>
                    </div>
                    <div className="iframe-background-content">


                    </div>
                    <ul className="info-div-contact hide d-none">

                        {properties?.address && (
                            <li>
                                <h3><img src="/assets/images/location.png" alt="" className="" /> Office Address</h3>
                                <address className="li-bd">{properties.address}</address></li>
                        )}
                        {properties?.opening && (
                            <li>
                                <h3><img src="/assets/images/working-hours.png" alt="" className="" /> Opening Hours:</h3>
                                <div className="d-flex">

                                    <p className="li-bd"
                                        dangerouslySetInnerHTML={{
                                            __html: properties.opening,
                                        }}
                                    />
                                </div>
                            </li>
                        )}
                        <li className="clts-1">
                            <div className="">
                                <h3><img src="/assets/images/mail.png" alt="" className="" /> Email:</h3>
                                {properties?.email && (
                                    <a
                                        href={`mailto:${properties.email}`}
                                        className="li-bd">{properties.email}</a>

                                )}
                                {properties?.admin_email && (
                                    <a
                                        href={`mailto:${properties.admin_email}`}
                                        className="li-bd">{properties.admin_email}</a>

                                )}
                            </div>
                        </li>
                        <li className="clts-1">
                            <div className="">
                                <h3><img src="/assets/images/telephone.png" alt="" className="" /> Phone:</h3>
                                <div className="tel-numbers">
                                    Tel :
                                    {properties?.telephone && (
                                        <a
                                            href={`tel:${properties.telephone}`}
                                            className="li-bd">{properties.telephone}</a>
                                    )} / {properties?.alt_telephone && (
                                        <a
                                            href={`tel:${properties.alt_telephone}`}
                                            className="li-bd">{properties.alt_telephone}</a>
                                    )}
                                </div>
                                <div className="tel-numbers">
                                    Mobile :
                                    {properties?.phone && (
                                        <a
                                            href={`tel:${properties.phone}`}
                                            className="li-bd">{properties.phone}</a>
                                    )} / {properties?.alt_phone && (
                                        <a
                                            href={`tel:${properties.alt_phone}`}
                                            className="li-bd">{properties.alt_phone}</a>
                                    )}
                                </div>
                            </div>
                        </li>

                    </ul>
                </section>
            </div>

        </>
    );
};

export default ContactUs;
