"use client";

import { useEffect, useRef, useState } from "react";
import { motion, AnimatePresence } from "framer-motion";
import { CalendarDays, Clock, Users, ArrowRight, CheckCircle, Sparkles } from "lucide-react";

export default function ReservationForm() {
  const canvasRef = useRef<HTMLCanvasElement>(null);
  const [formData, setFormData] = useState({
    name: "",
    email: "",
    guests: "2",
    date: "",
    time: "19:00",
  });
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [isSuccess, setIsSuccess] = useState(false);

  // Sparks/Gold embers canvas particle system
  useEffect(() => {
    const canvas = canvasRef.current;
    if (!canvas) return;
    const ctx = canvas.getContext("2d");
    if (!ctx) return;

    let animId: number;
    let width = (canvas.width = canvas.parentElement?.clientWidth || 800);
    let height = (canvas.height = canvas.parentElement?.clientHeight || 600);

    const handleResize = () => {
      if (!canvas.parentElement) return;
      width = canvas.width = canvas.parentElement.clientWidth;
      height = canvas.height = canvas.parentElement.clientHeight;
    };
    window.addEventListener("resize", handleResize);

    class Spark {
      x: number;
      y: number;
      vx: number;
      vy: number;
      radius: number;
      alpha: number;
      decay: number;

      constructor() {
        this.x = Math.random() * width;
        this.y = height + 10;
        this.vx = (Math.random() - 0.5) * 0.5;
        this.vy = -Math.random() * 1.2 - 0.4;
        this.radius = Math.random() * 2.0 + 0.5;
        this.alpha = Math.random() * 0.6 + 0.2;
        this.decay = Math.random() * 0.003 + 0.001;
      }

      update() {
        this.x += this.vx;
        this.y += this.vy;
        this.alpha -= this.decay;
        this.vx += (Math.random() - 0.5) * 0.05;
      }

      draw(c: CanvasRenderingContext2D) {
        c.save();
        c.beginPath();
        c.fillStyle = `rgba(212, 175, 55, ${this.alpha})`;
        c.shadowBlur = 6;
        c.shadowColor = "#D4AF37";
        c.arc(this.x, this.y, this.radius, 0, Math.PI * 2);
        c.fill();
        c.restore();
      }
    }

    const sparks: Spark[] = [];
    const maxSparks = 35;

    const render = () => {
      ctx.clearRect(0, 0, width, height);

      if (sparks.length < maxSparks && Math.random() > 0.6) {
        sparks.push(new Spark());
      }

      for (let i = sparks.length - 1; i >= 0; i--) {
        const s = sparks[i];
        s.update();
        s.draw(ctx);

        if (s.alpha <= 0 || s.y < 0) {
          sparks.splice(i, 1);
        }
      }

      animId = requestAnimationFrame(render);
    };

    render();

    return () => {
      window.removeEventListener("resize", handleResize);
      cancelAnimationFrame(animId);
    };
  }, []);

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    setIsSubmitting(true);

    // Simulate luxury API booking delay
    setTimeout(() => {
      setIsSubmitting(false);
      setIsSuccess(true);
    }, 2000);
  };

  return (
    <section className="relative min-h-screen py-24 px-6 md:px-12 flex flex-col justify-center items-center overflow-hidden bg-darkbg-light border-b border-gold/10">
      {/* Background Spark Canvas */}
      <canvas
        ref={canvasRef}
        className="absolute inset-0 z-0 pointer-events-none mix-blend-screen opacity-70"
      />

      <div className="container max-w-4xl mx-auto relative z-10">
        
        {/* Title */}
        <div className="mb-12 flex flex-col items-center text-center">
          <span className="font-sans text-[10px] tracking-[0.4em] uppercase text-gold font-semibold flex items-center gap-2 mb-3">
            <Sparkles size={12} className="animate-pulse" /> S A N C T U A R Y   T A B L E
          </span>
          <h2 className="font-serif text-4xl md:text-6xl font-bold tracking-wide text-foreground uppercase text-glow">
            RESERVE A COURT
          </h2>
          <div className="w-20 h-[1.5px] bg-maroon mt-4" />
        </div>

        {/* Reservation Card wrapper */}
        <div className="relative w-full max-w-2xl mx-auto rounded-xl p-8 md:p-12 glass shadow-[0_30px_70px_rgba(0,0,0,0.8)] border border-gold/20 overflow-hidden">
          
          {/* Inner ornaments */}
          <div className="absolute inset-3 border border-gold/10 rounded-lg pointer-events-none z-0" />
          <div className="absolute inset-[20px] border border-dashed border-gold/5 rounded-lg pointer-events-none z-0" />

          {/* Form states */}
          {!isSuccess ? (
            <form onSubmit={handleSubmit} className="relative z-10 flex flex-col gap-6">
              
              {/* Form Grid */}
              <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                
                {/* Name */}
                <div className="flex flex-col relative group">
                  <label className="font-serif text-[10px] tracking-widest text-gold-dark font-bold uppercase mb-2">
                    Patron Name
                  </label>
                  <input
                    type="text"
                    required
                    value={formData.name}
                    onChange={(e) => setFormData({ ...formData, name: e.target.value })}
                    className="font-sans text-xs md:text-sm text-stone-900 bg-white border border-gold/30 focus:border-maroon px-4 py-3 outline-none transition-all duration-300 rounded"
                    placeholder="Enter your full name"
                  />
                </div>

                {/* Email */}
                <div className="flex flex-col relative">
                  <label className="font-serif text-[10px] tracking-widest text-gold-dark font-bold uppercase mb-2">
                    Digital Address (Email)
                  </label>
                  <input
                    type="email"
                    required
                    value={formData.email}
                    onChange={(e) => setFormData({ ...formData, email: e.target.value })}
                    className="font-sans text-xs md:text-sm text-stone-900 bg-white border border-gold/30 focus:border-maroon px-4 py-3 outline-none transition-all duration-300 rounded"
                    placeholder="name@domain.com"
                  />
                </div>

                {/* Guest Count */}
                <div className="flex flex-col relative">
                  <label className="font-serif text-[10px] tracking-widest text-gold-dark font-bold uppercase mb-2 flex items-center gap-1.5">
                    <Users size={12} className="text-maroon" /> Assembly Size (Guests)
                  </label>
                  <select
                    value={formData.guests}
                    onChange={(e) => setFormData({ ...formData, guests: e.target.value })}
                    className="font-sans text-xs md:text-sm text-stone-900 bg-white border border-gold/30 focus:border-maroon px-4 py-3 outline-none transition-all duration-300 rounded cursor-pointer appearance-none"
                  >
                    <option value="1">1 Patron (Solo Dining)</option>
                    <option value="2">2 Patrons (Duet)</option>
                    <option value="4">4 Patrons (Quartet)</option>
                    <option value="6">6 Patrons (Family Court)</option>
                    <option value="8">8+ Patrons (Royal Sabha)</option>
                  </select>
                </div>

                {/* Date */}
                <div className="flex flex-col relative">
                  <label className="font-serif text-[10px] tracking-widest text-gold-dark font-bold uppercase mb-2 flex items-center gap-1.5">
                    <CalendarDays size={12} className="text-maroon" /> Feast Date
                  </label>
                  <input
                    type="date"
                    required
                    value={formData.date}
                    onChange={(e) => setFormData({ ...formData, date: e.target.value })}
                    className="font-sans text-xs md:text-sm text-stone-900 bg-white border border-gold/30 focus:border-maroon px-4 py-3 outline-none transition-all duration-300 rounded cursor-pointer"
                  />
                </div>

                {/* Time */}
                <div className="flex flex-col relative md:col-span-2">
                  <label className="font-serif text-[10px] tracking-widest text-gold-dark font-bold uppercase mb-2 flex items-center gap-1.5">
                    <Clock size={12} className="text-maroon" /> Dining Session
                  </label>
                  <select
                    value={formData.time}
                    onChange={(e) => setFormData({ ...formData, time: e.target.value })}
                    className="font-sans text-xs md:text-sm text-stone-900 bg-white border border-gold/30 focus:border-maroon px-4 py-3 outline-none transition-all duration-300 rounded cursor-pointer appearance-none"
                  >
                    <option value="16:30">Early Dinner Session - 04:30 PM</option>
                    <option value="18:00">Sunset Feast Session - 06:00 PM</option>
                    <option value="19:30">Royal Banquet Session - 07:30 PM</option>
                    <option value="21:00">Late Dining Session - 09:00 PM</option>
                  </select>
                </div>

              </div>

              {/* Submit CTA */}
              <button
                type="submit"
                disabled={isSubmitting}
                className="clickable w-full mt-6 bg-maroon border border-gold/60 text-white hover:text-white hover:border-maroon-dark py-4 px-6 rounded font-serif text-sm tracking-[0.2em] uppercase transition-all duration-500 flex items-center justify-center gap-3 shadow-[0_10px_20px_rgba(24,135,84,0.12)] relative group overflow-hidden"
              >
                <span className="absolute inset-0 bg-gold translate-y-full group-hover:translate-y-0 transition-transform duration-500 ease-out z-0" />
                <span className="relative z-10 flex items-center gap-3 group-hover:text-darkbg transition-colors duration-500">
                  {isSubmitting ? (
                    <>
                      <div className="w-4 h-4 rounded-full border-2 border-darkbg border-t-transparent animate-spin" />
                      Auditing Court Availability...
                    </>
                  ) : (
                    <>
                      Confirm Royal Seating <ArrowRight size={16} />
                    </>
                  )}
                </span>
              </button>

            </form>
          ) : (
            // Success Feedback State
            <div className="relative z-10 py-12 flex flex-col items-center text-center gap-6">
              <CheckCircle size={64} className="text-gold drop-shadow-[0_0_10px_rgba(212,175,55,0.6)] animate-[bounce_1.5s_infinite_alternate]" />
              <div>
                <h3 className="font-serif text-2xl font-bold text-stone-900 tracking-widest uppercase mb-2">
                  COURT SECURED
                </h3>
                <span className="font-sans text-[10px] text-maroon font-bold tracking-[0.3em] uppercase block mb-6">
                  N A L V A R A V U   P A T R O N
                </span>
                <p className="font-sans text-xs md:text-sm text-stone-700 leading-relaxed tracking-wider max-w-md mx-auto">
                  Namaste, <strong className="text-maroon-dark font-extrabold">{formData.name}</strong>. Your royal table for{" "}
                  <strong className="text-maroon-dark font-extrabold">{formData.guests} guests</strong> on{" "}
                  <strong className="text-maroon-dark font-extrabold">{formData.date}</strong> at{" "}
                  <strong className="text-maroon-dark font-extrabold">{formData.time}</strong> has been provisionally registered. A digital invite seal has been dispatched to{" "}
                  <strong className="text-maroon-dark font-extrabold">{formData.email}</strong>. We wait to welcome you.
                </p>
              </div>

              <button
                onClick={() => setIsSuccess(false)}
                className="clickable mt-6 font-serif text-[10px] tracking-[0.2em] uppercase text-maroon hover:text-white border border-maroon/30 hover:bg-maroon px-6 py-2.5 bg-transparent transition-all duration-300 rounded"
              >
                Book Another Table
              </button>
            </div>
          )}

        </div>

      </div>
    </section>
  );
}
