'use client';

import {
  ChatComposer,
  ChatComposerInput,
  ChatDictationButton,
  ChatLayout,
  ChatMessage,
  ChatMessageBubble,
  ChatMessageList,
  ChatMessageMetadata,
  useChatDictation,
} from '@astryxdesign/core/Chat';
import {Avatar} from '@astryxdesign/core/Avatar';
import {Button} from '@astryxdesign/core/Button';
import {Timestamp} from '@astryxdesign/core/Timestamp';
import {VStack} from '@astryxdesign/core/Layout';
import {Text} from '@astryxdesign/core/Text';
import {useCopilot} from '../CopilotProvider';

/**
 * Suggested prompts double as the empty state — an empty AI panel with a bare
 * input tells a merchant nothing about what it can answer.
 */
const SUGGESTED = [
  "Generate today's report",
  'Compare stores',
  'Suggest rewards',
  'Analyze sales',
  'Show best staff',
  'Predict weekend traffic',
];

function SuggestedPrompts({onPick}: {onPick: (p: string) => void}) {
  return (
    <VStack gap={2} padding={4}>
      <Text size="sm" color="secondary">
        Ask about footfall, LYT redemption, staff or store performance.
      </Text>
      <VStack gap={1.5}>
        {SUGGESTED.map((p) => (
          <Button
            key={p}
            variant="secondary"
            size="sm"
            label={p}
            onClick={() => onPick(p)}
          />
        ))}
      </VStack>
    </VStack>
  );
}

export function ChatTab() {
  const {messages, draft, setDraft, send, isStreaming} = useCopilot();

  // Appends recognised speech to whatever is already typed rather than
  // replacing it, so dictation composes with the keyboard.
  const dictation = useChatDictation({
    onResult: (text: string) => setDraft(draft ? `${draft} ${text}` : text),
  });

  return (
    <ChatLayout
      density="compact"
      emptyState={<SuggestedPrompts onPick={send} />}
      composer={
        <ChatComposer
          value={draft}
          onChange={setDraft}
          onSubmit={send}
          placeholder="Ask about footfall, LYTs, staff…"
          density="compact"
          elevation="none"
          isStopShown={isStreaming}
          input={<ChatComposerInput maxRows={6} />}
          // Renders nothing when SpeechRecognition is unsupported
          // (isHiddenWhenUnsupported defaults true) — progressive, no polyfill.
          sendActions={<ChatDictationButton dictation={dictation} size="sm" />}
        />
      }
    >
      {messages.length > 0 ? (
        <ChatMessageList isStreaming={isStreaming}>
          {messages.map((m) => (
            <ChatMessage
              key={m.id}
              sender={m.sender}
              density="compact"
              avatar={
                m.sender === 'assistant' ? (
                  <Avatar name="Loyaly AI" size="xsm" tooltip={false} />
                ) : undefined
              }
            >
              <ChatMessageBubble
                variant={m.sender === 'assistant' ? 'ghost' : 'filled'}
                metadata={
                  <ChatMessageMetadata
                    timestamp={<Timestamp value={m.at} />}
                  />
                }
              >
                {m.text}
              </ChatMessageBubble>
            </ChatMessage>
          ))}
        </ChatMessageList>
      ) : null}
    </ChatLayout>
  );
}
