'use client';

import {Button} from '@astryxdesign/core/Button';
import {Icon} from '@astryxdesign/core/Icon';
import {Item} from '@astryxdesign/core/Item';
import {HStack, VStack} from '@astryxdesign/core/Layout';
import {Text} from '@astryxdesign/core/Text';
import {Timestamp} from '@astryxdesign/core/Timestamp';
import {useLoyalyAi} from '@/features/loyaly-ai/providers/LoyalyAiProvider';
import {EmptyPanel} from '@/shared/components/patterns/EmptyPanel';
import {ICONS} from '@/shared/utils/icons';

/**
 * Past conversations, as an overlay INSIDE the panel.
 *
 * Not a second drawer off the side of the screen: the assistant already is a
 * drawer at most widths, and a drawer opening out of a drawer is how you end
 * up with two dismiss layers and a stack of Escape handlers that disagree.
 * Covering the conversation area instead keeps the header — with the same
 * History button, now toggled on — in place as the way back out.
 *
 * Absolutely positioned over the conversation rather than replacing it, so
 * the transcript is not unmounted: opening history and closing it again
 * returns to the same scroll position mid-conversation.
 */
export function HistoryDrawer() {
  const {history, openConversation, isHistoryOpen, setHistoryOpen} =
    useLoyalyAi();

  if (!isHistoryOpen) return null;

  return (
    <VStack
      gap={2}
      padding={3}
      width="100%"
      className="absolute inset-0 z-10 overflow-y-auto bg-surface"
      role="region"
      aria-label="Chat history"
    >
      <HStack hAlign="between" vAlign="center" paddingInline={1}>
        <Text size="sm" type="supporting">
          Recent chats
        </Text>
        {/* A text button rather than an IconButton: this closes a region, not
            the assistant, and an X here would be mistaken for the panel's own
            close in the header directly above it. */}
        <Button
          variant="ghost"
          size="sm"
          label="Done"
          onClick={() => setHistoryOpen(false)}
        />
      </HStack>

      {history.length === 0 ? (
        <EmptyPanel
          icon="chat"
          title="No conversations yet"
          description="Chats you start appear here for the rest of the session."
        />
      ) : (
        <VStack gap={0.5}>
          {history.map((c) => (
            <Item
              key={c.id}
              label={c.title}
              labelLines={1}
              description={<Timestamp value={c.updatedAt} />}
              density="balanced"
              className="rounded-lg cursor-pointer"
              startContent={<Icon icon={ICONS.chat} size="sm" />}
              onClick={() => openConversation(c.id)}
            />
          ))}
        </VStack>
      )}
    </VStack>
  );
}
