"use client";

import React, { useState, useRef } from "react";
import { motion, useInView, AnimatePresence } from "framer-motion";
import { Card, CardContent } from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { Button } from "@/components/ui/button";
import {
  Phone,
  Calendar,
  AlertTriangle,
  Check,
  ChevronLeft,
  ChevronRight,
  Calendar as CalendarIcon,
} from "lucide-react";

interface TimeSlot {
  startTime: Date;
  endTime: Date;
  available: boolean;
}

export function Booking() {
  const ref = useRef(null);
  const isInView = useInView(ref, { once: true, margin: "-100px" });
  const [step, setStep] = useState(1);
  const [formData, setFormData] = useState({
    phone: "",
    name: "",
    email: "",
  });
  const [isCrisis, setIsCrisis] = useState(false);
  const [isLoading, setIsLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [patientExists, setPatientExists] = useState<boolean | null>(null);
  const [selectedDate, setSelectedDate] = useState<Date | null>(null);
  const [availableSlots, setAvailableSlots] = useState<TimeSlot[]>([]);
  const [selectedSlot, setSelectedSlot] = useState<TimeSlot | null>(null);
  const [currentWeekStart, setCurrentWeekStart] = useState<Date>(new Date());
  const [appointmentSuccess, setAppointmentSuccess] = useState(false);

  const formatTimeDisplay = (date: Date): string => {
    return new Date(date).toLocaleTimeString("es-CO", {
      hour: "2-digit",
      minute: "2-digit",
    });
  };

  const formatDateDisplay = (date: Date): string => {
    return new Date(date).toLocaleDateString("es-CO", {
      weekday: "long",
      day: "numeric",
      month: "long",
    });
  };

  const formatDateForInput = (date: Date): string => {
    return date.toISOString().split("T")[0];
  };

  const handleDateSelect = (e: React.ChangeEvent<HTMLInputElement>) => {
    setSelectedDate(new Date(e.target.value));
    setSelectedSlot(null);
    setError(null);
  };

  const handleSlotSelect = (slot: TimeSlot) => {
    setSelectedSlot(slot);
    setError(null);
  };

  const handlePhoneSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setIsLoading(true);
    setError(null);

    try {
      const response = await fetch("/api/patients/search", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify({ phone: formData.phone }),
      });

      const data = await response.json();

      if (response.status === 429) {
        setError(
          `Demasiados intentos. Intenta nuevamente en ${Math.ceil((new Date(data.resetTime).getTime() - Date.now()) / 60000)} minutos.`
        );
        setIsLoading(false);
        return;
      }

      if (!response.ok) {
        setError("Error al buscar el paciente. Por favor intenta nuevamente.");
        setIsLoading(false);
        return;
      }

      if (data.exists) {
        setPatientExists(true);
        setStep(3);
      } else {
        setPatientExists(false);
        setStep(2);
      }
    } catch (error) {
      console.error("Phone submit error:", error);
      setError("Error de conexión. Por favor intenta nuevamente.");
      setIsLoading(false);
    } finally {
      setIsLoading(false);
    }
  };

  const handleRegistrationSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setIsLoading(true);
    setError(null);

    try {
      const response = await fetch("/api/patients/register", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify({
          phone: formData.phone,
          name: formData.name,
          email: formData.email,
        }),
      });

      const data = await response.json();

      if (response.status === 429) {
        setError(
          `Demasiados intentos. Intenta nuevamente en ${Math.ceil((new Date(data.resetTime).getTime() - Date.now()) / 60000)} minutos.`
        );
        setIsLoading(false);
        return;
      }

      if (response.status === 409) {
        setError("Este número de teléfono ya está registrado.");
        setIsLoading(false);
        return;
      }

      if (!response.ok) {
        setError("Error al registrar el paciente. Por favor intenta nuevamente.");
        setIsLoading(false);
        return;
      }

      setStep(3);
    } catch (error) {
      console.error("Registration submit error:", error);
      setError("Error de conexión. Por favor intenta nuevamente.");
      setIsLoading(false);
    } finally {
      setIsLoading(false);
    }
  };

  const handleCrisisResponse = (isCrisis: boolean) => {
    setIsCrisis(isCrisis);
    if (isCrisis) {
      setStep(5);
    } else {
      setStep(4);
    }
  };

  const fetchAvailability = async (startDate: Date) => {
    setIsLoading(true);
    setError(null);

    try {
      const endDate = new Date(startDate);
      endDate.setDate(endDate.getDate() + 7);

      const response = await fetch("/api/calendar/availability", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify({
          startDate: startDate.toISOString(),
          endDate: endDate.toISOString(),
        }),
      });

      const data = await response.json();

      if (response.ok) {
        setAvailableSlots(data.availability || []);
        setError(null);
      } else {
        setError(data.error || "Error al cargar disponibilidad.");
      }
    } catch (error) {
      console.error("Fetch availability error:", error);
      setError("Error de conexión. Por favor intenta nuevamente.");
    } finally {
      setIsLoading(false);
    }
  };

  const handleAppointmentSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setIsLoading(true);
    setError(null);

    if (!selectedSlot) {
      setError("Por favor selecciona un horario.");
      setIsLoading(false);
      return;
    }

    try {
      const response = await fetch("/api/calendar/create-event", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify({
          summary: `Cita con ${formData.name}`,
          description: "Nueva sesión terapéutica",
          start: selectedSlot.startTime,
          patientPhone: formData.phone,
          patientName: formData.name,
          email: formData.email || undefined,
          isCrisis: false,
        }),
      });

      const data = await response.json();

      if (response.ok && data.success) {
        setAppointmentSuccess(true);
        setStep(6);
      } else {
        setError(data.error || "Error al agendar cita. Por favor selecciona otro horario.");
      }
    } catch (error) {
      console.error("Appointment creation error:", error);
      setError("Error de conexión. Por favor intenta nuevamente.");
    } finally {
      setIsLoading(false);
    }
  };

  const resetBooking = () => {
    setStep(1);
    setFormData({ phone: "", name: "", email: "" });
    setSelectedDate(null);
    setSelectedSlot(null);
    setAvailableSlots([]);
    setError(null);
    setAppointmentSuccess(false);
  };

  return (
    <section id="agendar" className="bg-background py-20 sm:py-32" ref={ref}>
      <div className="container mx-auto px-4 sm:px-6 lg:px-8">
        <motion.div
          className="mb-12 text-center sm:mb-16"
          initial={{ opacity: 0, y: 20 }}
          animate={isInView ? { opacity: 1, y: 0 } : {}}
          transition={{ duration: 0.6 }}
        >
          <h2 className="mb-4 font-serif text-3xl font-bold text-primary sm:text-4xl lg:text-5xl">
            Agenda tu Cita
          </h2>
          <p className="mb-6 text-lg text-secondary">Primer paso: Ingresa tu número de teléfono</p>
          <motion.div
            className="mx-auto h-1 w-24 bg-accent"
            initial={{ width: 0 }}
            animate={isInView ? { width: 96 } : {}}
            transition={{ duration: 0.8, delay: 0.3 }}
          />
        </motion.div>

        <motion.div
          className="mx-auto max-w-2xl"
          initial={{ opacity: 0, y: 30 }}
          animate={isInView ? { opacity: 1, y: 0 } : {}}
          transition={{ duration: 0.8, delay: 0.4 }}
        >
          {/* Progress Steps */}
          <div className="mb-12 flex items-center justify-center space-x-4">
            {[1, 2, 3, 4, 5, 6].map((s) => (
              <React.Fragment key={s}>
                <motion.div
                  className={`flex h-10 w-10 items-center justify-center rounded-full ${
                    step >= s ? "bg-accent text-primary" : "bg-secondary/20 text-secondary"
                  }`}
                  initial={{ scale: 0 }}
                  animate={{ scale: 1 }}
                  transition={{ delay: s * 0.1 }}
                >
                  {step > s ? <Check className="h-5 w-5" /> : s}
                </motion.div>
                {s < 5 && (
                  <div className={`h-0.5 w-16 ${step > s ? "bg-accent" : "bg-secondary/20"}`} />
                )}
              </React.Fragment>
            ))}
          </div>

          {/* Step 1: Phone Input */}
          <AnimatePresence mode="wait">
            {step === 1 && (
              <motion.div
                key="step1"
                initial={{ opacity: 0, x: 20 }}
                animate={{ opacity: 1, x: 0 }}
                exit={{ opacity: 0, x: -20 }}
                transition={{ duration: 0.3 }}
              >
                <Card className="shadow-xl">
                  <CardContent className="p-8">
                    <div className="mb-6 text-center">
                      <motion.div
                        className="mx-auto mb-4 flex h-16 w-16 items-center justify-center rounded-full bg-accent/20"
                        whileHover={{ scale: 1.1, rotate: 5 }}
                        transition={{ type: "spring", stiffness: 400, damping: 17 }}
                      >
                        <Phone className="h-8 w-8 text-accent" />
                      </motion.div>
                      <h3 className="mb-2 font-serif text-2xl font-semibold text-primary">
                        Ingresa tu Teléfono
                      </h3>
                      <p className="text-secondary">
                        Usaremos tu número para identificar tu cuenta
                      </p>
                    </div>

                    <form onSubmit={handlePhoneSubmit} className="space-y-4">
                      <div>
                        <Input
                          type="tel"
                          placeholder="+52 55 1234 5678"
                          value={formData.phone}
                          onChange={(e) => {
                            setFormData({ ...formData, phone: e.target.value });
                            setError(null);
                          }}
                          required
                          pattern="[0-9+\s]{10,}"
                          className="h-14 text-center text-lg"
                          disabled={isLoading}
                        />
                      </div>

                      {error && (
                        <motion.div
                          className="rounded-lg border border-red-200 bg-red-50 px-4 py-2 text-sm text-red-700"
                          initial={{ opacity: 0, y: -10 }}
                          animate={{ opacity: 1, y: 0 }}
                        >
                          {error}
                        </motion.div>
                      )}

                      <Button
                        type="submit"
                        disabled={isLoading}
                        className="h-12 w-full bg-accent text-base text-primary hover:bg-accent/90"
                      >
                        {isLoading ? (
                          <span className="flex items-center">
                            <motion.div
                              className="mr-2 h-5 w-5 rounded-full border-2 border-white border-t-transparent"
                              animate={{ rotate: 360 }}
                              transition={{ duration: 1, repeat: Infinity, ease: "linear" }}
                            />
                            Buscando...
                          </span>
                        ) : (
                          "Continuar"
                        )}
                      </Button>
                    </form>
                  </CardContent>
                </Card>
              </motion.div>
            )}
          </AnimatePresence>

          {/* Step 2: Registration */}
          <AnimatePresence mode="wait">
            {step === 2 && (
              <motion.div
                key="step2"
                initial={{ opacity: 0, x: 20 }}
                animate={{ opacity: 1, x: 0 }}
                exit={{ opacity: 0, x: -20 }}
                transition={{ duration: 0.3 }}
              >
                <Card className="shadow-xl">
                  <CardContent className="p-8">
                    <div className="mb-6 text-center">
                      <CalendarIcon className="mx-auto mb-4 h-16 w-16 text-accent" />
                      <h3 className="mb-2 font-serif text-2xl font-semibold text-primary">
                        Regístrate
                      </h3>
                      <p className="text-secondary">Completa tu información para continuar</p>
                    </div>

                    <form onSubmit={handleRegistrationSubmit} className="space-y-4">
                      <div>
                        <Input
                          type="text"
                          placeholder="Nombre completo"
                          value={formData.name}
                          onChange={(e) => {
                            setFormData({ ...formData, name: e.target.value });
                            setError(null);
                          }}
                          required
                          disabled={isLoading}
                          className="h-12"
                        />
                      </div>

                      <div>
                        <Input
                          type="email"
                          placeholder="Email (opcional)"
                          value={formData.email}
                          onChange={(e) => {
                            setFormData({ ...formData, email: e.target.value });
                            setError(null);
                          }}
                          disabled={isLoading}
                          className="h-12"
                        />
                      </div>

                      {error && (
                        <motion.div
                          className="rounded-lg border border-red-200 bg-red-50 px-4 py-2 text-sm text-red-700"
                          initial={{ opacity: 0, y: -10 }}
                          animate={{ opacity: 1, y: 0 }}
                        >
                          {error}
                        </motion.div>
                      )}

                      <div className="flex space-x-3">
                        <Button
                          type="button"
                          variant="outline"
                          onClick={() => {
                            setStep(1);
                            setError(null);
                          }}
                          disabled={isLoading}
                          className="h-12 flex-1"
                        >
                          Atrás
                        </Button>
                        <Button
                          type="submit"
                          disabled={isLoading}
                          className="h-12 flex-1 bg-accent text-primary hover:bg-accent/90"
                        >
                          {isLoading ? (
                            <span className="flex items-center">
                              <motion.div
                                className="mr-2 h-5 w-5 rounded-full border-2 border-white border-t-transparent"
                                animate={{ rotate: 360 }}
                                transition={{ duration: 1, repeat: Infinity, ease: "linear" }}
                              />
                              Registrando...
                            </span>
                          ) : (
                            "Continuar"
                          )}
                        </Button>
                      </div>
                    </form>
                  </CardContent>
                </Card>
              </motion.div>
            )}
          </AnimatePresence>

          {/* Step 3: Crisis Screening */}
          <AnimatePresence mode="wait">
            {step === 3 && (
              <motion.div
                key="step3"
                initial={{ opacity: 0, x: 20 }}
                animate={{ opacity: 1, x: 0 }}
                exit={{ opacity: 0, x: -20 }}
                transition={{ duration: 0.3 }}
              >
                <Card className="border-l-4 border-l-accent shadow-xl">
                  <CardContent className="p-8">
                    <div className="mb-6 text-center">
                      <motion.div
                        className="mx-auto mb-4 flex h-16 w-16 items-center justify-center rounded-full bg-amber-100"
                        animate={{ scale: [1, 1.1, 1] }}
                        transition={{ duration: 2, repeat: Infinity, ease: "easeInOut" }}
                      >
                        <AlertTriangle className="h-8 w-8 text-amber-600" />
                      </motion.div>
                      <h3 className="mb-2 font-serif text-2xl font-semibold text-primary">
                        ¿Es una urgencia?
                      </h3>
                      <p className="text-secondary">
                        ¿Estás experimentando una crisis emocional o situación de emergencia?
                      </p>
                    </div>

                    <div className="space-y-4">
                      <Button
                        onClick={() => handleCrisisResponse(true)}
                        variant="outline"
                        className="h-14 w-full border-amber-500 text-base text-amber-700 hover:bg-amber-50"
                      >
                        Sí, Necesito Ayuda Urgente
                      </Button>

                      <Button
                        onClick={() => handleCrisisResponse(false)}
                        className="h-14 w-full bg-accent text-primary hover:bg-accent/90"
                      >
                        No, Quiero Agendar una Cita Regular
                      </Button>
                    </div>

                    <div className="mt-6 border-t pt-6">
                      <p className="text-center text-xs text-secondary">
                        Si es una emergencia médica, llama al 911 o acude al hospital más cercano.
                      </p>
                    </div>
                  </CardContent>
                </Card>
              </motion.div>
            )}
          </AnimatePresence>

          {/* Step 4: Calendar */}
          <AnimatePresence mode="wait">
            {step === 4 && (
              <motion.div
                key="step4"
                initial={{ opacity: 0, x: 20 }}
                animate={{ opacity: 1, x: 0 }}
                exit={{ opacity: 0, x: -20 }}
                transition={{ duration: 0.3 }}
              >
                <Card className="shadow-xl">
                  <CardContent className="p-8">
                    <div className="text-center">
                      <CalendarIcon className="mx-auto mb-4 h-16 w-16 text-accent" />
                      <h3 className="mb-2 font-serif text-2xl font-semibold text-primary">
                        Selecciona tu Cita
                      </h3>
                      <p className="mb-6 text-secondary">Elige el día y horario disponible</p>
                    </div>

                    {/* Week Navigation */}
                    <div className="mb-6 flex items-center justify-between">
                      <Button
                        onClick={() => {
                          const newDate = new Date(currentWeekStart);
                          newDate.setDate(newDate.getDate() - 7);
                          setCurrentWeekStart(newDate);
                          fetchAvailability(newDate);
                        }}
                        variant="outline"
                        disabled={isLoading}
                        className="h-10 px-4"
                      >
                        <ChevronLeft className="h-5 w-5" />
                      </Button>

                      <span className="text-sm text-secondary">
                        {formatDateDisplay(currentWeekStart)} -{" "}
                        {formatDateDisplay(
                          new Date(currentWeekStart.getTime() + 6 * 24 * 60 * 60 * 1000)
                        )}
                      </span>

                      <Button
                        onClick={() => {
                          const newDate = new Date(currentWeekStart);
                          newDate.setDate(newDate.getDate() + 7);
                          setCurrentWeekStart(newDate);
                          fetchAvailability(newDate);
                        }}
                        variant="outline"
                        disabled={isLoading}
                        className="h-10 px-4"
                      >
                        <ChevronRight className="h-5 w-5" />
                      </Button>
                    </div>

                    {/* Date Input */}
                    <div className="mb-6">
                      <label className="mb-2 block text-sm font-medium text-primary">
                        Selecciona fecha
                      </label>
                      <input
                        type="date"
                        min={formatDateForInput(new Date())}
                        max={formatDateForInput(
                          new Date(currentWeekStart.getTime() + 6 * 24 * 60 * 60 * 1000)
                        )}
                        value={selectedDate ? formatDateForInput(selectedDate) : ""}
                        onChange={handleDateSelect}
                        className="h-12 w-full border-secondary/30 focus:border-accent"
                        disabled={isLoading}
                      />
                    </div>

                    {/* Time Slots */}
                    {isLoading ? (
                      <div className="flex items-center justify-center py-12">
                        <div className="h-5 w-5 rounded-full border-2 border-accent border-t-transparent">
                          <motion.div
                            className="h-5 w-5 rounded-full border-2 border-white border-t-transparent"
                            animate={{ rotate: 360 }}
                            transition={{ duration: 1, repeat: Infinity, ease: "linear" }}
                          />
                        </div>
                        <span className="ml-3 text-secondary">Cargando horarios...</span>
                      </div>
                    ) : availableSlots.length === 0 ? (
                      <div className="py-8 text-center">
                        <p className="text-secondary">
                          No hay horarios disponibles para esta semana
                        </p>
                      </div>
                    ) : (
                      <div className="space-y-3">
                        {availableSlots
                          .filter((slot) => slot.available)
                          .map((slot, index) => (
                            <motion.button
                              key={`${slot.startTime.getTime()}`}
                              type="button"
                              onClick={() => handleSlotSelect(slot)}
                              className={`w-full border-2 p-3 text-left transition-all ${
                                selectedSlot?.startTime.getTime() === slot.startTime.getTime()
                                  ? "border-accent bg-accent text-white"
                                  : "border-secondary/20 hover:border-accent"
                              }`}
                              whileHover={{ scale: 1.01 }}
                              whileTap={{ scale: 0.99 }}
                            >
                              <div className="mb-1 flex items-center justify-between">
                                <span className="font-medium text-primary">
                                  {formatTimeDisplay(slot.startTime)}
                                </span>
                                <span className="text-sm text-secondary">
                                  - {formatTimeDisplay(slot.endTime)}
                                </span>
                              </div>
                              <span className="text-xs text-secondary">
                                {slot.available ? "Disponible" : "Ocupado"}
                              </span>
                            </motion.button>
                          ))}
                      </div>
                    )}

                    {/* Selected Slot Display */}
                    {selectedSlot && (
                      <motion.div
                        className="mt-6 rounded-lg border-2 border-accent bg-accent/10 p-4"
                        initial={{ opacity: 0, y: 10 }}
                        animate={{ opacity: 1, y: 0 }}
                        transition={{ duration: 0.3 }}
                      >
                        <div className="text-center">
                          <CalendarIcon className="mx-auto mb-2 h-8 w-8 text-accent" />
                          <p className="font-medium text-primary">Horario seleccionado</p>
                          <p className="text-sm text-accent">
                            {formatDateDisplay(selectedSlot.startTime)} de{" "}
                            {formatTimeDisplay(selectedSlot.endTime)}
                          </p>
                        </div>

                        <div className="flex gap-2">
                          <Button
                            onClick={() => {
                              setSelectedSlot(null);
                              setError(null);
                            }}
                            variant="outline"
                            disabled={isLoading}
                            className="flex-1"
                          >
                            Limpiar
                          </Button>
                          <Button
                            onClick={() => {
                              setSelectedSlot(null);
                              setError(null);
                              setStep(3);
                            }}
                            variant="outline"
                            disabled={isLoading}
                            className="flex-1"
                          >
                            Atrás
                          </Button>
                          <Button
                            onClick={handleAppointmentSubmit}
                            disabled={isLoading}
                            className="flex-2 bg-accent text-primary hover:bg-accent/90"
                          >
                            {isLoading ? (
                              <span className="flex items-center">
                                <motion.div
                                  className="mr-2 h-5 w-5 rounded-full border-2 border-white border-t-transparent"
                                  animate={{ rotate: 360 }}
                                  transition={{ duration: 1, repeat: Infinity, ease: "linear" }}
                                />
                                Agendando...
                              </span>
                            ) : (
                              "Confirmar Cita"
                            )}
                          </Button>
                        </div>
                      </motion.div>
                    )}

                    {error && (
                      <motion.div
                        className="mt-6 rounded-lg border-red-200 bg-red-50 px-4 py-2 text-sm text-red-700"
                        initial={{ opacity: 0, y: -10 }}
                        animate={{ opacity: 1, y: 0 }}
                      >
                        {error}
                      </motion.div>
                    )}

                    <div className="mt-4 text-center">
                      <Button
                        onClick={() => {
                          setStep(1);
                          resetBooking();
                        }}
                        variant="outline"
                        className="h-10 px-4"
                      >
                        Cancelar
                      </Button>
                    </div>
                  </CardContent>
                </Card>
              </motion.div>
            )}
          </AnimatePresence>

          {/* Step 5: Crisis Protocol */}
          <AnimatePresence mode="wait">
            {step === 5 && (
              <motion.div
                key="step5"
                initial={{ opacity: 0, x: 20 }}
                animate={{ opacity: 1, x: 0 }}
                exit={{ opacity: 0, x: -20 }}
                transition={{ duration: 0.3 }}
              >
                <Card className="border-2 border-red-500 bg-red-50 shadow-2xl">
                  <CardContent className="p-8">
                    <div className="mb-6 text-center">
                      <motion.div
                        className="mx-auto mb-4 flex h-20 w-20 items-center justify-center rounded-full bg-red-100"
                        animate={{ scale: [1, 1.1, 1] }}
                        transition={{ duration: 2, repeat: Infinity, ease: "easeInOut" }}
                      >
                        <AlertTriangle className="h-10 w-10 text-red-600" />
                      </motion.div>
                      <h3 className="mb-2 font-serif text-2xl font-semibold text-primary">
                        Protocolo de Crisis
                      </h3>
                      <p className="text-secondary">Si es una emergencia, sigue estos pasos</p>
                    </div>

                    <div className="space-y-4 text-left">
                      <div className="flex items-start space-x-3">
                        <div className="flex h-6 w-6 flex-shrink-0 items-center justify-center rounded-full bg-red-100 text-sm font-bold text-white">
                          1
                        </div>
                        <p className="text-primary">
                          Si es una emergencia médica, llama al **911** o acude al hospital más
                          cercano.
                        </p>
                      </div>

                      <div className="flex items-start space-x-3">
                        <div className="flex h-6 w-6 flex-shrink-0 items-center justify-center rounded-full bg-red-100 text-sm font-bold text-white">
                          2
                        </div>
                        <p className="text-primary">
                          Línea de ayuda: **800-123-4567** (disponible 24/7).
                        </p>
                      </div>

                      <div className="flex items-start space-x-3">
                        <div className="flex h-6 w-6 flex-shrink-0 items-center justify-center rounded-full bg-red-100 text-sm font-bold text-white">
                          3
                        </div>
                        <p className="text-primary">Contacta a un familiar o amigo de confianza.</p>
                      </div>
                    </div>

                    <div className="mt-6 space-y-3">
                      <Button
                        onClick={() => window.open("tel:911")}
                        className="h-14 w-full bg-red-600 text-white hover:bg-red-700"
                      >
                        Llamar 911
                      </Button>

                      <Button onClick={() => setStep(1)} variant="outline" className="h-14 w-full">
                        No es una emergencia
                      </Button>
                    </div>

                    <div className="mt-4 border-t border-red-300 pt-6">
                      <p className="text-xs text-primary">
                        Si no es una emergencia médica, puedes continuar con el agendamiento.
                      </p>
                    </div>
                  </CardContent>
                </Card>
              </motion.div>
            )}
          </AnimatePresence>

          {/* Step 6: Success */}
          <AnimatePresence mode="wait">
            {step === 6 && (
              <motion.div
                key="step6"
                initial={{ opacity: 0, scale: 0.8 }}
                animate={{ opacity: 1, scale: 1 }}
                exit={{ opacity: 0, scale: 0.8 }}
                transition={{ duration: 0.5, type: "spring", stiffness: 300, damping: 25 }}
              >
                <Card className="border-2 border-green-500 bg-green-50 shadow-xl">
                  <CardContent className="p-8 text-center">
                    <motion.div
                      className="mx-auto mb-4 flex h-20 w-20 items-center justify-center rounded-full bg-green-100"
                      initial={{ scale: 0 }}
                      animate={{ scale: 1, rotate: 360 }}
                      transition={{
                        duration: 0.5,
                        delay: 0.2,
                        type: "spring",
                        stiffness: 200,
                        damping: 15,
                      }}
                    >
                      <Check className="h-10 w-10 text-green-600" />
                    </motion.div>

                    <h3 className="mb-2 font-serif text-2xl font-semibold text-primary">
                      ¡Cita Agendada!
                    </h3>

                    <p className="mb-6 text-secondary">Tu cita ha sido agendada exitosamente.</p>

                    <div className="mb-6 rounded-lg bg-background p-6">
                      <p className="mb-2 font-medium text-primary">
                        <span className="font-semibold">Fecha:</span>{" "}
                        {formatDateDisplay(selectedSlot?.startTime || new Date())}
                      </p>
                      <p className="text-sm text-secondary">
                        <span className="font-semibold">Hora:</span>{" "}
                        {formatTimeDisplay(selectedSlot?.startTime || new Date())}
                      </p>
                      <p className="text-sm text-secondary">
                        <span className="font-semibold">Modalidad:</span>{" "}
                        {isCrisis ? "Sesión virtual" : "Presencial"}
                      </p>
                    </div>

                    <p className="mb-6 text-sm text-secondary">
                      Recibirás un recordatorio por WhatsApp 24 horas antes de tu cita.
                    </p>

                    <Button
                      onClick={() => setStep(1)}
                      className="h-12 w-full bg-accent text-primary hover:bg-accent/90"
                    >
                      Agendar Otra Cita
                    </Button>

                    <div className="mt-4 border-t border-green-300 pt-6">
                      <p className="text-xs text-primary">
                        Te enviaremos un mensaje de confirmación con todos los detalles de tu cita.
                      </p>
                    </div>
                  </CardContent>
                </Card>
              </motion.div>
            )}
          </AnimatePresence>
        </motion.div>
      </div>
    </section>
  );
}
