"use client";

import React, { useEffect, useRef, useState } from "react";
import Navbar from "@/components/Navbar";
import Breadcrumbs from "@/components/Breadcrumbs";
import Footer from "@/components/Footer";
import Image from "next/image";
import {
    Phone,
    Mail,
    MapPin,
    ArrowRight,
    ChevronLeft,
    ChevronRight,
    CheckCircle2,
    Loader2,
    AlertCircle
} from "lucide-react";
import gsap from "gsap";
import { ScrollTrigger } from "gsap/dist/ScrollTrigger";

if (typeof window !== "undefined") {
    gsap.registerPlugin(ScrollTrigger);
}

const ContactPage = () => {
    const mainRef = useRef<HTMLDivElement>(null);
    const [status, setStatus] = useState<"idle" | "submitting" | "success" | "error">("idle");
    const [errorMessage, setErrorMessage] = useState("");
    const [activeTestimonial, setActiveTestimonial] = useState(0);
    const [formData, setFormData] = useState({
        fullname: "",
        mobile: "",
        email: "",
        role: "",
        projectType: "",
        productOfInterest: "",
        estimatedArea: "",
        message: "",
        attachment: null as File | null
    });

    const testimonials = [
        {
            quote: "Working with iRoof has been an absolute pleasure from start to finish. Their team's expertise in architectural design allowed them to bring our vision to life with precision and creativity.",
            name: "Sarah Johnson",
            role: "Chief Marketing Officer at TechSavvy Solutions"
        },
        {
            quote: "The durability and aesthetic finish of iRoof Max products completely transformed our luxury villa project. The thermal insulation properties are incredibly effective in this climate.",
            name: "David Silva",
            role: "Lead Architect at Apex Design Studio"
        },
        {
            quote: "Their engineering support was flawless. We needed a specific custom profile for a commercial heritage restoration, and the iRoof team delivered beyond our expectations.",
            name: "Michael Fernando",
            role: "Project Director at Heritage Builds"
        }
    ];

    const nextTestimonial = () => {
        setActiveTestimonial((prev) => (prev + 1) % testimonials.length);
    };

    const prevTestimonial = () => {
        setActiveTestimonial((prev) => (prev - 1 + testimonials.length) % testimonials.length);
    };

    useEffect(() => {
        const ctx = gsap.context(() => {
            const tl = gsap.timeline({ defaults: { ease: "power4.out", duration: 1.5 } });

            tl.from(".contact-hero-badge", { y: 20, opacity: 0, delay: 0.5 })
                .from(".contact-hero-title", { y: 40, opacity: 0, duration: 1.2, stagger: 0.2 }, "-=0.6")
                .from(".contact-hero-desc", { y: 20, opacity: 0, duration: 1 }, "-=0.8");

            // Reveal animations for high-polish elements
            gsap.utils.toArray<HTMLElement>(".reveal-up").forEach((elem) => {
                gsap.from(elem, {
                    y: 40,
                    opacity: 0,
                    duration: 1.5,
                    ease: "power3.out",
                    scrollTrigger: {
                        trigger: elem,
                        start: "top 90%",
                        toggleActions: "play none none none"
                    }
                });
            });
        }, mainRef);

        return () => ctx.revert();
    }, []);

    const handleChange = (e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement>) => {
        const { name, value } = e.target;
        setFormData(prev => ({ ...prev, [name]: value }));
    };

    const handleFileChange = (e: React.ChangeEvent<HTMLInputElement>) => {
        if (e.target.files && e.target.files.length > 0) {
            setFormData(prev => ({ ...prev, attachment: e.target.files![0] }));
        }
    };

    const handleSubmit = async (e: React.FormEvent) => {
        e.preventDefault();
        setStatus("submitting");
        setErrorMessage("");

        try {
            const submitData = new FormData();
            submitData.append("subject", `New Contact Form Submission from ${formData.fullname}`);
            submitData.append("fullname", formData.fullname);
            submitData.append("email", formData.email);
            submitData.append("mobile", formData.mobile);
            submitData.append("role", formData.role);
            submitData.append("projectType", formData.projectType);
            submitData.append("productOfInterest", formData.productOfInterest);
            submitData.append("estimatedArea", formData.estimatedArea);
            submitData.append("message", formData.message);
            if (formData.attachment) {
                submitData.append("attachment", formData.attachment);
            }

            const response = await fetch("/api/contact", {
                method: "POST",
                body: submitData,
            });

            const result = await response.json();
            if (response.ok && result.success) {
                setStatus("success");
                setFormData({ fullname: "", mobile: "", email: "", role: "", projectType: "", productOfInterest: "", estimatedArea: "", message: "", attachment: null });
            } else {
                setErrorMessage(result.error || "Something went wrong while sending your message.");
                setStatus("error");
            }
        } catch (error) {
            console.error(error);
            setErrorMessage("We could not send your message right now. Please try again.");
            setStatus("error");
        }
    };

    return (
        <main ref={mainRef} className="min-h-screen bg-white text-brand-dark selection:bg-brand-accent selection:text-white">
            <Navbar />

            {/* CONTACT HERO - Immersive Banner */}
            <section className="relative pt-32 pb-24 md:pt-48 md:pb-32 overflow-hidden bg-brand-dark min-h-[50vh] flex items-center">
                {/* Background Image */}
                <div className="absolute inset-0 z-0">
                    <Image
                        src="/images/pexels9.webp"
                        alt="iRoof Premium Architecture"
                        fill
                        className="object-cover opacity-40 mix-blend-overlay"
                        priority
                    />
                    <div className="absolute inset-0 bg-linear-to-t from-brand-dark via-brand-dark/80 to-transparent" />
                </div>

                <div className="max-w-350 mx-auto px-8 md:px-16 lg:px-32 xl:px-40 relative z-10 w-full text-center">
                    <div className="max-w-4xl mx-auto flex flex-col items-center">
                        <div className="contact-hero-badge flex items-center justify-center gap-4 mb-8 mt-6 group">
                            <div className="h-[1.5px] w-8 md:w-12 bg-brand-accent group-hover:w-16 transition-all duration-700" />
                            <span className="text-[10px] md:text-[11px] font-semibold text-brand-accent uppercase tracking-[0.3em] md:tracking-[0.4em]">
                                Direct Liaison Hub
                            </span>
                            <div className="h-[1.5px] w-8 md:w-12 bg-brand-accent group-hover:w-16 transition-all duration-700" />
                        </div>
                        <h1 className="contact-hero-title text-4xl md:text-6xl lg:text-7xl font-semibold text-white tracking-tighter leading-[1.1] mb-8">
                            Let&apos;s Build Your <br />
                            <span className="text-brand-accent">Architectural Vision</span>
                        </h1>
                        <p className="contact-hero-desc text-sm md:text-base text-zinc-300 max-w-2xl font-light leading-relaxed">
                            Connect with our engineering experts for technical consultations, product specifications, and rapid support across Sri Lanka.
                        </p>
                    </div>
                </div>
            </section>
            {/* COMPACT MINIMALIST GLOBAL HUB (Concise Context) */}
            <section className="py-24 bg-white relative">
                <div className="max-w-350 mx-auto px-8 md:px-16 lg:px-32 xl:px-40 pb-8 -mt-12">
                    <Breadcrumbs items={[{ label: "Contact" }]} className="mb-12" />
                </div>
                <div className="max-w-350 mx-auto px-8 md:px-16 lg:px-32 xl:px-40">
                    {/* Compact Header */}
                    <div className="mb-12 reveal-up">
                        <div className="flex items-center gap-4 mb-4 group">
                            <div className="h-[1.5px] w-8 md:w-12 bg-brand-accent group-hover:w-16 transition-all duration-700" />
                            <span className="text-[10px] md:text-[11px] font-semibold text-brand-accent uppercase tracking-[0.3em] md:tracking-[0.4em]">Direct Liaison</span>
                        </div>
                        <h2 className="text-3xl md:text-5xl font-bold text-brand-dark tracking-tighter leading-none mb-8">
                            Find us
                            <span className="text-brand-accent"> Globally</span>
                        </h2>
                    </div>

                    {/* Concise Contact Grid */}
                    <div className="grid grid-cols-1 md:grid-cols-3 gap-8 mb-12 reveal-up">
                        {[
                            {
                                label: "Voice Channel",
                                title: "076 2200 200",
                                sub: "Mon-Fri | 8.30am-5.30pm",
                                icon: <Phone size={18} strokeWidth={1.5} />,
                                href: "tel:+94762200200"
                            },
                            {
                                label: "Digital Mail",
                                title: "info@iroof.lk",
                                sub: "24/7 Digital Intake",
                                icon: <Mail size={18} strokeWidth={1.5} />,
                                href: "mailto:info@iroof.lk"
                            },
                            {
                                label: "Physical HQ",
                                title: "Colombo, Sri Lanka",
                                sub: "Lucas Road, Colombo 14",
                                icon: <MapPin size={18} strokeWidth={1.5} />
                            }
                        ].map((item, i) => (
                            <div key={i} className="group flex flex-col items-start cursor-default">
                                <div className="text-brand-accent mb-4">
                                    {item.icon}
                                </div>
                                <p className="text-[9px] font-semibold uppercase tracking-[0.2em] text-zinc-300 mb-1.5">{item.label}</p>
                                {item.href ? (
                                    <a href={item.href} className="text-lg font-semibold text-brand-dark hover:text-brand-accent transition-colors duration-500 mb-0.5 inline-block">
                                        {item.title}
                                    </a>
                                ) : (
                                    <h4 className="text-lg font-bold text-brand-dark group-hover:text-brand-accent transition-colors duration-500 mb-0.5">{item.title}</h4>
                                )}
                                <p className="text-[10px] font-medium text-zinc-400">{item.sub}</p>
                            </div>
                        ))}
                    </div>

                    {/* Integrated Compact Map */}
                    <div className="reveal-up relative aspect-21/9 md:aspect-21/7 overflow-hidden border border-zinc-200 shadow-sm bg-zinc-50 group">
                        <iframe
                            src="https://www.google.com/maps?q=Idea%20Group%20Limited%20Colombo%2006%20Lucas%20Road&z=15&output=embed"
                            className="absolute inset-0 w-full h-full hover:scale-105 transition-all duration-1000"
                            loading="lazy"
                        />
                    </div>
                </div>
            </section>

            {/* REFERENCE-STYLE DESIGN HUB */}
            <section className="py-24 bg-white">
                <div className="max-w-350 mx-auto px-8 md:px-16 lg:px-32 xl:px-40">
                    <div className="bg-white overflow-hidden shadow-sm border border-brand-dark/5">
                        <div className="grid grid-cols-1 xl:grid-cols-2">

                            {/* Left Column: Visual & Testimony */}
                            <div className="relative min-h-125 xl:min-h-175 overflow-hidden group">
                                <Image
                                    src="/images/footer-background.webp"
                                    alt="iRoof Premium Architecture"
                                    fill
                                    className="object-cover transition-transform duration-1000 group-hover:scale-110"
                                />
                                <div className="absolute inset-0 bg-linear-to-t from-brand-dark/80 via-brand-dark/20 to-transparent" />

                                {/* Testimonial Box */}
                                <div className="absolute bottom-8 left-8 right-8 p-8 bg-black/40 backdrop-blur-md border border-white/10 rounded-2xl text-white reveal-up overflow-hidden">
                                    <div className="relative">
                                        <p
                                            key={activeTestimonial}
                                            className="text-lg font-light leading-relaxed mb-8 italic animate-in fade-in slide-in-from-right-4 duration-500"
                                        >
                                            &quot;{testimonials[activeTestimonial].quote}&quot;
                                        </p>
                                    </div>
                                    <div className="flex items-center justify-between">
                                        <div
                                            key={`author-${activeTestimonial}`}
                                            className="animate-in fade-in slide-in-from-left-4 duration-500"
                                        >
                                            <h4 className="font-bold text-sm">{testimonials[activeTestimonial].name},</h4>
                                            <p className="text-[10px] font-medium text-white/50 uppercase tracking-widest">{testimonials[activeTestimonial].role}</p>
                                        </div>
                                        <div className="flex gap-3">
                                            <button
                                                onClick={prevTestimonial}
                                                className="w-10 h-10 rounded-full border border-white/20 flex items-center justify-center hover:bg-white hover:text-brand-dark transition-all duration-300 active:scale-95"
                                            >
                                                <ChevronLeft size={16} />
                                            </button>
                                            <button
                                                onClick={nextTestimonial}
                                                className="w-10 h-10 rounded-full bg-white text-brand-dark flex items-center justify-center hover:bg-brand-accent hover:text-white transition-all duration-300 active:scale-95"
                                            >
                                                <ChevronRight size={16} />
                                            </button>
                                        </div>
                                    </div>
                                </div>
                            </div>

                            {/* Right Column: Interaction Form */}
                            <div id="quotation" className="p-8 md:p-16 flex flex-col justify-center bg-white">
                                <div className="max-w-md">


                                    <h2 className="text-3xl md:text-4xl font-semibold text-brand-dark tracking-tighter leading-tight mb-4">
                                        Have a project idea? <br />
                                        Let&apos;s discuss it together.
                                    </h2>
                                    <p className="text-xs md:text-sm font-normal text-brand-dark/50 leading-relaxed mb-10">
                                        Complete all fields to receive an accurate quotation.
                                    </p>

                                    {status === "success" ? (
                                        <div className="bg-emerald-50 border border-emerald-100 p-8 rounded-2xl text-center flex flex-col items-center animate-in fade-in zoom-in duration-700">
                                            <div className="w-16 h-16 bg-emerald-500 rounded-full flex items-center justify-center mb-6 text-white shadow-lg shadow-emerald-500/20">
                                                <CheckCircle2 size={32} />
                                            </div>
                                            <h3 className="text-xl font-black text-brand-dark mb-3 tracking-tight">Message Sent!</h3>
                                            <p className="text-xs font-medium text-brand-dark/60 leading-relaxed mb-6">
                                                Thank you for reaching out. Our engineering experts will get back to you shortly.
                                            </p>
                                            <button
                                                onClick={() => setStatus("idle")}
                                                className="text-[10px] font-black text-brand-accent uppercase tracking-[0.2em] hover:text-brand-dark transition-all"
                                            >
                                                Send Another Message
                                            </button>
                                        </div>
                                    ) : (
                                        <form onSubmit={handleSubmit} className="space-y-6">
                                            <div className="space-y-4">
                                                <div className="space-y-2">
                                                    <label className="text-[10px] font-semibold uppercase tracking-widest text-brand-dark/50 ml-1">Full name</label>
                                                    <input
                                                        required
                                                        type="text"
                                                        name="fullname"
                                                        value={formData.fullname}
                                                        onChange={handleChange}
                                                        placeholder="Full Name"
                                                        className="w-full bg-zinc-50 border border-brand-dark/5 rounded-xl px-5 py-3.5 focus:ring-2 focus:ring-brand-accent/10 focus:border-brand-accent focus:bg-white outline-none transition-all text-sm font-medium placeholder:text-brand-dark/20"
                                                    />
                                                </div>

                                                <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                                                    <div className="space-y-2">
                                                        <label className="text-[10px] font-semibold uppercase tracking-widest text-brand-dark/50 ml-1">Email address</label>
                                                        <input
                                                            required
                                                            type="email"
                                                            name="email"
                                                            value={formData.email}
                                                            onChange={handleChange}
                                                            placeholder="Email address"
                                                            className="w-full bg-zinc-50 border border-brand-dark/5 rounded-xl px-5 py-3.5 focus:ring-2 focus:ring-brand-accent/10 focus:border-brand-accent focus:bg-white outline-none transition-all text-sm font-medium placeholder:text-brand-dark/20"
                                                        />
                                                    </div>
                                                    <div className="space-y-2">
                                                        <label className="text-[10px] font-semibold uppercase tracking-widest text-brand-dark/50 ml-1">Mobile number</label>
                                                        <input
                                                            required
                                                            type="tel"
                                                            name="mobile"
                                                            value={formData.mobile}
                                                            onChange={handleChange}
                                                            placeholder="Mobile number"
                                                            className="w-full bg-zinc-50 border border-brand-dark/5 rounded-xl px-5 py-3.5 focus:ring-2 focus:ring-brand-accent/10 focus:border-brand-accent focus:bg-white outline-none transition-all text-sm font-medium placeholder:text-brand-dark/20"
                                                        />
                                                    </div>
                                                </div>

                                                <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                                                    <div className="space-y-2">
                                                        <label className="text-[10px] font-semibold uppercase tracking-widest text-brand-dark/50 ml-1">Your Role</label>
                                                        <select
                                                            required
                                                            name="role"
                                                            value={formData.role}
                                                            onChange={handleChange}
                                                            className="w-full bg-zinc-50 border border-brand-dark/5 rounded-xl px-5 py-3.5 focus:ring-2 focus:ring-brand-accent/10 focus:border-brand-accent focus:bg-white outline-none transition-all text-sm font-medium text-brand-dark/70"
                                                        >
                                                            <option value="" disabled>Select Role</option>
                                                            <option value="Architect">Architect</option>
                                                            <option value="Contractor">Contractor</option>
                                                            <option value="Home Owner">Home Owner</option>
                                                            <option value="Interior Designer">Interior Designer</option>
                                                            <option value="Other">Other</option>
                                                        </select>
                                                    </div>
                                                    <div className="space-y-2">
                                                        <label className="text-[10px] font-semibold uppercase tracking-widest text-brand-dark/50 ml-1">Project Type</label>
                                                        <select
                                                            required
                                                            name="projectType"
                                                            value={formData.projectType}
                                                            onChange={handleChange}
                                                            className="w-full bg-zinc-50 border border-brand-dark/5 rounded-xl px-5 py-3.5 focus:ring-2 focus:ring-brand-accent/10 focus:border-brand-accent focus:bg-white outline-none transition-all text-sm font-medium text-brand-dark/70"
                                                        >
                                                            <option value="" disabled>Select Type</option>
                                                            <option value="Residential">Residential</option>
                                                            <option value="Commercial">Commercial</option>
                                                            <option value="Hospitality">Hospitality</option>
                                                            <option value="Office">Office</option>
                                                            <option value="Institution">Institution</option>
                                                            <option value="Government">Government</option>
                                                            <option value="Other">Other</option>
                                                        </select>
                                                    </div>
                                                </div>

                                                <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                                                    <div className="space-y-2">
                                                        <label className="text-[10px] font-semibold uppercase tracking-widest text-brand-dark/50 ml-1">Product of Interest</label>
                                                        <select
                                                            required
                                                            name="productOfInterest"
                                                            value={formData.productOfInterest}
                                                            onChange={handleChange}
                                                            className="w-full bg-zinc-50 border border-brand-dark/5 rounded-xl px-5 py-3.5 focus:ring-2 focus:ring-brand-accent/10 focus:border-brand-accent focus:bg-white outline-none transition-all text-sm font-medium text-brand-dark/70"
                                                        >
                                                            <option value="" disabled>Select Product</option>
                                                            <option value="iRoof Max Chocolate Brown">iRoof Max Chocolate Brown</option>
                                                            <option value="iRoof Max Brick Red">iRoof Max Brick Red</option>
                                                            <option value="iRoof Max White">iRoof Max White</option>
                                                            <option value="iRoof Max Dark Green">iRoof Max Dark Green</option>
                                                            <option value="Arctic">Arctic</option>
                                                        </select>
                                                    </div>
                                                    <div className="space-y-2">
                                                        <label className="text-[10px] font-semibold uppercase tracking-widest text-brand-dark/50 ml-1">Estimated Area (sqft)</label>
                                                        <input
                                                            required
                                                            type="number"
                                                            name="estimatedArea"
                                                            value={formData.estimatedArea}
                                                            onChange={handleChange}
                                                            placeholder="e.g. 1500"
                                                            className="w-full bg-zinc-50 border border-brand-dark/5 rounded-xl px-5 py-3.5 focus:ring-2 focus:ring-brand-accent/10 focus:border-brand-accent focus:bg-white outline-none transition-all text-sm font-medium placeholder:text-brand-dark/20"
                                                        />
                                                    </div>
                                                </div>

                                                <div className="space-y-2">
                                                    <label className="text-[10px] font-semibold uppercase tracking-widest text-brand-dark/50 ml-1">Attach Files / Blueprint (Optional)</label>
                                                    <input
                                                        type="file"
                                                        name="attachment"
                                                        onChange={handleFileChange}
                                                        accept=".pdf,.png,.jpg,.jpeg,.doc,.docx"
                                                        className="w-full bg-zinc-50 border border-brand-dark/5 rounded-xl px-5 py-3 focus:ring-2 focus:ring-brand-accent/10 focus:border-brand-accent focus:bg-white outline-none transition-all text-sm font-medium file:mr-4 file:py-2 file:px-4 file:rounded-full file:border-0 file:text-[10px] file:font-bold file:uppercase file:tracking-widest file:bg-brand-dark file:text-white hover:file:bg-brand-accent"
                                                    />
                                                    <p className="text-[10px] font-medium text-brand-dark/35 ml-1">
                                                        Accepted files: PDF, PNG, JPG, JPEG, DOC, DOCX up to 10 MB.
                                                    </p>
                                                </div>

                                                <div className="space-y-2">
                                                    <label className="text-[10px] font-semibold uppercase tracking-widest text-brand-dark/50 ml-1">Message (Optional)</label>
                                                    <textarea
                                                        rows={3}
                                                        name="message"
                                                        value={formData.message}
                                                        onChange={handleChange}
                                                        placeholder="Any additional information..."
                                                        className="w-full bg-zinc-50 border border-brand-dark/5 rounded-xl px-5 py-3.5 focus:ring-2 focus:ring-brand-accent/10 focus:border-brand-accent focus:bg-white outline-none transition-all text-sm font-medium resize-none placeholder:text-brand-dark/20"
                                                    ></textarea>
                                                </div>
                                            </div>

                                            {status === "error" && (
                                                <div className="flex items-center gap-3 p-4 bg-red-50 text-red-600 rounded-xl text-xs font-bold border border-red-100">
                                                    <AlertCircle size={16} />
                                                    <p>{errorMessage || "Something went wrong. Please try again later."}</p>
                                                </div>
                                            )}

                                            <button
                                                disabled={status === "submitting"}
                                                className="w-full bg-brand-dark text-white py-6 rounded-xl font-semibold text-xs uppercase tracking-[0.4em] hover:bg-brand-accent transition-all duration-500 shadow-xl shadow-brand-dark/5 flex items-center justify-center gap-4 disabled:opacity-50 disabled:cursor-not-allowed"
                                            >
                                                {status === "submitting" ? (
                                                    <>
                                                        <Loader2 className="animate-spin" size={18} />
                                                        <span>Sending...</span>
                                                    </>
                                                ) : (
                                                    <>
                                                        <span>Send Message</span>
                                                        <ArrowRight size={18} />
                                                    </>
                                                )}
                                            </button>
                                        </form>
                                    )}
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </section>



            <Footer />
        </main>
    );
};

export default ContactPage;
