"use client"; import { useState } from "react"; import { Button } from "@/components/ui/button"; import { useAppTheme } from "@/components/ThemeProvider"; import { Input } from "@/components/ui/input"; import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue, } from "@/components/ui/select"; import { Calendar, Clock, User, Mail, Phone, MessageSquare, ArrowLeft, Heart, CheckCircle2, CheckCircle, Loader2, LogOut, } from "lucide-react"; import Link from "next/link"; import Image from "next/image"; import { useRouter } from "next/navigation"; import { LoginDialog } from "@/components/LoginDialog"; import { useAuth } from "@/hooks/useAuth"; import { toast } from "sonner"; interface User { ID: number; CreatedAt?: string; UpdatedAt?: string; DeletedAt?: string | null; first_name: string; last_name: string; email: string; phone: string; location: string; date_of_birth?: string; is_admin?: boolean; bookings?: null; } interface Booking { ID: number; CreatedAt: string; UpdatedAt: string; DeletedAt: string | null; user_id: number; user: User; scheduled_at: string; duration: number; status: string; jitsi_room_id: string; jitsi_room_url: string; payment_id: string; payment_status: string; amount: number; notes: string; } interface BookingsResponse { bookings: Booking[]; limit: number; offset: number; total: number; } export default function BookNowPage() { const router = useRouter(); const { theme } = useAppTheme(); const isDark = theme === "dark"; const { isAuthenticated, logout } = useAuth(); const [formData, setFormData] = useState({ firstName: "", lastName: "", email: "", phone: "", preferredDays: [] as string[], preferredTimes: [] as string[], message: "", }); const [loading, setLoading] = useState(false); const [booking, setBooking] = useState(null); const [error, setError] = useState(null); const [showLoginDialog, setShowLoginDialog] = useState(false); const handleLogout = () => { logout(); toast.success("Logged out successfully"); router.push("/"); }; // Handle submit button click const handleSubmit = async (e: React.FormEvent) => { e.preventDefault(); // Open login dialog instead of submitting directly setShowLoginDialog(true); }; const handleLoginSuccess = async () => { // After successful login, proceed with booking submission await submitBooking(); }; const submitBooking = async () => { setLoading(true); setError(null); try { if (formData.preferredDays.length === 0) { setError("Please select at least one available day."); setLoading(false); return; } if (formData.preferredTimes.length === 0) { setError("Please select at least one preferred time."); setLoading(false); return; } // For now, we'll use the first selected day and first selected time // This can be adjusted based on your backend requirements const firstDay = formData.preferredDays[0]; const firstTime = formData.preferredTimes[0]; const timeMap: { [key: string]: string } = { morning: "09:00", lunchtime: "12:00", afternoon: "14:00", }; const time24 = timeMap[firstTime] || "09:00"; // Get next occurrence of the first selected day const today = new Date(); const days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday']; const targetDayIndex = days.indexOf(firstDay); let daysUntilTarget = (targetDayIndex - today.getDay() + 7) % 7; if (daysUntilTarget === 0) daysUntilTarget = 7; // Next week if today const targetDate = new Date(today); targetDate.setDate(today.getDate() + daysUntilTarget); const dateString = targetDate.toISOString().split("T")[0]; // Combine date and time into scheduled_at (ISO format) const dateTimeString = `${dateString}T${time24}:00Z`; // Prepare request payload const payload = { first_name: formData.firstName, last_name: formData.lastName, email: formData.email, phone: formData.phone, scheduled_at: dateTimeString, duration: 60, // Default to 60 minutes preferred_days: formData.preferredDays, preferred_times: formData.preferredTimes, notes: formData.message || "", }; // Simulate API call - Replace with actual API endpoint const response = await fetch("/api/bookings", { method: "POST", headers: { "Content-Type": "application/json", }, body: JSON.stringify(payload), }).catch(() => { // Fallback to mock data if API is not available return null; }); let bookingData: Booking; if (response && response.ok) { const data: BookingsResponse = await response.json(); bookingData = data.bookings[0]; } else { // Mock response for development - matches the API structure provided await new Promise((resolve) => setTimeout(resolve, 1000)); bookingData = { ID: Math.floor(Math.random() * 1000), CreatedAt: new Date().toISOString(), UpdatedAt: new Date().toISOString(), DeletedAt: null, user_id: 1, user: { ID: 1, CreatedAt: new Date().toISOString(), UpdatedAt: new Date().toISOString(), DeletedAt: null, first_name: formData.firstName, last_name: formData.lastName, email: formData.email, phone: formData.phone, location: "", date_of_birth: "0001-01-01T00:00:00Z", is_admin: false, bookings: null, }, scheduled_at: dateTimeString, duration: 60, status: "scheduled", jitsi_room_id: `booking-${Math.floor(Math.random() * 1000)}-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`, jitsi_room_url: `https://meet.jit.si/booking-${Math.floor(Math.random() * 1000)}-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`, payment_id: "", payment_status: "pending", amount: 52, notes: formData.message || "Initial consultation session", }; } setBooking(bookingData); setLoading(false); // Redirect to home after 2 seconds setTimeout(() => { router.push("/"); }, 2000); } catch (err) { setError("Failed to submit booking. Please try again."); setLoading(false); console.error("Booking error:", err); } }; const handleChange = (field: string, value: string) => { setFormData((prev) => ({ ...prev, [field]: value })); }; const handleDayToggle = (day: string) => { setFormData((prev) => { const days = prev.preferredDays.includes(day) ? prev.preferredDays.filter((d) => d !== day) : [...prev.preferredDays, day]; return { ...prev, preferredDays: days }; }); }; const handleTimeToggle = (time: string) => { setFormData((prev) => { const times = prev.preferredTimes.includes(time) ? prev.preferredTimes.filter((t) => t !== time) : [...prev.preferredTimes, time]; return { ...prev, preferredTimes: times }; }); }; const formatDateTime = (dateString: string) => { const date = new Date(dateString); return date.toLocaleString("en-US", { month: "short", day: "numeric", year: "numeric", hour: "numeric", minute: "2-digit", hour12: true, }); }; return (
{/* Main Content */}
{/* Left Side - Image (Fixed) */}
Therapy session with diverse clients
{/* Logo at Top */}
Attune Heart Therapy
{/* Overlay Content - Lower Position */}

Begin Your Journey to Wellness

Take the first step towards healing and growth. Our compassionate team is here to support you every step of the way.

{/* Features List */}
Safe and confidential environment
Experienced licensed therapists
Personalized treatment plans
Flexible scheduling options
{/* Right Side - Form (Scrollable) */}
{/* Page Header */}

Book Your Appointment

Fill out the form below and we'll get back to you to confirm your appointment

{/* Booking Form or Success Message */}
{booking ? (

Booking Confirmed!

Your appointment has been successfully booked.

Booking ID

#{booking.ID}

Patient

{booking.user.first_name} {booking.user.last_name}

Scheduled Time

{formatDateTime(booking.scheduled_at)}

Duration

{booking.duration} minutes

Status

{booking.status}

Amount

${booking.amount}

{booking.notes && (

Notes

{booking.notes}

)}
) : ( <>
{error && (

{error}

)}
{/* Personal Information Section */}

Personal Information

handleChange("firstName", e.target.value) } required className={`h-11 ${isDark ? 'bg-gray-700 border-gray-600 text-white placeholder:text-gray-400' : 'bg-white border-gray-300 text-gray-900 placeholder:text-gray-500'}`} />
handleChange("lastName", e.target.value) } required className={`h-11 ${isDark ? 'bg-gray-700 border-gray-600 text-white placeholder:text-gray-400' : 'bg-white border-gray-300 text-gray-900 placeholder:text-gray-500'}`} />
handleChange("email", e.target.value)} required className={`h-11 ${isDark ? 'bg-gray-700 border-gray-600 text-white placeholder:text-gray-400' : 'bg-white border-gray-300 text-gray-900 placeholder:text-gray-500'}`} />
handleChange("phone", e.target.value)} required className={`h-11 ${isDark ? 'bg-gray-700 border-gray-600 text-white placeholder:text-gray-400' : 'bg-white border-gray-300 text-gray-900 placeholder:text-gray-500'}`} />
{/* Appointment Details Section */}

Appointment Details

{['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday'].map((day) => ( ))}
{[ { value: 'morning', label: 'Morning' }, { value: 'lunchtime', label: 'Lunchtime' }, { value: 'afternoon', label: 'Afternoon' } ].map((time) => ( ))}
{/* Additional Message Section */}