"use client";

import { useState, ChangeEvent, FormEvent, useEffect } from "react";
import Header from "@/components/Header";
import Footer from "@/components/Footer";
import PropertyGallery from "@/components/PropertyGallery";
import PropertyNav from "@/components/PropertyNav";
import InnerBanner from "@/components/InnerBanner";
import { Property } from "@/data/properties";
import axios from "axios";

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

interface FormErrors {
    name?: string;
    email?: string;
    phone?: string;
}

const sections = [
    { id: "overview", label: "Overview" },
    { id: "about", label: "About" },
    { id: "amenities", label: "Amenities" },
    { id: "floor-plans", label: "Floor Plans" },
    { id: "location", label: "Location" },
    { id: "pricing", label: "Pricing" },
];

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

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

    const handleChange = (e: ChangeEvent<HTMLInputElement | HTMLTextAreaElement>) => {
        const { name, value } = e.target;
        setFormData((prev) => ({ ...prev, [name]: value }));
        // Clear error when user types
        if (formErrors[name as keyof FormErrors]) {
            setFormErrors(prev => ({ ...prev, [name]: undefined }));
        }
    };

    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.";

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

        setIsSubmitting(true);

        const emailData = {
            name: formData.name,
            phone: formData.phone,
            email: formData.email,
            subject: `Property Inquiry: ${property?.title} from ${formData.name}`,
            message: `<strong>Property Inquiry</strong><br /><br />
                <strong>Property:</strong> ${property?.title}<br />
                <strong>Location:</strong> ${property?.location}<br />
                <strong>Price:</strong> ${property?.price}<br /><br />
                <strong>Customer Details:</strong><br />
                Name: ${formData.name}<br />
                Phone: ${formData.phone}<br />
                Email: ${formData.email}<br />
                Message: ${formData.message || 'N/A'}`,
            to: "hello@skyandsoil.com",
            senderName: "Sky and Soil Property Inquiry",
        };

        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 || "Request sent successfully! We will contact you soon.",
            });

            setFormData({ name: "", email: "", phone: "", message: "" });
            setFormErrors({});
        } catch (error) {
            setAlert({
                show: true,
                type: "danger",
                message: "Failed to send request. Please try again later.",
            });
        } finally {
            setIsSubmitting(false);
        }
    };

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

    return (
        <div className="min-h-screen bg-gray-50 dark:bg-black">
            <Header />

            <InnerBanner
                title={property.title}
                subtitle={property.location}
                breadcrumbs={[
                    { label: "Home", href: "/" },
                    { label: "Projects", href: "/projects" },
                    { label: "Residential Real Estate", href: "/residential-real-estate" },
                    { label: property.title }
                ]}
                backgroundImage={property.image}
            />

            <div>

                {/* Sticky Navigation */}
                <PropertyNav sections={sections} />

                <div className="max-w-7xl mx-auto px-6 py-8">
                    {/* Property Header */}
                    <div className="bg-white dark:bg-gray-900 rounded-2xl p-8 mb-8 shadow-sm border border-gray-200 dark:border-gray-800">
                        <div className="flex flex-col md:flex-row md:items-center md:justify-between gap-4 mb-6">
                            <div>
                                <div className="flex items-center gap-3 mb-3">
                                    <h1 className="text-3xl md:text-4xl font-bold text-foreground">{property.title}</h1>
                                    <span className="px-4 py-1.5 bg-gradient-to-r from-green-500 to-emerald-500 text-white rounded-full text-sm font-semibold shadow-md">
                                        {property.status}
                                    </span>
                                </div>
                                <div className="flex items-center text-gray-600 dark:text-gray-400">
                                    <svg className="w-5 h-5 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M17.657 16.657L13.414 20.9a1.998 1.998 0 01-2.827 0l-4.244-4.243a8 8 0 1111.314 0z" />
                                    </svg>
                                    {property.location}
                                </div>
                            </div>
                            <div className="text-right">
                                <div className="text-sm text-gray-500 dark:text-gray-400 mb-1">Starting from</div>
                                <div className="text-4xl font-bold bg-gradient-to-r from-primary to-blue-600 bg-clip-text text-transparent">
                                    {property.price}
                                </div>
                            </div>
                        </div>

                        {/* Quick Stats */}
                        <div className="grid grid-cols-2 md:grid-cols-4 gap-4 pt-6 border-t border-gray-200 dark:border-gray-800">
                            <div className="text-center p-4 bg-gray-50 dark:bg-gray-800 rounded-xl">
                                <div className="text-2xl font-bold text-primary mb-1">{property.overview.bhk}</div>
                                <div className="text-sm text-gray-600 dark:text-gray-400">Configuration</div>
                            </div>
                            <div className="text-center p-4 bg-gray-50 dark:bg-gray-800 rounded-xl">
                                <div className="text-2xl font-bold text-primary mb-1">{property.overview.size}</div>
                                <div className="text-sm text-gray-600 dark:text-gray-400">Area</div>
                            </div>
                            <div className="text-center p-4 bg-gray-50 dark:bg-gray-800 rounded-xl">
                                <div className="text-2xl font-bold text-primary mb-1">{property.overview.possession}</div>
                                <div className="text-sm text-gray-600 dark:text-gray-400">Possession</div>
                            </div>
                            <div className="text-center p-4 bg-gray-50 dark:bg-gray-800 rounded-xl">
                                <div className="text-2xl font-bold text-primary mb-1">{property.overview.totalUnits}</div>
                                <div className="text-sm text-gray-600 dark:text-gray-400">Total Units</div>
                            </div>
                        </div>
                    </div>

                    {/* Image Gallery */}
                    <PropertyGallery images={property.images} title={property.title} />

                    <div className="grid grid-cols-1 lg:grid-cols-3 gap-8">
                        {/* Main Content */}
                        <div className="lg:col-span-2 space-y-8">
                            {/* Overview Section */}
                            <div id="overview" className="bg-white dark:bg-gray-900 rounded-2xl p-8 shadow-sm border border-gray-200 dark:border-gray-800 scroll-mt-32">
                                <h2 className="text-2xl font-bold text-foreground mb-6 flex items-center gap-3">
                                    <div className="w-1 h-8 bg-primary rounded-full"></div>
                                    Overview
                                </h2>
                                <div className="grid grid-cols-2 md:grid-cols-3 gap-6">
                                    <div className="p-4 bg-gray-50 dark:bg-gray-800 rounded-xl">
                                        <div className="text-gray-500 dark:text-gray-400 text-sm mb-2">Property Type</div>
                                        <div className="text-lg font-semibold text-foreground">{property.category}</div>
                                    </div>
                                    <div className="p-4 bg-gray-50 dark:bg-gray-800 rounded-xl">
                                        <div className="text-gray-500 dark:text-gray-400 text-sm mb-2">RERA Status</div>
                                        <div className="text-lg font-semibold text-green-600">Approved</div>
                                    </div>
                                    <div className="p-4 bg-gray-50 dark:bg-gray-800 rounded-xl">
                                        <div className="text-gray-500 dark:text-gray-400 text-sm mb-2">Availability</div>
                                        <div className="text-lg font-semibold text-foreground">Available</div>
                                    </div>
                                </div>
                            </div>

                            {/* About Section */}
                            <div id="about" className="bg-white dark:bg-gray-900 rounded-2xl p-8 shadow-sm border border-gray-200 dark:border-gray-800 scroll-mt-32">
                                <h2 className="text-2xl font-bold text-foreground mb-6 flex items-center gap-3">
                                    <div className="w-1 h-8 bg-primary rounded-full"></div>
                                    About this Property
                                </h2>
                                <p className="text-gray-700 dark:text-gray-300 leading-relaxed text-lg">{property.description}</p>
                            </div>

                            {/* Amenities Section */}
                            <div id="amenities" className="bg-white dark:bg-gray-900 rounded-2xl p-8 shadow-sm border border-gray-200 dark:border-gray-800 scroll-mt-32">
                                <h2 className="text-2xl font-bold text-foreground mb-6 flex items-center gap-3">
                                    <div className="w-1 h-8 bg-primary rounded-full"></div>
                                    Amenities
                                </h2>
                                <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                                    {property.amenities.map((amenity, idx) => (
                                        <div key={idx} className="flex items-center gap-3 p-4 bg-gradient-to-r from-blue-50 to-indigo-50 dark:from-blue-900/20 dark:to-indigo-900/20 rounded-xl hover:shadow-md transition-shadow">
                                            <div className="w-10 h-10 bg-primary rounded-full flex items-center justify-center flex-shrink-0">
                                                <svg className="w-5 h-5 text-white" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M5 13l4 4L19 7" />
                                                </svg>
                                            </div>
                                            <span className="text-gray-700 dark:text-gray-300 font-medium">{amenity}</span>
                                        </div>
                                    ))}
                                </div>
                            </div>

                            {/* Floor Plans Section */}
                            <div id="floor-plans" className="bg-white dark:bg-gray-900 rounded-2xl p-8 shadow-sm border border-gray-200 dark:border-gray-800 scroll-mt-32">
                                <h2 className="text-2xl font-bold text-foreground mb-6 flex items-center gap-3">
                                    <div className="w-1 h-8 bg-primary rounded-full"></div>
                                    Floor Plans
                                </h2>
                                <div className="bg-gradient-to-br from-gray-100 to-gray-200 dark:from-gray-800 dark:to-gray-900 rounded-2xl p-12 text-center">
                                    <svg className="w-20 h-20 mx-auto text-gray-400 mb-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.5} d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z" />
                                    </svg>
                                    <p className="text-gray-600 dark:text-gray-400 text-lg mb-4">Floor plans available on request</p>
                                    <button className="px-6 py-3 bg-primary text-white rounded-lg hover:bg-blue-700 transition-colors font-medium">
                                        Request Floor Plans
                                    </button>
                                </div>
                            </div>

                            {/* Location Section */}
                            <div id="location" className="bg-white dark:bg-gray-900 rounded-2xl p-8 shadow-sm border border-gray-200 dark:border-gray-800 scroll-mt-32">
                                <h2 className="text-2xl font-bold text-foreground mb-6 flex items-center gap-3">
                                    <div className="w-1 h-8 bg-primary rounded-full"></div>
                                    Location
                                </h2>
                                <div className="bg-gray-100 dark:bg-gray-800 rounded-xl p-8 text-center">
                                    <svg className="w-16 h-16 mx-auto text-gray-400 mb-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.5} d="M9 20l-5.447-2.724A1 1 0 013 16.382V5.618a1 1 0 011.447-.894L9 7m0 13l6-3m-6 3V7m6 10l4.553 2.276A1 1 0 0021 18.382V7.618a1 1 0 00-.553-.894L15 4m0 13V4m0 0L9 7" />
                                    </svg>
                                    <p className="text-gray-600 dark:text-gray-400">Interactive map coming soon</p>
                                </div>
                            </div>

                            {/* Pricing Section */}
                            <div id="pricing" className="bg-white dark:bg-gray-900 rounded-2xl p-8 shadow-sm border border-gray-200 dark:border-gray-800 scroll-mt-32">
                                <h2 className="text-2xl font-bold text-foreground mb-6 flex items-center gap-3">
                                    <div className="w-1 h-8 bg-primary rounded-full"></div>
                                    Pricing Details
                                </h2>
                                <div className="space-y-4">
                                    <div className="flex justify-between items-center p-4 bg-gray-50 dark:bg-gray-800 rounded-xl">
                                        <span className="text-gray-700 dark:text-gray-300">Base Price</span>
                                        <span className="text-xl font-bold text-primary">{property.price}</span>
                                    </div>
                                    <p className="text-sm text-gray-500 dark:text-gray-400">* Prices are subject to change. Please contact us for the latest pricing and offers.</p>
                                </div>
                            </div>
                        </div>

                        {/* Sidebar */}
                        <div className="lg:col-span-1">
                            <div className="sticky top-32 space-y-6">
                                {/* Contact Form */}
                                <div className="bg-white dark:bg-gray-900 border border-gray-200 dark:border-gray-800 rounded-2xl p-6 shadow-lg">
                                    <h3 className="text-xl font-bold text-foreground mb-4">Get in Touch</h3>

                                    {alert.show && (
                                        <div className={`mb-4 p-3 rounded-lg text-sm font-medium ${alert.type === 'success' ? 'bg-green-50 text-green-700 border border-green-200' : 'bg-red-50 text-red-700 border border-red-200'}`}>
                                            {alert.message}
                                        </div>
                                    )}

                                    <form onSubmit={handleSubmit} className="space-y-4">
                                        <div>
                                            <input
                                                type="text"
                                                name="name"
                                                value={formData.name}
                                                onChange={handleChange}
                                                placeholder="Your Name"
                                                className={`w-full px-4 py-3 border ${formErrors.name ? 'border-red-500' : 'border-gray-300 dark:border-gray-700'} rounded-lg focus:ring-2 focus:ring-primary focus:border-transparent bg-white dark:bg-gray-800 text-foreground transition-all`}
                                            />
                                            {formErrors.name && <small className="text-red-500 text-xs ml-1">{formErrors.name}</small>}
                                        </div>
                                        <div>
                                            <input
                                                type="email"
                                                name="email"
                                                value={formData.email}
                                                onChange={handleChange}
                                                placeholder="Email Address"
                                                className={`w-full px-4 py-3 border ${formErrors.email ? 'border-red-500' : 'border-gray-300 dark:border-gray-700'} rounded-lg focus:ring-2 focus:ring-primary focus:border-transparent bg-white dark:bg-gray-800 text-foreground transition-all`}
                                            />
                                            {formErrors.email && <small className="text-red-500 text-xs ml-1">{formErrors.email}</small>}
                                        </div>
                                        <div>
                                            <input
                                                type="tel"
                                                name="phone"
                                                value={formData.phone}
                                                onChange={handleChange}
                                                placeholder="Phone Number"
                                                className={`w-full px-4 py-3 border ${formErrors.phone ? 'border-red-500' : 'border-gray-300 dark:border-gray-700'} rounded-lg focus:ring-2 focus:ring-primary focus:border-transparent bg-white dark:bg-gray-800 text-foreground transition-all`}
                                            />
                                            {formErrors.phone && <small className="text-red-500 text-xs ml-1">{formErrors.phone}</small>}
                                        </div>
                                        <textarea
                                            rows={4}
                                            name="message"
                                            value={formData.message}
                                            onChange={handleChange}
                                            placeholder="Message (Optional)"
                                            className="w-full px-4 py-3 border border-gray-300 dark:border-gray-700 rounded-lg focus:ring-2 focus:ring-primary focus:border-transparent bg-white dark:bg-gray-800 text-foreground transition-all"
                                        />
                                        <button
                                            type="submit"
                                            disabled={isSubmitting}
                                            className={`w-full bg-gradient-to-r from-primary to-blue-600 text-white py-3 rounded-lg font-semibold hover:shadow-lg transition-all transform hover:scale-105 ${isSubmitting ? 'opacity-70 cursor-not-allowed' : ''}`}
                                        >
                                            {isSubmitting ? 'Sending...' : 'Request Callback'}
                                        </button>
                                    </form>
                                </div>

                                {/* Quick Actions */}
                                <div className="bg-gradient-to-br from-gray-50 to-gray-100 dark:from-gray-900 dark:to-gray-800 rounded-2xl p-6 border border-gray-200 dark:border-gray-700">
                                    <h3 className="text-lg font-bold text-foreground mb-4">Quick Actions</h3>
                                    <div className="space-y-3">
                                        <button className="w-full flex items-center justify-center gap-2 px-4 py-3 bg-white dark:bg-gray-800 border border-gray-300 dark:border-gray-700 rounded-lg hover:shadow-md transition-all text-foreground">
                                            <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M8.684 13.342C8.886 12.938 9 12.482 9 12c0-.482-.114-.938-.316-1.342m0 2.684a3 3 0 110-2.684m0 2.684l6.632 3.316m-6.632-6l6.632-3.316m0 0a3 3 0 105.367-2.684 3 3 0 00-5.367 2.684zm0 9.316a3 3 0 105.368 2.684 3 3 0 00-5.368-2.684z" />
                                            </svg>
                                            Share Property
                                        </button>
                                        <button className="w-full flex items-center justify-center gap-2 px-4 py-3 bg-white dark:bg-gray-800 border border-gray-300 dark:border-gray-700 rounded-lg hover:shadow-md transition-all text-foreground">
                                            <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M4.318 6.318a4.5 4.5 0 000 6.364L12 20.364l7.682-7.682a4.5 4.5 0 00-6.364-6.364L12 7.636l-1.318-1.318a4.5 4.5 0 00-6.364 0z" />
                                            </svg>
                                            Save to Wishlist
                                        </button>
                                        <button className="w-full flex items-center justify-center gap-2 px-4 py-3 bg-white dark:bg-gray-800 border border-gray-300 dark:border-gray-700 rounded-lg hover:shadow-md transition-all text-foreground">
                                            <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M17 17h2a2 2 0 002-2v-4a2 2 0 00-2-2H5a2 2 0 00-2 2v4a2 2 0 002 2h2m2 4h6a2 2 0 002-2v-4a2 2 0 00-2-2H9a2 2 0 00-2 2v4a2 2 0 002 2zm8-12V5a2 2 0 00-2-2H9a2 2 0 00-2 2v4h10z" />
                                            </svg>
                                            Print Details
                                        </button>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <Footer />
        </div>
    );
}
