'use client';

import {TabList, Tab} from '@astryxdesign/core/TabList';
import {VStack, HStack} from '@astryxdesign/core/Layout';
import {Heading} from '@astryxdesign/core/Text';
import {IconButton} from '@astryxdesign/core/IconButton';
import {Icon} from '@astryxdesign/core/Icon';
import {ICONS} from '@/lib/icons';
import {useCopilot} from './CopilotProvider';
import type {CopilotTab} from './CopilotProvider';
import {AiTab} from './tabs/AiTab';
import {AnalyticsTab} from './tabs/AnalyticsTab';
import {ChatTab} from './tabs/ChatTab';

/**
 * The Copilot body. Rendered identically inside the inline LayoutPanel and
 * inside the slide-over — presentation differs, this does not. All of its
 * state comes from CopilotProvider, so it is safe to unmount and remount.
 */
export function CopilotPanel({onDismiss}: {onDismiss?: () => void}) {
  const {tab, setTab} = useCopilot();

  return (
    <VStack gap={0} height="100%">
      <HStack
        gap={2}
        vAlign="center"
        hAlign="between"
        paddingInline={4}
        paddingBlock={3}
      >
        <HStack gap={2} vAlign="center">
          <Icon icon={ICONS.ai} size="sm" />
          <Heading level={2}>Loyaly AI</Heading>
        </HStack>
        {onDismiss ? (
          <IconButton
            icon={<Icon icon={ICONS.panelClose} />}
            label="Hide Loyaly AI"
            variant="ghost"
            size="sm"
            onClick={onDismiss}
          />
        ) : null}
      </HStack>

      <TabList
        value={tab}
        onChange={(v) => setTab(v as CopilotTab)}
        layout="fill"
        size="sm"
        hasDivider
      >
        <Tab value="ai" label="AI" icon={<Icon icon={ICONS.ai} size="sm" />} />
        <Tab
          value="analytics"
          label="Analytics"
          icon={<Icon icon={ICONS.analytics} size="sm" />}
        />
        <Tab
          value="chat"
          label="Chat"
          icon={<Icon icon={ICONS.chat} size="sm" />}
        />
      </TabList>

      {/* The chat tab owns its own scroll container (ChatLayout docks the
          composer), so it must not be wrapped in a scrolling VStack. */}
      {tab === 'chat' ? (
        <ChatTab />
      ) : (
        <VStack height="100%" isScrollable>
          {tab === 'ai' ? <AiTab /> : <AnalyticsTab />}
        </VStack>
      )}
    </VStack>
  );
}
