"use client"

import { type CSSProperties, useEffect, useMemo, useRef, useState } from "react"
import { Button } from "@/components/ui/button"
import { Card, CardContent, CardHeader, CardTitle, CardDescription, CardFooter } from "@/components/ui/card"
import { Input } from "@/components/ui/input"
import { Avatar, AvatarFallback } from "@/components/ui/avatar"
import { Badge } from "@/components/ui/badge"
import {
  Send,
  Bot,
  User,
  Sparkles,
  CheckCircle2,
  XCircle,
  MapPin,
  CalendarClock,
  Users as UsersIcon,
  Car,
  Monitor,
  Phone,
  Presentation,
} from "lucide-react"
import { cn } from "@/lib/utils"
import { format } from "date-fns"
import { es } from "date-fns/locale"
import { toast } from "sonner"

interface Message {
  id: string
  role: "user" | "assistant"
  content: string
  timestamp: Date
}

type PendingAction =
  | {
      type: "create_reservation"
      params?: {
        resourceId?: string
        startAt?: string
        endAt?: string
        notes?: string | null
      }
      summary: string
    }
  | {
      type: "edit_reservation"
      params?: {
        reservationId?: string
        resourceId?: string
        startAt?: string
        endAt?: string
        notes?: string | null
      }
      summary: string
    }
  | {
      type: "cancel_reservation"
      params?: {
        reservationId?: string
      }
      summary: string
    }

type SammyApiResponse = {
  assistantMessage: string
  pendingAction: PendingAction | null
  availabilityResults?: AvailabilityResult[] | null
  modelUsed?: string | null
}

type PendingActionCard = {
  id: string
  action: PendingAction
  createdAt: Date
  status: "pending" | "confirmed" | "discarded"
  resolvedAt?: Date
}

type AvailabilityResult = {
  id: string
  name: string
  resourceTypeName: string | null
  resourceTypeSlug: string | null
  location: string | null
  floor: string | null
  capacity: number | null
  amenities: string[]
  imageUrl: string | null
  startAt: string | null
  endAt: string | null
}

type AvailabilityResultCard = {
  id: string
  createdAt: Date
  items: AvailabilityResult[]
}

const resourceIconMap: Record<string, React.ReactNode> = {
  "meeting-room": <UsersIcon className="h-5 w-5" />,
  parking: <Car className="h-5 w-5" />,
  desk: <Monitor className="h-5 w-5" />,
  "phone-booth": <Phone className="h-5 w-5" />,
  "conference-room": <Presentation className="h-5 w-5" />,
}

const LOCATION_BLOCK_STYLE: CSSProperties = {
  minHeight: "calc(1.4em * 3)",
}

const LOCATION_TEXT_STYLE: CSSProperties = {
  display: "-webkit-box",
  WebkitLineClamp: 3,
  WebkitBoxOrient: "vertical",
  overflow: "hidden",
}

function normalizeIntentText(value: string) {
  return value
    .trim()
    .toLowerCase()
    .normalize("NFD")
    .replace(/[\u0300-\u036f]/g, "")
}

function isExplicitConfirmIntent(value: string) {
  const normalized = normalizeIntentText(value)
  return /^(si|ok|dale|de una|confirmo|confirmar|acepto|procede|hagamoslo|hacelo|hazlo|listo|metele)[!.]*$/.test(
    normalized,
  )
}

function isExplicitDiscardIntent(value: string) {
  const normalized = normalizeIntentText(value)
  return /^(no|cancela|cancelar|descarto|descartar|mejor no|dejalo|dejalo ahi|olvidalo)[!.]*$/.test(
    normalized,
  )
}

function getConfirmedAvailabilityRange(item: AvailabilityResult) {
  if (!item.startAt || !item.endAt) return null
  const start = new Date(item.startAt)
  const end = new Date(item.endAt)
  if (Number.isNaN(start.getTime()) || Number.isNaN(end.getTime())) return null
  if (end <= start) return null
  return {
    startAt: start.toISOString(),
    endAt: end.toISOString(),
  }
}

export default function SammyPage() {
  const [messages, setMessages] = useState<Message[]>([
    {
      id: "1",
      role: "assistant",
      content:
        "Hola, soy Sammy. Puedo consultar disponibilidad y preparar acciones de reserva por vos. Para crear, editar o cancelar, siempre voy a pedir confirmacion explicita y no voy a asumir horarios si no los indicas.",
      timestamp: new Date(),
    },
  ])
  const [input, setInput] = useState("")
  const [loading, setLoading] = useState(false)
  const [pendingAction, setPendingAction] = useState<PendingAction | null>(null)
  const [pendingActionCards, setPendingActionCards] = useState<PendingActionCard[]>([])
  const [availabilityResultCards, setAvailabilityResultCards] = useState<AvailabilityResultCard[]>([])
  const [activePendingActionCardId, setActivePendingActionCardId] = useState<string | null>(null)
  const [modelLabel, setModelLabel] = useState<string | null>(null)
  const messagesContainerRef = useRef<HTMLDivElement>(null)
  const messageCounterRef = useRef(2)
  const presetSuggestions = useMemo(
    () => [
      "¿Qué salas hay libres hoy de 15:00 a 16:00?",
      "Quiero reservar una sala mañana de 10:00 a 11:00.",
      "Cancelá mi próxima reserva.",
    ],
    [],
  )

  useEffect(() => {
    if (messagesContainerRef.current) {
      messagesContainerRef.current.scrollTop = messagesContainerRef.current.scrollHeight
    }
  }, [messages, pendingActionCards, availabilityResultCards, loading])

  const toApiMessages = (base: Message[]) =>
    base.map((message) => ({
      role: message.role,
      content: message.content,
    }))

  const appendAssistantMessage = (content: string) => {
    const assistantMessage: Message = {
      id: `${messageCounterRef.current++}`,
      role: "assistant",
      content,
      timestamp: new Date(),
    }
    setMessages((prev) => [...prev, assistantMessage])
  }

  const areSamePendingAction = (left: PendingAction | null, right: PendingAction | null) => {
    if (!left || !right) return false
    return (
      left.type === right.type &&
      left.summary === right.summary &&
      JSON.stringify(left.params ?? {}) === JSON.stringify(right.params ?? {})
    )
  }

  const addPendingActionCard = (action: PendingAction) => {
    const cardId = `action-${messageCounterRef.current++}`
    const card: PendingActionCard = {
      id: cardId,
      action,
      createdAt: new Date(),
      status: "pending",
    }
    setPendingActionCards((prev) => [...prev, card])
    setActivePendingActionCardId(cardId)
  }

  const resolveActivePendingCard = (status: "confirmed" | "discarded") => {
    const now = new Date()
    if (!activePendingActionCardId) return
    setPendingActionCards((prev) =>
      prev.map((card) =>
        card.id === activePendingActionCardId && card.status === "pending"
          ? { ...card, status, resolvedAt: now }
          : card,
      ),
    )
    setActivePendingActionCardId(null)
  }

  const addAvailabilityResultCard = (items: AvailabilityResult[]) => {
    if (!Array.isArray(items) || items.length === 0) return
    const card: AvailabilityResultCard = {
      id: `availability-${messageCounterRef.current++}`,
      createdAt: new Date(),
      items,
    }
    setAvailabilityResultCards((prev) => [...prev, card])
  }

  const buildReservePromptFromAvailability = (item: AvailabilityResult) => {
    const range = getConfirmedAvailabilityRange(item)
    if (!range) {
      return {
        visibleText: `Quiero reservar ${item.name}, pero todavia no elegi horario. Pedime hora de inicio y fin antes de preparar la accion.`,
        apiText: `Quiero reservar ${item.name}. resourceId=${item.id}. Todavia no elegi horario. Pedime hora de inicio y fin antes de preparar la accion.`,
      }
    }

    return {
      visibleText: `Quiero reservar ${item.name} en el horario de esta card.`,
      apiText: `Quiero reservar ${item.name}. resourceId=${item.id}. startAt=${range.startAt}. endAt=${range.endAt}. Preparame la confirmacion de reserva.`,
    }
  }

  const timeline = useMemo(() => {
    const messageItems = messages.map((message) => ({
      kind: "message" as const,
      id: message.id,
      timestamp: message.timestamp,
      message,
    }))
    const actionItems = pendingActionCards.map((card) => ({
      kind: "action" as const,
      id: card.id,
      timestamp: card.createdAt,
      card,
    }))
    const availabilityItems = availabilityResultCards.map((card) => ({
      kind: "availability" as const,
      id: card.id,
      timestamp: card.createdAt,
      card,
    }))
    return [...messageItems, ...actionItems, ...availabilityItems].sort(
      (a, b) => a.timestamp.getTime() - b.timestamp.getTime(),
    )
  }, [messages, pendingActionCards, availabilityResultCards])

  const callSammyApi = async ({
    apiMessages,
    confirmPendingAction,
    currentPendingAction,
  }: {
    apiMessages: Array<{ role: "user" | "assistant"; content: string }>
    confirmPendingAction: boolean
    currentPendingAction: PendingAction | null
  }) => {
    const now = new Date()
    const response = await fetch("/api/sammy", {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
      },
      body: JSON.stringify({
        messages: apiMessages,
        pendingAction: currentPendingAction,
        confirmPendingAction,
        clientNowIso: now.toISOString(),
        clientUtcOffsetMinutes: now.getTimezoneOffset(),
      }),
    })

    const payload = (await response.json().catch(() => null)) as SammyApiResponse | { error?: string } | null
    if (!response.ok) {
      throw new Error((payload as { error?: string } | null)?.error ?? "No se pudo procesar la solicitud")
    }
    return payload as SammyApiResponse
  }

  const handleSend = async (text?: string) => {
    const messageText = text || input
    if (!messageText.trim()) return

    const confirmByText = Boolean(pendingAction && isExplicitConfirmIntent(messageText))
    const discardByText = Boolean(pendingAction && isExplicitDiscardIntent(messageText))

    const userMessage: Message = {
      id: `${messageCounterRef.current++}`,
      role: "user",
      content: messageText,
      timestamp: new Date(),
    }
    const nextMessages = [...messages, userMessage]
    setMessages(nextMessages)
    setInput("")

    if (discardByText) {
      resolveActivePendingCard("discarded")
      setPendingAction(null)
      appendAssistantMessage("Perfecto, descarté la accion pendiente.")
      return
    }

    setLoading(true)

    try {
      const payload = await callSammyApi({
        apiMessages: toApiMessages(nextMessages),
        confirmPendingAction: confirmByText,
        currentPendingAction: pendingAction,
      })
      if (confirmByText && pendingAction) {
        resolveActivePendingCard("confirmed")
      }
      appendAssistantMessage(payload.assistantMessage)
      addAvailabilityResultCard(payload.availabilityResults ?? [])
      if (payload.pendingAction) {
        if (!areSamePendingAction(pendingAction, payload.pendingAction)) {
          addPendingActionCard(payload.pendingAction)
        }
      } else if (!confirmByText) {
        setActivePendingActionCardId(null)
      }
      setPendingAction(payload.pendingAction)
      setModelLabel(payload.modelUsed ?? null)
    } catch (error) {
      const message = error instanceof Error ? error.message : "Error inesperado"
      const lowered = message.toLowerCase()
      if (lowered.includes("unauthorized") || lowered.includes("no autorizado")) {
        appendAssistantMessage("Tu sesión expiró. Volvé a iniciar sesión para seguir operando con Sammy.")
      } else {
        appendAssistantMessage("No pude completar la accion en este momento. Intenta nuevamente.")
      }
      toast.error(message)
    } finally {
      setLoading(false)
    }
  }

  const handleConfirmPendingAction = async () => {
    if (!pendingAction || loading) return
    setLoading(true)
    try {
      const payload = await callSammyApi({
        apiMessages: toApiMessages(messages),
        confirmPendingAction: true,
        currentPendingAction: pendingAction,
      })
      resolveActivePendingCard("confirmed")
      appendAssistantMessage(payload.assistantMessage)
      addAvailabilityResultCard(payload.availabilityResults ?? [])
      setPendingAction(payload.pendingAction)
      setModelLabel(payload.modelUsed ?? null)
    } catch (error) {
      const message = error instanceof Error ? error.message : "Error inesperado"
      const lowered = message.toLowerCase()
      if (lowered.includes("unauthorized") || lowered.includes("no autorizado")) {
        appendAssistantMessage("Tu sesión expiró. Volvé a iniciar sesión para ejecutar la acción.")
      } else {
        appendAssistantMessage("No pude ejecutar la accion confirmada.")
      }
      toast.error(message)
    } finally {
      setLoading(false)
    }
  }

  const handleDiscardPendingAction = () => {
    if (!pendingAction) return
    resolveActivePendingCard("discarded")
    setPendingAction(null)
    appendAssistantMessage("Perfecto, descarté la accion pendiente.")
  }

  const handleKeyDown = (e: React.KeyboardEvent) => {
    if (e.key === "Enter" && !e.shiftKey) {
      e.preventDefault()
      handleSend()
    }
  }

  const handleReserveFromAvailability = async (resource: AvailabilityResult) => {
    if (loading) return

    const reservePrompt = buildReservePromptFromAvailability(resource)
    const userMessage: Message = {
      id: `${messageCounterRef.current++}`,
      role: "user",
      content: reservePrompt.visibleText,
      timestamp: new Date(),
    }
    const nextMessages = [...messages, userMessage]
    const nextApiMessages = toApiMessages(nextMessages)
    if (nextApiMessages.length > 0) {
      const last = nextApiMessages[nextApiMessages.length - 1]
      nextApiMessages[nextApiMessages.length - 1] = {
        ...last,
        content: reservePrompt.apiText,
      }
    }
    setMessages(nextMessages)
    setInput("")
    setLoading(true)

    try {
      const payload = await callSammyApi({
        apiMessages: nextApiMessages,
        confirmPendingAction: false,
        currentPendingAction: pendingAction,
      })

      appendAssistantMessage(payload.assistantMessage)
      addAvailabilityResultCard(payload.availabilityResults ?? [])
      if (payload.pendingAction) {
        if (!areSamePendingAction(pendingAction, payload.pendingAction)) {
          addPendingActionCard(payload.pendingAction)
        }
      } else {
        setActivePendingActionCardId(null)
      }
      setPendingAction(payload.pendingAction)
      setModelLabel(payload.modelUsed ?? null)
    } catch (error) {
      const message = error instanceof Error ? error.message : "Error inesperado"
      const lowered = message.toLowerCase()
      if (lowered.includes("unauthorized") || lowered.includes("no autorizado")) {
        appendAssistantMessage("Tu sesión expiró. Volvé a iniciar sesión para seguir operando con Sammy.")
      } else {
        appendAssistantMessage("No pude completar la accion en este momento. Intenta nuevamente.")
      }
      toast.error(message)
    } finally {
      setLoading(false)
    }
  }

  const renderAvailabilityRange = (item: AvailabilityResult) => {
    if (!item.startAt || !item.endAt) return "Falta horario para validar disponibilidad"
    const start = new Date(item.startAt)
    const end = new Date(item.endAt)
    if (Number.isNaN(start.getTime()) || Number.isNaN(end.getTime())) return "Horario no válido"
    if (end <= start) return "Horario no confirmado"
    return `${format(start, "EEE d MMM, HH:mm", { locale: es })} - ${format(end, "HH:mm", { locale: es })}`
  }

  return (
    <div className="flex h-[calc(100vh-8rem)] min-h-0 flex-col gap-[var(--ds-space-2x)]">
      <div className="rounded-[var(--ds-radius-l)] bg-[var(--ds-blueprimary-100)] px-[var(--ds-space-4x)] py-[var(--ds-space-3x)] shadow-[var(--ds-shadow-4dp)]">
        <div className="flex items-center gap-[var(--ds-space-2x)]">
          <div className="flex h-[var(--ds-space-5x)] w-[var(--ds-space-5x)] items-center justify-center rounded-[var(--ds-radius-m)] bg-[var(--ds-brand-400)] text-white">
            <Sparkles className="h-6 w-6" />
          </div>
          <div>
            <h1 className="ds-type-global-l ds-type-semibold text-[var(--ds-blueprimary-800)]">
              Sammy
            </h1>
            <p className="mt-[var(--ds-space-05x)] ds-type-global-s text-[var(--ds-text-neutral-lighter)]">
              Asistente transaccional con Claude
            </p>
          </div>
        </div>
      </div>

      <Card className="flex min-h-0 flex-1 flex-col overflow-hidden rounded-[var(--ds-radius-l)] border-[var(--ds-neutral-200)] bg-white shadow-[var(--ds-shadow-4dp)]">
        <div
          ref={messagesContainerRef}
          className="min-h-0 flex-1 overflow-y-auto p-[var(--ds-space-2x)]"
        >
          <div className="space-y-[var(--ds-space-2x)]">
            {timeline.map((item) => {
              if (item.kind === "message") {
                const message = item.message
                return (
                  <div
                    key={message.id}
                    className={cn("flex gap-3", message.role === "user" ? "flex-row-reverse" : "")}
                  >
                    <Avatar className="h-[var(--ds-space-4x)] w-[var(--ds-space-4x)] shrink-0">
                      <AvatarFallback
                        className={cn(
                          message.role === "assistant"
                            ? "bg-[var(--ds-brand-400)] text-white"
                            : "bg-[var(--ds-neutral-100)] text-[var(--ds-text-neutral-default)]",
                        )}
                      >
                        {message.role === "assistant" ? <Bot className="h-4 w-4" /> : <User className="h-4 w-4" />}
                      </AvatarFallback>
                    </Avatar>
                    <div
                      className={cn(
                        "flex max-w-[80%] flex-col gap-2",
                        message.role === "user" ? "items-end" : "items-start",
                      )}
                    >
                      <div
                        className={cn(
                          "rounded-[var(--ds-radius-m)] px-[var(--ds-space-2x)] py-[var(--ds-space-1x)]",
                          message.role === "assistant"
                            ? "bg-[var(--ds-neutral-100)] text-[var(--ds-text-neutral-default)]"
                            : "bg-[var(--ds-brand-400)] text-white",
                        )}
                      >
                        <p className="ds-type-global-xs">{message.content}</p>
                      </div>

                      <span className="ds-type-global-xxs text-[var(--ds-text-neutral-lighter)]">
                        {format(message.timestamp, "HH:mm")}
                      </span>
                    </div>
                  </div>
                )
              }

              if (item.kind === "action") {
                const { card } = item
                const isActivePending = card.status === "pending" && card.id === activePendingActionCardId
                const statusLabel =
                  card.status === "confirmed"
                    ? "Acción confirmada"
                    : card.status === "discarded"
                      ? "Acción descartada"
                      : "Acción pendiente"

                return (
                  <div key={card.id} className="flex gap-3">
                    <Avatar className="h-[var(--ds-space-4x)] w-[var(--ds-space-4x)] shrink-0">
                      <AvatarFallback className="bg-[var(--ds-brand-400)] text-white">
                        <Bot className="h-4 w-4" />
                      </AvatarFallback>
                    </Avatar>
                    <div className="w-full max-w-[80%] space-y-[var(--ds-space-1x)]">
                      <Card className="rounded-[var(--ds-radius-m)] border-[var(--ds-neutral-200)] bg-white py-[var(--ds-space-2x)]">
                        <CardHeader className="px-[var(--ds-space-2x)] pb-[var(--ds-space-1x)]">
                          <CardTitle className="ds-type-global-xs ds-type-semibold text-[var(--ds-text-neutral-default)]">
                            {statusLabel}
                          </CardTitle>
                          <CardDescription className="ds-type-global-xxs text-[var(--ds-text-neutral-lighter)]">
                            {card.action.summary}
                          </CardDescription>
                        </CardHeader>
                        {isActivePending && (
                          <CardContent className="flex gap-[var(--ds-space-1x)] px-[var(--ds-space-2x)]">
                            <Button
                              size="sm"
                              disabled={loading}
                              onClick={handleConfirmPendingAction}
                              className="rounded-[var(--ds-radius-m)] bg-[var(--ds-success-700)] ds-type-global-xs text-white hover:opacity-90"
                            >
                              <CheckCircle2 className="mr-1 h-4 w-4" />
                              Confirmar
                            </Button>
                            <Button
                              size="sm"
                              variant="outline"
                              disabled={loading}
                              onClick={handleDiscardPendingAction}
                              className="rounded-[var(--ds-radius-m)] border-[var(--ds-neutral-300)] bg-white ds-type-global-xs text-[var(--ds-text-neutral-default)]"
                            >
                              <XCircle className="mr-1 h-4 w-4" />
                              Descartar
                            </Button>
                          </CardContent>
                        )}
                      </Card>
                      <span className="ds-type-global-xxs text-[var(--ds-text-neutral-lighter)]">
                        {format(card.resolvedAt ?? card.createdAt, "HH:mm")}
                      </span>
                    </div>
                  </div>
                )
              }

              const { card } = item
              return (
                <div key={card.id} className="flex gap-3">
                  <Avatar className="h-[var(--ds-space-4x)] w-[var(--ds-space-4x)] shrink-0">
                    <AvatarFallback className="bg-[var(--ds-brand-400)] text-white">
                      <Bot className="h-4 w-4" />
                    </AvatarFallback>
                  </Avatar>
                  <div className="w-full max-w-[80%] space-y-[var(--ds-space-1x)]">
                    <p className="ds-type-global-xs ds-type-semibold text-[var(--ds-text-neutral-default)]">
                      Salas disponibles
                    </p>
                    <div className="grid grid-cols-1 items-stretch gap-[var(--ds-space-1x)] md:grid-cols-2">
                      {card.items.map((resource) => (
                        <Card
                          key={`${card.id}-${resource.id}`}
                          className="h-full gap-0 rounded-[var(--ds-radius-m)] border-[var(--ds-neutral-200)] bg-white py-0 shadow-[var(--ds-shadow-4dp)]"
                        >
                          <CardContent className="flex flex-1 flex-col gap-[var(--ds-space-1x)] px-[var(--ds-space-15x)] pt-[var(--ds-space-15x)]">
                            <div className="flex items-start justify-between gap-[var(--ds-space-1x)]">
                              <div className="space-y-[var(--ds-space-05x)] min-h-[var(--ds-space-6x)]">
                                <div className="flex items-center gap-[var(--ds-space-1x)]">
                                  <div className="flex h-8 w-8 items-center justify-center rounded-[var(--ds-radius-s)] bg-[var(--ds-blueprimary-100)] text-[var(--ds-brand-400)]">
                                    {resourceIconMap[resource.resourceTypeSlug ?? ""] ?? (
                                      <Monitor className="h-5 w-5" />
                                    )}
                                  </div>
                                  <p className="ds-type-global-xs ds-type-semibold text-[var(--ds-text-neutral-default)]">
                                    {resource.name}
                                  </p>
                                </div>
                                <p className="ds-type-global-xxs text-[var(--ds-text-neutral-lighter)]">
                                  {resource.resourceTypeName ?? "Sin tipo"}
                                </p>
                              </div>
                              <div className="flex h-12 w-20 shrink-0 items-center justify-center rounded-[var(--ds-radius-s)] border border-[var(--ds-neutral-200)] bg-[var(--ds-neutral-100)]">
                                {resource.imageUrl ? (
                                  <img
                                    src={resource.imageUrl}
                                    alt={resource.name}
                                    className="h-full w-full rounded-[var(--ds-radius-s)] object-cover"
                                  />
                                ) : (
                                  <span className="ds-type-global-xxs text-[var(--ds-text-neutral-lighter)]">Sin foto</span>
                                )}
                              </div>
                            </div>

                            <div className="space-y-[var(--ds-space-05x)] min-h-[var(--ds-space-8x)]">
                              <p
                                className="flex items-start gap-[var(--ds-space-05x)] ds-type-global-xxs text-[var(--ds-text-neutral-lighter)]"
                                style={LOCATION_BLOCK_STYLE}
                              >
                                <MapPin className="mt-[2px] h-3 w-3 shrink-0" />
                                <span style={LOCATION_TEXT_STYLE}>
                                  {resource.location ?? "Sin ubicación"}
                                  {resource.floor ? ` • ${resource.floor}` : ""}
                                </span>
                              </p>
                              <p className="flex items-center gap-[var(--ds-space-05x)] ds-type-global-xxs text-[var(--ds-text-neutral-lighter)]">
                                <CalendarClock className="h-3 w-3" />
                                <span className="capitalize">{renderAvailabilityRange(resource)}</span>
                              </p>
                              <p className="flex min-h-[calc(1.4em)] items-center gap-[var(--ds-space-05x)] ds-type-global-xxs text-[var(--ds-text-neutral-lighter)]">
                                <UsersIcon className="h-3 w-3" />
                                {resource.capacity && resource.capacity > 0 ? `${resource.capacity} personas` : "Sin capacidad"}
                              </p>
                            </div>

                            <div className="min-h-[var(--ds-space-5x)]">
                              {resource.amenities.length > 0 ? (
                                <div className="flex flex-wrap gap-[var(--ds-space-05x)]">
                                  {resource.amenities.slice(0, 3).map((amenity) => (
                                    <Badge
                                      key={`${resource.id}-${amenity}`}
                                      className="rounded-[var(--ds-radius-s)] border-0 bg-[var(--ds-neutral-100)] ds-type-global-xxs text-[var(--ds-text-neutral-default)] hover:bg-[var(--ds-neutral-100)]"
                                    >
                                      {amenity}
                                    </Badge>
                                  ))}
                                </div>
                              ) : (
                                <span className="ds-type-global-xxs text-[var(--ds-text-neutral-lighter)]">Sin amenities</span>
                              )}
                            </div>

                          </CardContent>
                          <CardFooter className="mt-auto px-[var(--ds-space-15x)] pb-[var(--ds-space-15x)] pt-[var(--ds-space-1x)]">
                            <Button
                              type="button"
                              size="sm"
                              disabled={loading}
                              className="w-full rounded-[var(--ds-radius-m)] bg-[var(--ds-brand-400)] ds-type-global-xs ds-type-semibold text-white hover:bg-[var(--ds-brand-500)]"
                              onClick={() => handleReserveFromAvailability(resource)}
                            >
                              {getConfirmedAvailabilityRange(resource) ? "Reservar" : "Reservar (elegir horario)"}
                            </Button>
                          </CardFooter>
                        </Card>
                      ))}
                    </div>
                    <span className="ds-type-global-xxs text-[var(--ds-text-neutral-lighter)]">
                      {format(card.createdAt, "HH:mm")}
                    </span>
                  </div>
                </div>
              )
            })}

            {loading && (
              <div className="flex gap-3">
                <Avatar className="h-[var(--ds-space-4x)] w-[var(--ds-space-4x)] shrink-0">
                  <AvatarFallback className="bg-[var(--ds-brand-400)] text-white">
                    <Bot className="h-4 w-4" />
                  </AvatarFallback>
                </Avatar>
                <div className="flex min-h-[var(--ds-space-4x)] items-center rounded-[var(--ds-radius-m)] bg-[var(--ds-neutral-100)] px-[var(--ds-space-2x)] py-[var(--ds-space-1x)]">
                  <div className="flex items-center gap-1">
                    <span className="h-2 w-2 animate-bounce rounded-full bg-[var(--ds-text-neutral-lighter)]/50" style={{ animationDelay: "0ms" }} />
                    <span className="h-2 w-2 animate-bounce rounded-full bg-[var(--ds-text-neutral-lighter)]/50" style={{ animationDelay: "150ms" }} />
                    <span className="h-2 w-2 animate-bounce rounded-full bg-[var(--ds-text-neutral-lighter)]/50" style={{ animationDelay: "300ms" }} />
                  </div>
                </div>
              </div>
            )}
          </div>
        </div>

        <div className="border-t border-[var(--ds-neutral-200)] p-[var(--ds-space-2x)]">
          <div className="mb-[var(--ds-space-1x)] flex flex-wrap gap-[var(--ds-space-1x)]">
            {presetSuggestions.map((suggestion) => (
              <Button
                key={suggestion}
                type="button"
                variant="outline"
                size="sm"
                disabled={loading}
                className="h-auto rounded-[var(--ds-radius-m)] border-[var(--ds-neutral-300)] px-[var(--ds-space-15x)] py-[var(--ds-space-05x)] ds-type-global-xxs text-[var(--ds-text-neutral-default)]"
                onClick={() => handleSend(suggestion)}
              >
                {suggestion}
              </Button>
            ))}
          </div>
          <div className="flex gap-[var(--ds-space-1x)]">
            <Input
              value={input}
              onChange={(e) => setInput(e.target.value)}
              onKeyDown={handleKeyDown}
              placeholder="Escribe tu mensaje..."
              disabled={loading}
              className="rounded-[var(--ds-radius-m)] border-[var(--ds-neutral-300)] ds-type-global-xs text-[var(--ds-text-neutral-default)]"
            />
            <Button
              onClick={() => handleSend()}
              disabled={!input.trim() || loading}
              className="rounded-[var(--ds-radius-m)] bg-[var(--ds-brand-400)] text-white hover:bg-[var(--ds-brand-500)]"
            >
              <Send className="h-4 w-4" />
            </Button>
          </div>
          <p className="mt-[var(--ds-space-1x)] text-center ds-type-global-xxs text-[var(--ds-text-neutral-lighter)]">
            Sammy ejecuta consultas automaticamente y pide confirmacion para mutaciones
          </p>
          {modelLabel && (
            <p className="mt-[var(--ds-space-05x)] text-center ds-type-global-xxs text-[var(--ds-text-neutral-lighter)]">
              Modelo: {modelLabel}
            </p>
          )}
        </div>
      </Card>
    </div>
  )
}
