// ⚠️ DO NOT EDIT imports — all available components are pre-imported.
import React, { useState, useEffect, useMemo, useCallback, useRef } from 'react';
import { Container, Card, Stack, Row, Box, Divider, Spacer, Text, Heading, Button, Input, TextArea, Select, Checkbox, Toggle, RadioGroup, Slider, Badge, Spinner, Avatar, Alert, Progress, Image, Icon, Link, Tooltip, Table, Tabs, Toast, Accordion } from '@ggui-ai/design/primitives';
import { SearchField, FormField, MenuItem, Tag, Dropdown, Autocomplete, Breadcrumb, Pagination } from '@ggui-ai/design/components';
import { Header, Sidebar, CardGrid, CommentThread, DataTable, ChatWindow, NavigationBar, FileUploader, UserProfileCard, NotificationCenter, Modal, CommandPalette, Footer, Hero } from '@ggui-ai/design/compositions';
import { Clickable, Hoverable, Pressable } from '@ggui-ai/design/interact';

// ⚠️ DO NOT EDIT — generated from data contract. Changing this will fail validation.
interface Props {
  title: string; // Chat window title
  currentUser: string; // Current user name (for right-aligning own messages)
  participantCount: number; // Number of participants
  messages: Array<{ sender?: string; text?: string; timestamp?: string }>; // Array of messages with sender name, text, and ISO timestamp
  onSendMessage?: (data: Record<string, unknown>) => void; // Action: Send Message
}

function useComponent(props: Props) {
  const handleSendMessage = useCallback((data: Record<string, unknown>) => {
    props.onSendMessage?.(data);
  }, [props.onSendMessage]);

  const [inputValue, setInputValue] = useState('');
  const scrollRef = useRef<HTMLDivElement>(null);
  const inputRef = useRef<HTMLTextAreaElement>(null);

  // Auto-scroll to bottom when messages change
  useEffect(() => {
    if (scrollRef.current) {
      setTimeout(() => {
        scrollRef.current!.scrollTop = scrollRef.current!.scrollHeight;
      }, 0);
    }
  }, [props.messages]);

  // Group messages by sender to avoid duplicate avatars
  const messageGroups = useMemo(() => {
    const groups: typeof props.messages[][] = [];
    let currentGroup: typeof props.messages = [];

    props.messages.forEach((msg) => {
      if (currentGroup.length === 0 || currentGroup[0].sender === msg.sender) {
        currentGroup.push(msg);
      } else {
        groups.push(currentGroup);
        currentGroup = [msg];
      }
    });
    if (currentGroup.length > 0) {
      groups.push(currentGroup);
    }
    return groups;
  }, [props.messages]);

  const handleSend = useCallback(() => {
    if (inputValue.trim()) {
      handleSendMessage({ text: inputValue, timestamp: new Date().toISOString() });
      setInputValue('');
      inputRef.current?.focus();
    }
  }, [inputValue, handleSendMessage]);

  return { inputValue, setInputValue, scrollRef, inputRef, handleSend, messageGroups };
}

export default function Component(props: Props) {
  const { inputValue, setInputValue, scrollRef, inputRef, handleSend, messageGroups } = useComponent(props);

  const isOwnMessage = (sender?: string) => sender === props.currentUser;

  const formatTime = (timestamp?: string) => {
    if (!timestamp) return '';
    try {
      const date = new Date(timestamp);
      return date.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
    } catch {
      return '';
    }
  };

  return (
    <Container maxWidth="full" padding={0}>
      <Stack direction="vertical" gap={0} align="stretch">
        {/* Header */}
        <Stack direction="horizontal" gap="var(--ggui-spacing-4, 16px)" align="center" justify="between" style={{ padding: 'var(--ggui-spacing-4, 16px)' }}>
          <Heading level={2} style={{ margin: 0 }}>{props.title}</Heading>
          <Badge variant="primary" size="sm">{props.participantCount} participants</Badge>
        </Stack>
        <Divider orientation="horizontal" margin={0} />

        {/* Message List */}
        <Box
          ref={scrollRef}
          style={{
            flex: 1,
            overflowY: 'auto',
            padding: 'var(--ggui-spacing-4, 16px)',
            backgroundColor: 'var(--ggui-color-surface, #fafafa)',
          }}
          role="log"
          aria-label="Message history"
        >
          <Stack direction="vertical" gap="var(--ggui-spacing-4, 16px)" align="stretch">
            {messageGroups.map((group, groupIdx) => {
              const sender = group[0].sender;
              const isOwn = isOwnMessage(sender);

              return (
                <Stack
                  key={groupIdx}
                  direction="horizontal"
                  gap="var(--ggui-spacing-2, 8px)"
                  align="flex-end"
                  justify={isOwn ? 'end' : 'start'}
                  style={{ marginLeft: isOwn ? 'auto' : 0, marginRight: isOwn ? 0 : 'auto' }}
                >
                  {!isOwn && <Avatar name={sender} size="sm" />}
                  <Stack direction="vertical" gap="var(--ggui-spacing-1, 4px)" align={isOwn ? 'end' : 'start'} style={{ maxWidth: '60%' }}>
                    {group.map((msg, msgIdx) => (
                      <Card
                        key={msgIdx}
                        padding="var(--ggui-spacing-2, 8px) var(--ggui-spacing-4, 16px)"
                        shadow="sm"
                        radius="lg"
                        style={{
                          backgroundColor: isOwn
                            ? 'var(--ggui-color-primary-600, #0284c7)'
                            : 'var(--ggui-color-surfaceVariant, #f4f4f5)',
                          color: isOwn ? '#ffffff' : 'var(--ggui-color-onSurface, #18181b)',
                        }}
                      >
                        <Text variant="body" color={isOwn ? '#ffffff' : undefined} style={{ margin: 0 }}>
                          {msg.text}
                        </Text>
                      </Card>
                    ))}
                    <Text
                      variant="caption"
                      color="var(--ggui-color-onSurfaceVariant, #52525b)"
                      style={{ opacity: 0.7, margin: 0 }}
                    >
                      {formatTime(group[group.length - 1].timestamp)}
                    </Text>
                  </Stack>
                  {isOwn && <Avatar name={props.currentUser} size="sm" />}
                </Stack>
              );
            })}
          </Stack>
        </Box>

        <Divider orientation="horizontal" margin={0} />

        {/* Input Area */}
        <Stack
          direction="horizontal"
          gap="var(--ggui-spacing-2, 8px)"
          align="flex-end"
          style={{ padding: 'var(--ggui-spacing-4, 16px)' }}
        >
          <div style={{ flex: 1 }}>
            <TextArea
              ref={inputRef}
              label="Message"
              placeholder="Type a message..."
              value={inputValue}
              onChange={setInputValue}
              rows={3}
              style={{ display: 'none' }}
              onKeyDown={(e: React.KeyboardEvent<HTMLTextAreaElement>) => {
                if ((e.ctrlKey || e.metaKey) && e.key === 'Enter') {
                  handleSend();
                }
              }}
            />
            <Input
              label="Message"
              placeholder="Type a message..."
              value={inputValue}
              onChange={setInputValue}
              onKeyDown={(e: React.KeyboardEvent<HTMLInputElement>) => {
                if (e.key === 'Enter' && !e.shiftKey) {
                  e.preventDefault();
                  handleSend();
                }
              }}
              style={{ display: 'block' }}
            />
          </div>
          <Button
            variant="primary"
            size="md"
            onClick={handleSend}
            disabled={!inputValue.trim()}
            aria-label="Send message"
          >
            Send
          </Button>
        </Stack>
      </Stack>
    </Container>
  );
}
