"use client";

import { ThemeProvider } from "@/providers/themeProvider/ThemeProvider";
import React, { useState, FormEvent } from "react";
import ReactLenis from "lenis/react";
import NavbarLayoutFloatingOverlay from '@/components/navbar/NavbarLayoutFloatingOverlay/NavbarLayoutFloatingOverlay';
import FooterBase from '@/components/sections/footer/FooterBase';
import ContactSplitForm from '@/components/sections/contact/ContactSplitForm';
import { CheckCircle } from 'lucide-react'; // For success message icon

export default function BookingPage() {
  const [formData, setFormData] = useState({
    name: "",    phone: "",    email: "",    eventType: "", // Assuming single selection for simplicity, though propsSchema allows multiSelect
    desiredDate: "",    numGuests: "",    message: ""});
  const [formSubmitted, setFormSubmitted] = useState(false);
  const [errors, setErrors] = useState<Record<string, string>>({});

  const validateForm = () => {
    const newErrors: Record<string, string> = {};
    if (!formData.name) newErrors.name = "Le nom est requis.";
    if (!formData.phone) newErrors.phone = "Le numéro de téléphone est requis.";
    if (!formData.email) newErrors.email = "L'adresse email est requise.";
    else if (!/^\w+([.-]?\w+)*@\w+([.-]?\w+)*(\.\w{2,3})+$/.test(formData.email)) newErrors.email = "Format d'email invalide.";
    if (!formData.eventType) newErrors.eventType = "Le type d'événement est requis.";
    if (!formData.desiredDate) newErrors.desiredDate = "La date souhaitée est requise.";
    if (!formData.numGuests) newErrors.numGuests = "Le nombre d'invités est requis.";
    else if (isNaN(Number(formData.numGuests)) || Number(formData.numGuests) <= 0) newErrors.numGuests = "Doit être un nombre valide.";
    setErrors(newErrors);
    return Object.keys(newErrors).length === 0;
  };

  const handleChange = (name: string, value: string) => {
    setFormData((prev) => ({
      ...prev,
      [name]: value,
    }));
    // Clear error for the field being edited
    setErrors((prev) => {
      const newErrors = { ...prev };
      delete newErrors[name];
      return newErrors;
    });
  };

  const handleSubmit = (data: Record<string, string>) => {
    // Merge custom form data into event data for validation
    const fullData = { ...formData, ...data };
    setFormData(fullData as typeof formData); // Ensure formData is updated for validation

    if (validateForm()) {
      console.log("Formulaire de devis soumis:", fullData);
      // Simulate API call
      setTimeout(() => {
        setFormSubmitted(true);
        // Optionally clear form data after submission
        // setFormData({ name: "", phone: "", email: "", eventType: "", desiredDate: "", numGuests: "", message: "" });
      }, 1000);
    }
  };

  const navItems = [
    { name: "Accueil", id: "/" },
    { name: "À Propos", id: "/#about" },
    { name: "Services", id: "/#services" },
    { name: "Galerie", id: "/#gallery" },
    { name: "Témoignages", id: "/#testimonials" },
    { name: "FAQ", id: "/#faq" },
    { name: "Contact", id: "/contact" },
    { name: "Réserver", id: "/booking" }
  ];

  const footerColumns = [
    {
      title: "Découvrir",      items: [
        { label: "Accueil", href: "/" },
        { label: "À Propos", href: "/#about" },
        { label: "Services", href: "/#services" },
        { label: "Galerie", href: "/#gallery" },
        { label: "Réserver", href: "/booking" }
      ]
    },
    {
      title: "Assistance",      items: [
        { label: "FAQ", href: "/#faq" },
        { label: "Contact", href: "/contact" },
        { label: "Politique de Confidentialité", href: "#" },
        { label: "Conditions Générales", href: "#" }
      ]
    },
    {
      title: "Nous Suivre",      items: [
        { label: "Facebook", href: "#" },
        { label: "Instagram", href: "#" },
        { label: "LinkedIn", href: "#" }
      ]
    }
  ];

  return (
    <ThemeProvider
      defaultButtonVariant="shift-hover"
      defaultTextAnimation="entrance-slide"
      borderRadius="rounded"
      contentWidth="mediumSmall"
      sizing="large"
      background="circleGradient"
      cardStyle="subtle-shadow"
      primaryButtonStyle="double-inset"
      secondaryButtonStyle="glass"
      headingFontWeight="extrabold"
    >
      <ReactLenis root>
        <div id="nav" data-section="nav">
          <NavbarLayoutFloatingOverlay
            navItems={navItems}
            brandName="Salle Évasion"
            button={{
              text: "Demander un devis",              href: "/booking"
            }}
          />
        </div>

        <div className="flex min-h-screen flex-col items-center justify-between pt-32 pb-16">
          {formSubmitted ? (
            <div className="max-w-md mx-auto text-center p-8 bg-card rounded-lg shadow-lg">
              <CheckCircle className="h-16 w-16 text-primary-cta mx-auto mb-4" />
              <h2 className="text-2xl font-bold mb-2">Devis Envoyé avec Succès !</h2>
              <p className="text-foreground/80">Merci pour votre demande. Nous vous contacterons très prochainement pour discuter de votre événement.</p>
              <button
                onClick={() => setFormSubmitted(false)}
                className="mt-6 px-6 py-2 bg-primary-cta text-primary-cta-foreground rounded-md hover:bg-primary-cta/90 transition-colors"
              >
                Nouvelle demande
              </button>
            </div>
          ) : (
            <ContactSplitForm
              title="Demandez Votre Devis Personnalisé"
              description="Remplissez le formulaire ci-dessous pour nous faire part des détails de votre événement. Notre équipe vous recontactera rapidement avec une proposition sur mesure."
              inputs={[
                { name: "name", type: "text", placeholder: "Votre nom complet", required: true, className: errors.name ? "border-red-500" : "" },
                { name: "phone", type: "tel", placeholder: "Votre numéro de téléphone", required: true, className: errors.phone ? "border-red-500" : "" },
                { name: "email", type: "email", placeholder: "Votre adresse email", required: true, className: errors.email ? "border-red-500" : "" },
                { name: "desiredDate", type: "date", placeholder: "Date souhaitée de l'événement", required: true, className: errors.desiredDate ? "border-red-500" : "" },
                { name: "numGuests", type: "number", placeholder: "Nombre d'invités", required: true, className: errors.numGuests ? "border-red-500" : "" }
              ]}
              multiSelect={{
                name: "eventType",                label: "Type d'événement",                options: ["Mariage", "Anniversaire", "Séminaire", "Conférence", "Autre"]
              }}
              textarea={{
                name: "message",                placeholder: "Votre message et détails spécifiques (thème, besoins spéciaux, etc.)",                rows: 5,
                required: false
              }}
              buttonText="Recevoir mon devis"
              onSubmit={handleSubmit}
              useInvertedBackground={true}
              imageSrc="http://img.b2bpic.net/free-photo/planner-woman-holding-wedding-checklist-documents_23-2148784110.jpg"
              imageAlt="Organisateur d'événements préparant un devis"
              mediaAnimation="slide-up"
              className="w-full max-w-6xl mx-auto"
            />
          )}
        </div>

        <div id="footer" data-section="footer">
          <FooterBase
            columns={footerColumns}
            logoText="Salle Évasion"
            copyrightText="© 2024 Salle Évasion. Tous droits réservés."
          />
        </div>
      </ReactLenis>
    </ThemeProvider>
  );
}
