import { CustomModal } from "@ui/components/CustomModal";
import { useSession } from "@xtablo/shared/contexts/SessionContext";
import { useTheme } from "@xtablo/shared/contexts/ThemeContext";
import { TimeSlot, usePublicSlots } from "@xtablo/shared/hooks/public";
import { Button } from "@xtablo/ui/components/button";
import { FieldError } from "@xtablo/ui/components/field";
import { Input } from "@xtablo/ui/components/input";
import { Label } from "@xtablo/ui/components/label";
import {
  Text,
  TypographyH3,
  TypographyH4,
  TypographyMuted,
} from "@xtablo/ui/components/typography";
import {
  CalendarCheck2,
  CalendarIcon,
  ChevronLeftIcon,
  ChevronRightIcon,
  ClockIcon,
  MapPinIcon,
  MonitorIcon,
  MoonIcon,
  SunIcon,
  UserIcon,
} from "lucide-react";
import { useEffect, useState } from "react";
import { useParams } from "react-router-dom";
import { twMerge } from "tailwind-merge";
import { useBookSlot } from "../hooks/book";
import { api } from "../lib/api";

export function PublicBookingPage() {
  const { user_info, event_type_standard_name } = useParams<{
    user_info: string;
    event_type_standard_name: string;
  }>();
  // const { mutateAsync: signUpWithoutPassword, isPending: isSigningUpWithoutPassword } =
  //   useSignUpWithoutPassword(supabase, api);
  const { session } = useSession();
  const user = session ? session.user : null;

  const shortUserId = user_info?.substring(user_info.lastIndexOf("-") + 1);

  const { data: publicSlots, isLoading: isLoadingSlots } = usePublicSlots(
    api,
    shortUserId || "",
    event_type_standard_name || ""
  );

  const { mutateAsync: bookSlot, isPending: isBookingSlot } = useBookSlot(
    api,
    session?.access_token
  );

  const isPending = isBookingSlot;

  const userProfile = publicSlots?.user;
  const eventType = publicSlots?.eventType;
  const slotsData = publicSlots?.slots || {};

  // Calendar state
  const [currentDate, setCurrentDate] = useState(new Date());
  const [selectedDate, setSelectedDate] = useState<Date | null>(null);

  // Modal state
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [selectedSlot, setSelectedSlot] = useState<{
    date: Date;
    slot: TimeSlot;
  } | null>(null);

  const [formData, setFormData] = useState({
    email: "",
    name: "",
  });
  const [formErrors, setFormErrors] = useState({
    email: "",
    name: "",
  });

  // Loading messages rotation
  const loadingMessages = [
    "Nous créons votre rendez-vous, veuillez patienter",
    "Creation de votre compte...",
    "Préparation de votre réservation...",
    "Configuration de votre appel...",
    "Finalisation de votre créneau...",
  ];
  const [currentMessageIndex, setCurrentMessageIndex] = useState(0);

  useEffect(() => {
    setCurrentMessageIndex(0);
    if (isPending) {
      const interval = setInterval(() => {
        setCurrentMessageIndex((prev) => (prev + 1) % loadingMessages.length);
      }, 1000);

      return () => clearInterval(interval);
    }
  }, [isPending]);

  // Theme
  const { theme, setTheme } = useTheme();

  const toggleTheme = () => {
    setTheme(theme === "light" ? "dark" : "light");
  };

  const getThemeIcon = () => {
    switch (theme) {
      case "light":
        return <SunIcon className="w-5 h-5" />;
      case "dark":
        return <MoonIcon className="w-5 h-5" />;
      case "system":
        return <MonitorIcon className="w-5 h-5" />;
      default:
        return <SunIcon className="w-5 h-5" />;
    }
  };

  // Helper function to convert date to CET timezone string (YYYY-MM-DD)
  const formatDateToCET = (date: Date): string => {
    return date.toLocaleDateString("sv-SE", { timeZone: "Europe/Paris" });
  };

  // Helper function to get current date in CET timezone
  const getCurrentDateInCET = (): Date => {
    const now = new Date();
    const cetTime = new Date(now.toLocaleString("en-US", { timeZone: "Europe/Paris" }));
    return cetTime;
  };

  // Get available time slots for a specific date
  const getAvailableSlots = (date: Date): TimeSlot[] => {
    const dateStr = formatDateToCET(date);
    return slotsData[dateStr]?.filter((slot) => slot.available) || [];
  };

  // Check if a date has any available slots
  const hasAvailableSlots = (date: Date): boolean => {
    const dateStr = formatDateToCET(date);
    return slotsData[dateStr]?.some((slot) => slot.available) || false;
  };

  // Calendar helper functions
  const getDaysInMonth = (date: Date) => {
    const year = date.getFullYear();
    const month = date.getMonth();

    // Create first day of month and get its day of week in CET
    const firstDayStr = `${year}-${String(month + 1).padStart(2, "0")}-01`;
    const firstDay = new Date(`${firstDayStr}T12:00:00`);
    const firstDayOfWeekInCET = new Date(
      firstDay.toLocaleString("en-US", { timeZone: "Europe/Paris" })
    ).getDay();

    // Adjust for Monday as first day of week
    const mondayStartingDay = firstDayOfWeekInCET === 0 ? 6 : firstDayOfWeekInCET - 1;

    // Get number of days in month
    const lastDay = new Date(year, month + 1, 0);
    const daysInMonth = lastDay.getDate();

    const days = [];

    // Add empty cells for days before the first day of the month
    for (let i = 0; i < mondayStartingDay; i++) {
      days.push(null);
    }

    // Add all days of the month
    for (let day = 1; day <= daysInMonth; day++) {
      const dayStr = `${year}-${String(month + 1).padStart(2, "0")}-${String(day).padStart(
        2,
        "0"
      )}`;
      days.push(new Date(`${dayStr}T12:00:00`));
    }

    return days;
  };

  const navigateMonth = (direction: "prev" | "next") => {
    setCurrentDate((prev) => {
      const newDate = new Date(prev);
      if (direction === "prev") {
        newDate.setMonth(prev.getMonth() - 1);
      } else {
        newDate.setMonth(prev.getMonth() + 1);
      }
      return newDate;
    });
  };

  const isToday = (date: Date) => {
    const todayInCET = getCurrentDateInCET();
    const todayStr = formatDateToCET(todayInCET);
    const dateStr = formatDateToCET(date);
    return dateStr === todayStr;
  };

  const isPastDate = (date: Date) => {
    const todayInCET = getCurrentDateInCET();
    const todayStr = formatDateToCET(todayInCET);
    const dateStr = formatDateToCET(date);
    return dateStr < todayStr;
  };

  const formatMonthYear = (date: Date) => {
    return date.toLocaleDateString("fr-FR", { month: "long", year: "numeric" });
  };

  const formatDuration = (minutes: number) => {
    if (minutes < 60) {
      return `${minutes} min`;
    }
    const hours = Math.floor(minutes / 60);
    const remainingMinutes = minutes % 60;
    if (remainingMinutes === 0) {
      return `${hours}h`;
    }
    return `${hours}h ${remainingMinutes}min`;
  };

  // Modal and form handlers
  const handleSlotClick = (date: Date, slot: TimeSlot) => {
    setSelectedSlot({ date, slot });
    setIsModalOpen(true);
    setFormData({ email: "", name: "" });
    setFormErrors({ email: "", name: "" });
  };

  const handleCloseModal = () => {
    setIsModalOpen(false);
    setSelectedSlot(null);
    setFormData({ email: "", name: "" });
    setFormErrors({ email: "", name: "" });
  };

  const validateForm = () => {
    if (user) {
      return true;
    }

    const errors = { email: "", name: "" };
    let isValid = true;

    if (!formData.email.trim()) {
      errors.email = "L'adresse email est requise";
      isValid = false;
    } else if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(formData.email)) {
      errors.email = "Veuillez entrer une adresse email valide";
      isValid = false;
    }

    if (!formData.name.trim()) {
      errors.name = "Le nom est requis";
      isValid = false;
    }

    setFormErrors(errors);
    return isValid;
  };

  // Calculate end time based on start time and duration
  const calculateEndTime = (startTime: string, durationMinutes: number): string => {
    if (!startTime) return "";

    const [hours, minutes] = startTime.split(":").map(Number);
    const startDate = new Date();
    startDate.setHours(hours, minutes, 0, 0);

    const endDate = new Date(startDate.getTime() + durationMinutes * 60000);

    return endDate.toTimeString().slice(0, 5); // Format as HH:MM
  };

  const handleBookSlot = () => {
    if (!validateForm()) {
      return;
    }

    const startTime = selectedSlot?.slot.time || "";
    const duration = eventType?.duration || 60; // duration in minutes
    const endTime = calculateEndTime(startTime, duration);

    const userDetails = user
      ? {
          name: user.user_metadata.name,
          email: user.email || "",
        }
      : {
          name: formData.name,
          email: formData.email,
        };

    bookSlot({
      event_type_standard_name: event_type_standard_name as string,
      owner_short_id: shortUserId || "",
      event_details: {
        start_date: selectedSlot?.slot.date || "",
        start_time: selectedSlot?.slot.time || "",
        end_time: endTime || "",
      },
      user_details: userDetails,
    });

    handleCloseModal();
  };

  // const handleSubmitIfNotLoggedIn = async () => {
  //   if (validateForm()) {
  //     const { session: sessionFromSignUp } = await signUpWithoutPassword({
  //       email: formData.email,
  //       name: formData.name,
  //     });

  //     const startTime = selectedSlot?.slot.time || "";
  //     const duration = eventType?.duration || 60; // duration in minutes
  //     const endTime = calculateEndTime(startTime, duration);

  //     await createTabloWithOwner({
  //       name: eventType?.name || "",
  //       status: "todo",
  //       owner_short_id: shortUserId || "",
  //       event: {
  //         description: eventType?.description || "",
  //         end_time: endTime || "",
  //         start_date: selectedSlot?.slot.date || "",
  //         start_time: selectedSlot?.slot.time || "",
  //         title: eventType?.name || "",
  //       } as EventInsertInTablo,
  //       access_token: sessionFromSignUp?.access_token || "",
  //     });

  //     handleCloseModal();
  //   }
  // };

  // const handleSubmitIfLoggedIn = async () => {
  //   if (user) {
  //     const startTime = selectedSlot?.slot.time || "";
  //     const duration = eventType?.duration || 60; // duration in minutes
  //     const endTime = calculateEndTime(startTime, duration);

  //     await createTabloWithOwner({
  //       name: eventType?.name || "",
  //       status: "todo",
  //       owner_short_id: shortUserId || "",
  //       event: {
  //         description: eventType?.description || "",
  //         end_time: endTime || "",
  //         start_date: selectedSlot?.slot.date || "",
  //         start_time: selectedSlot?.slot.time || "",
  //         title: eventType?.name || "",
  //       } as EventInsertInTablo,
  //       access_token: session?.access_token || "",
  //     });

  //     handleCloseModal();
  //   }
  // };

  return (
    <div className="min-h-screen bg-gradient-to-br from-gray-50 to-gray-100 dark:from-gray-900 dark:to-gray-800 p-4 md:p-8">
      <div className="max-w-7xl mx-auto">
        {/* Theme Toggle - Floating */}
        <div className="absolute top-4 right-4 z-20">
          <Button
            variant="ghost"
            size="icon"
            onClick={toggleTheme}
            className="text-gray-500 hover:text-gray-700 dark:text-gray-400 dark:hover:text-gray-200 bg-white/80 dark:bg-gray-800/80 backdrop-blur-sm shadow-lg"
            aria-label={`Changer le thème (actuellement: ${theme})`}
          >
            {getThemeIcon()}
          </Button>
        </div>

        {/* Main Card */}
        <div className="bg-white dark:bg-gray-800 rounded-2xl border border-gray-200 dark:border-gray-700 shadow-2xl overflow-hidden">
          <div className="flex flex-col lg:flex-row min-h-[700px]">
            {/* Left Panel - User Profile & Event Details */}
            <div className="w-full lg:w-[400px] bg-linear-to-br from-gray-900 via-gray-800 to-gray-900 dark:from-purple-900 dark:via-purple-800 dark:to-purple-900 p-8 flex flex-col relative overflow-hidden">
              {/* Subtle accent overlay */}
              <div className="absolute inset-0 bg-linear-to-br from-purple-600/5 via-transparent to-purple-600/10 pointer-events-none"></div>

              <div className="relative z-10 flex flex-col h-full">
                {/* User Profile */}
                <div className="mb-8">
                  {userProfile?.avatar_url ? (
                    <img
                      src={userProfile.avatar_url}
                      alt={userProfile.name || "Profile"}
                      className="w-20 h-20 rounded-full object-cover border-4 border-purple-500/30 mb-4"
                    />
                  ) : (
                    <div className="w-20 h-20 rounded-full bg-gray-700 flex items-center justify-center border-4 border-purple-500/30 mb-4">
                      <UserIcon className="w-10 h-10 text-gray-300" />
                    </div>
                  )}
                  <h2 className="text-2xl font-bold mb-1 text-white">
                    {userProfile?.name || "Professionnel"}
                  </h2>
                </div>

                {/* Event Type Info */}
                <div className="flex-1">
                  <h3 className="text-xl font-bold mb-3 text-white">
                    {eventType?.name || "Type d'appel"}
                  </h3>

                  {eventType?.description && (
                    <TypographyMuted className="mb-6 text-sm leading-relaxed text-gray-400">
                      {eventType.description}
                    </TypographyMuted>
                  )}

                  <div className="space-y-4">
                    {eventType?.duration && (
                      <div className="flex items-center gap-3">
                        <div className="w-10 h-10 rounded-lg bg-gray-700/50 border border-purple-500/20 flex items-center justify-center shrink-0">
                          <ClockIcon className="w-5 h-5 text-purple-400" />
                        </div>
                        <div>
                          <p className="text-xs text-gray-400">Durée</p>
                          <p className="font-semibold text-white">
                            {formatDuration(eventType.duration)}
                          </p>
                        </div>
                      </div>
                    )}

                    {eventType?.price && (
                      <div className="flex items-center gap-3">
                        <div className="w-10 h-10 rounded-lg bg-gray-700/50 border border-purple-500/20 flex items-center justify-center shrink-0">
                          <span className="text-xl font-bold text-purple-400">€</span>
                        </div>
                        <div>
                          <p className="text-xs text-gray-400">Prix</p>
                          <p className="font-semibold text-white">{eventType.price}€</p>
                        </div>
                      </div>
                    )}

                    {eventType?.location && (
                      <div className="flex items-center gap-3">
                        <div className="w-10 h-10 rounded-lg bg-gray-700/50 border border-purple-500/20 flex items-center justify-center shrink-0">
                          <MapPinIcon className="w-5 h-5 text-purple-400" />
                        </div>
                        <div>
                          <p className="text-xs text-gray-400">Lieu</p>
                          <p className="font-semibold text-sm text-white">{eventType.location}</p>
                        </div>
                      </div>
                    )}
                  </div>
                </div>

                {/* Footer */}
                <div className="mt-auto pt-6 border-t border-gray-700/50">
                  <div className="mb-4">
                    <img src="/logo_white.png" alt="Xtablo" className="h-8 w-auto" />
                  </div>
                  <TypographyMuted className="text-xs text-gray-500">
                    Propulsé par{" "}
                    <a
                      href="https://www.xtablo.com"
                      target="_blank"
                      rel="noopener noreferrer"
                      className="hover:underline text-purple-400/60"
                    >
                      XTablo
                    </a>
                  </TypographyMuted>
                </div>
              </div>
            </div>

            {/* Right Panel - Calendar & Time Slots */}
            <div className="flex-1 flex flex-col p-6 lg:p-8 relative">
              {/* Loading Overlay for Calendar/Slots */}
              {isLoadingSlots && (
                <div className="absolute inset-0 bg-white/80 dark:bg-gray-800/80 backdrop-blur-sm z-10 flex items-center justify-center rounded-lg">
                  <div className="flex flex-col items-center gap-4">
                    <div className="text-center">
                      <Text className="text-gray-900 dark:text-white font-semibold">
                        Chargement des disponibilités...
                      </Text>
                    </div>
                  </div>
                </div>
              )}

              <div className="flex-1 flex flex-col lg:flex-row gap-6">
                {/* Calendar */}
                <div className="flex-1">
                  <div className="flex items-center justify-between mb-6">
                    <TypographyH3 className="font-semibold text-gray-900 dark:text-white capitalize">
                      {formatMonthYear(currentDate)}
                    </TypographyH3>
                    <div className="flex gap-1">
                      <Button
                        variant="ghost"
                        size="icon"
                        onClick={() => navigateMonth("prev")}
                        className="h-8 w-8 text-gray-500 hover:text-gray-700 dark:text-gray-400 dark:hover:text-gray-200"
                      >
                        <ChevronLeftIcon className="w-4 h-4" />
                      </Button>
                      <Button
                        variant="ghost"
                        size="icon"
                        onClick={() => navigateMonth("next")}
                        className="h-8 w-8 text-gray-500 hover:text-gray-700 dark:text-gray-400 dark:hover:text-gray-200"
                      >
                        <ChevronRightIcon className="w-4 h-4" />
                      </Button>
                    </div>
                  </div>

                  {/* Calendar Grid */}
                  <div className="grid grid-cols-7 gap-1 mb-2">
                    {["Lun", "Mar", "Mer", "Jeu", "Ven", "Sam", "Dim"].map((day) => (
                      <div
                        key={day}
                        className="p-1 text-center text-xs font-medium text-gray-500 dark:text-gray-400"
                      >
                        {day}
                      </div>
                    ))}
                  </div>

                  <div className="grid grid-cols-7 gap-1">
                    {getDaysInMonth(currentDate).map((date, index) => (
                      <div key={index} className="aspect-square">
                        {date ? (
                          <button
                            onClick={() =>
                              !isPastDate(date) && hasAvailableSlots(date) && setSelectedDate(date)
                            }
                            disabled={isPastDate(date) || !hasAvailableSlots(date)}
                            className={twMerge(
                              "w-full h-full flex items-center justify-center text-sm rounded-lg transition-colors",
                              isPastDate(date)
                                ? "text-gray-300 dark:text-gray-600 cursor-not-allowed"
                                : selectedDate?.toDateString() === date.toDateString()
                                  ? "bg-purple-600 dark:bg-purple-500 text-white font-semibold shadow-md ring-2 ring-purple-500/50"
                                  : isToday(date)
                                    ? "bg-gray-100 dark:bg-gray-700 text-gray-900 dark:text-white font-semibold border border-purple-500/30"
                                    : hasAvailableSlots(date)
                                      ? "text-gray-700 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-700 hover:border-purple-500/50 border border-gray-200 dark:border-gray-600"
                                      : "text-gray-400 dark:text-gray-500 cursor-not-allowed"
                            )}
                          >
                            {date.getDate()}
                          </button>
                        ) : (
                          <div></div>
                        )}
                      </div>
                    ))}
                  </div>
                </div>

                {/* Time Slots */}
                <div className="w-full lg:w-64 lg:border-l border-t lg:border-t-0 pt-6 lg:pt-0 border-gray-200 dark:border-gray-700 lg:pl-6">
                  <TypographyH4 className="font-semibold text-gray-900 dark:text-white mb-4">
                    {selectedDate ? (
                      <>
                        Créneaux disponibles
                        <br />
                        <TypographyMuted className="text-sm font-normal text-gray-500 dark:text-gray-400">
                          {selectedDate.toLocaleDateString("fr-FR", {
                            weekday: "long",
                            day: "numeric",
                            month: "long",
                          })}
                        </TypographyMuted>
                      </>
                    ) : (
                      "Sélectionnez une date"
                    )}
                  </TypographyH4>

                  {selectedDate ? (
                    <div className="space-y-2 max-h-[500px] overflow-y-auto pr-1">
                      {getAvailableSlots(selectedDate).map((slot, index) => (
                        <Button
                          key={index}
                          variant="outline"
                          size="sm"
                          className="w-full justify-center text-sm py-2 text-gray-900 dark:text-gray-100 border-gray-300 dark:border-gray-600 hover:bg-purple-600 dark:hover:bg-purple-500 hover:text-white dark:hover:text-white hover:border-purple-500/50 transition-all"
                          onClick={() => handleSlotClick(selectedDate, slot)}
                        >
                          {slot.time}
                        </Button>
                      ))}

                      {getAvailableSlots(selectedDate).length === 0 && (
                        <div className="text-center py-8">
                          <Text className="text-xs text-gray-500 dark:text-gray-400">
                            Aucun créneau disponible ce jour
                          </Text>
                        </div>
                      )}
                    </div>
                  ) : (
                    <div className="text-center py-8">
                      <CalendarIcon className="w-8 h-8 text-gray-300 dark:text-gray-600 mx-auto mb-2" />
                      <Text className="text-xs text-gray-500 dark:text-gray-400">
                        Choisissez une date dans le calendrier
                      </Text>
                    </div>
                  )}
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>

      {/* Loading Overlay */}
      {isPending && (
        <div className="fixed inset-0 bg-black/60 backdrop-blur-sm z-[100] flex items-center justify-center">
          <div className="bg-white dark:bg-gray-800 rounded-2xl shadow-2xl p-8 w-md mx-4 border border-gray-200 dark:border-gray-700">
            <div className="flex flex-col items-center gap-6">
              {/* Animated Icon */}
              <div className="relative">
                <div className="w-20 h-20 rounded-full bg-gradient-to-br from-purple-500 to-blue-500 flex items-center justify-center animate-pulse">
                  <CalendarCheck2 className="w-10 h-10 text-white" />
                </div>
                <div className="absolute inset-0 rounded-full border-4 border-purple-500/30 animate-ping"></div>
              </div>

              {/* Text */}
              <div className="text-center space-y-2">
                <TypographyH3 className="text-gray-900 dark:text-white">
                  Réservation en cours...
                </TypographyH3>
                <TypographyMuted className="text-gray-600 dark:text-gray-400">
                  {loadingMessages[currentMessageIndex]}
                </TypographyMuted>
              </div>

              {/* Loading Spinner */}
              <div className="flex gap-2">
                <div
                  className="w-3 h-3 rounded-full bg-purple-500 animate-bounce"
                  style={{ animationDelay: "0ms" }}
                ></div>
                <div
                  className="w-3 h-3 rounded-full bg-purple-500 animate-bounce"
                  style={{ animationDelay: "150ms" }}
                ></div>
                <div
                  className="w-3 h-3 rounded-full bg-purple-500 animate-bounce"
                  style={{ animationDelay: "300ms" }}
                ></div>
              </div>
            </div>
          </div>
        </div>
      )}

      {/* Booking Modal */}
      <CustomModal
        isOpen={isModalOpen}
        onClose={handleCloseModal}
        title={user ? "Confirmer la réservation" : "Créer un compte pour réserver"}
        width="md"
      >
        {selectedSlot && (
          <div className="mb-6 p-4 bg-gray-100 dark:bg-gray-800 rounded-lg border border-purple-500/20">
            <div className="flex items-center gap-2 text-gray-900 dark:text-gray-100">
              <CalendarIcon className="w-4 h-4 text-purple-600 dark:text-purple-400" />
              <Text className="font-medium">
                {selectedSlot.date.toLocaleDateString("fr-FR", {
                  weekday: "long",
                  day: "numeric",
                  month: "long",
                })}
              </Text>
            </div>
            <div className="flex items-center gap-2 text-gray-900 dark:text-gray-100 mt-1">
              <ClockIcon className="w-4 h-4 text-purple-600 dark:text-purple-400" />
              <Text className="font-medium">{selectedSlot.slot.time}</Text>
            </div>
          </div>
        )}

        <div className="space-y-4">
          <div className="space-y-2">
            <Label htmlFor="name">
              Nom complet <span className="text-red-500">*</span>
            </Label>
            <Input
              id="name"
              type="text"
              placeholder="Votre nom complet"
              value={
                user
                  ? `${user.user_metadata.first_name} ${user.user_metadata.last_name}`
                  : formData.name
              }
              onChange={(e) => setFormData((prev) => ({ ...prev, name: e.target.value }))}
              disabled={!!user}
            />
            {formErrors.name && <FieldError errors={[{ message: formErrors.name }]} />}
          </div>

          <div className="space-y-2">
            <Label htmlFor="email">
              Adresse email <span className="text-red-500">*</span>
            </Label>
            <Input
              id="email"
              type="email"
              placeholder="votre@email.com"
              value={user?.email || formData.email}
              onChange={(e) => setFormData((prev) => ({ ...prev, email: e.target.value }))}
              disabled={!!user}
            />
            {formErrors.email && <FieldError errors={[{ message: formErrors.email }]} />}
          </div>

          {!user && (
            <div className="pt-2">
              <Text className="text-sm text-gray-600 dark:text-gray-400">
                Un compte sera créé avec ces informations pour gérer votre réservation.
              </Text>
            </div>
          )}
        </div>

        <div className="flex justify-end gap-3 mt-6 pt-4 border-t border-gray-200 dark:border-gray-700">
          <Button variant="outline" onClick={handleCloseModal}>
            Annuler
          </Button>
          <Button
            variant="default"
            onClick={handleBookSlot}
            // isPending={user ? isCreatingTablo : isSigningUpWithoutPassword}
            // pendingLabel={user ? "Réservation..." : "Création du compte..."}
          >
            {user ? "Confirmer la réservation" : "Créer le compte et réserver"}
          </Button>
        </div>
      </CustomModal>
    </div>
  );
}
