"use client"

import { useState } from "react"
import { db } from "@/lib/firebase"
import { collection, addDoc, serverTimestamp } from "firebase/firestore"
import { motion } from "framer-motion"
import confetti from "canvas-confetti"
import DatePicker from "react-datepicker"
import "react-datepicker/dist/react-datepicker.css"
import Navbar from "@/components/Navbar"
import Footer from "@/components/Footer"
import { User, Mail, Store, Clock, Calendar, CheckCircle, Phone } from "lucide-react"

export default function RendezVous() {
  const [formData, setFormData] = useState({
    nom: "",
    email: "",
    telephone: "",
    restaurant: "",
  })
  const [selectedDate, setSelectedDate] = useState<Date | null>(null)
  const [selectedTime, setSelectedTime] = useState<string>("")
  const [loading, setLoading] = useState(false)
  const [success, setSuccess] = useState(false)

  const timeSlots = ["09:00", "10:00", "11:00", "14:00", "15:00", "16:00", "17:00"]

  const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    setFormData({ ...formData, [e.target.name]: e.target.value })
  }

  const handleSubmit = async (e: React.FormEvent<HTMLFormElement>) => {
    e.preventDefault()
    if (!selectedDate || !selectedTime) return

    const [hours, minutes] = selectedTime.split(":")
    const dateTime = new Date(selectedDate)
    dateTime.setHours(parseInt(hours), parseInt(minutes))

    setLoading(true)

    try {
      await addDoc(collection(db, "meetings"), {
        ...formData,
        date: dateTime.toISOString(),
        status: "nouveau",
        attended: false,
        createdAt: serverTimestamp(),
      })

      confetti({
        particleCount: 100,
        spread: 70,
        origin: { y: 0.6 },
      })

      setSuccess(true)
    } catch (err) {
      console.error(err)
    } finally {
      setLoading(false)
    }
  }

  if (success) {
    return (
      <motion.div
        initial={{ opacity: 0 }}
        animate={{ opacity: 1 }}
        className="min-h-screen flex flex-col bg-gray-900 text-gray-100"
      >
        <Navbar />
        <main className="flex-grow flex items-center justify-center px-6 py-16">
          <div className="max-w-md w-full bg-gray-800 rounded-lg p-8 shadow-xl text-center">
            <div className="w-16 h-16 bg-green-600 rounded-full flex items-center justify-center mx-auto mb-4">
              <CheckCircle className="w-8 h-8 text-white" />
            </div>
            <h2 className="text-2xl font-bold mb-2">Rendez-vous confirmé !</h2>
            <p className="text-gray-300 mb-4">
              Merci <span className="font-semibold">{formData.nom}</span>
            </p>
            <p className="text-gray-400 text-sm mb-6">
              Votre démonstration est prévue le{" "}
              {selectedDate?.toLocaleDateString("fr-FR", {
                weekday: "long",
                day: "numeric",
                month: "long",
                year: "numeric",
              })}{" "}
              à {selectedTime}.<br />
              Un email de confirmation a été envoyé à {formData.email}.
              {formData.telephone && (
                <> Nous vous contacterons également au {formData.telephone}.</>
              )}
            </p>
            <button
              onClick={() => setSuccess(false)}
              className="w-full py-2 bg-blue-600 hover:bg-blue-700 rounded transition-colors"
            >
              Planifier une autre démonstration
            </button>
          </div>
        </main>
        <Footer />
      </motion.div>
    )
  }

  return (
    <div className="min-h-screen flex flex-col bg-gray-900 text-gray-100">
      <Navbar />
      <main className="flex-grow flex items-center justify-center px-6 py-16">
        <div className="w-full max-w-4xl bg-gray-800 rounded-lg p-8 shadow-xl">
          <h1 className="text-3xl font-bold text-center mb-2">Planifier une démonstration</h1>
          <p className="text-center text-gray-400 mb-8">
            Choisissez la date et l'heure qui vous conviennent.
          </p>

          <form onSubmit={handleSubmit} className="space-y-6">
            <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
              {/* Left column: user info */}
              <div className="space-y-4">
                <h2 className="text-lg font-semibold border-b border-gray-700 pb-2">Vos informations</h2>
                <div>
                  <label htmlFor="nom" className="block text-sm font-medium text-gray-300 mb-1">
                    Nom complet
                  </label>
                  <div className="relative">
                    <User className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-500" />
                    <input
                      id="nom"
                      name="nom"
                      type="text"
                      required
                      value={formData.nom}
                      onChange={handleChange}
                      className="w-full pl-10 pr-3 py-2 bg-gray-700 border border-gray-600 rounded focus:outline-none focus:border-blue-500"
                    />
                  </div>
                </div>
                <div>
                  <label htmlFor="email" className="block text-sm font-medium text-gray-300 mb-1">
                    Adresse email
                  </label>
                  <div className="relative">
                    <Mail className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-500" />
                    <input
                      id="email"
                      name="email"
                      type="email"
                      required
                      value={formData.email}
                      onChange={handleChange}
                      className="w-full pl-10 pr-3 py-2 bg-gray-700 border border-gray-600 rounded focus:outline-none focus:border-blue-500"
                    />
                  </div>
                </div>
                <div>
                  <label htmlFor="telephone" className="block text-sm font-medium text-gray-300 mb-1">
                    Numéro de téléphone
                  </label>
                  <div className="relative">
                    <Phone className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-500" />
                    <input
                      id="telephone"
                      name="telephone"
                      type="tel"
                      required
                      value={formData.telephone}
                      onChange={handleChange}
                      placeholder="99 XXX XXX"
                      className="w-full pl-10 pr-3 py-2 bg-gray-700 border border-gray-600 rounded focus:outline-none focus:border-blue-500"
                    />
                  </div>
                </div>
                <div>
                  <label htmlFor="restaurant" className="block text-sm font-medium text-gray-300 mb-1">
                    Nom du restaurant
                  </label>
                  <div className="relative">
                    <Store className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-500" />
                    <input
                      id="restaurant"
                      name="restaurant"
                      type="text"
                      required
                      value={formData.restaurant}
                      onChange={handleChange}
                      className="w-full pl-10 pr-3 py-2 bg-gray-700 border border-gray-600 rounded focus:outline-none focus:border-blue-500"
                    />
                  </div>
                </div>
              </div>

              {/* Right column: date & time */}
              <div className="space-y-4">
                <h2 className="text-lg font-semibold border-b border-gray-700 pb-2">Date & heure</h2>
                <div>
                  <label className="block text-sm font-medium text-gray-300 mb-2">Sélectionnez une date</label>
                  <div className="bg-gray-700 border border-gray-600 rounded p-3">
                    <DatePicker
  selected={selectedDate}
  onChange={(date: Date | null) => {
    setSelectedDate(date)
    setSelectedTime("")
  }}
  inline
  minDate={new Date()}
  calendarClassName="dark-theme"
  dayClassName={(date) => {
    const isSelected = date.toDateString() === selectedDate?.toDateString()
    return isSelected ? "bg-blue-600 text-white rounded-full" : "hover:bg-gray-600 rounded-full"
  }}
/>
                  </div>
                </div>

                {selectedDate && (
                  <div>
                    <label className="block text-sm font-medium text-gray-300 mb-2">Choisissez un horaire</label>
                    <div className="grid grid-cols-3 gap-2">
                      {timeSlots.map((time) => (
                        <button
                          key={time}
                          type="button"
                          onClick={() => setSelectedTime(time)}
                          className={`py-2 px-1 rounded border transition-colors ${
                            selectedTime === time
                              ? "bg-blue-600 border-blue-400 text-white"
                              : "bg-gray-700 border-gray-600 text-gray-300 hover:bg-gray-600"
                          }`}
                        >
                          {time}
                        </button>
                      ))}
                    </div>
                  </div>
                )}
              </div>
            </div>

            <button
              type="submit"
              disabled={loading || !selectedDate || !selectedTime}
              className="w-full py-3 bg-blue-600 hover:bg-blue-700 rounded font-medium transition-colors disabled:opacity-50 disabled:cursor-not-allowed flex items-center justify-center gap-2"
            >
              {loading ? (
                <>
                  <svg className="animate-spin h-4 w-4 text-white" viewBox="0 0 24 24">
                    <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4" fill="none" />
                    <path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z" />
                  </svg>
                  Envoi...
                </>
              ) : (
                <>
                  <Clock className="w-4 h-4" />
                  Réserver ma démonstration
                </>
              )}
            </button>
          </form>
        </div>
      </main>
      <Footer />
    </div>
  )
}