'use client';

import {VStack, HStack} from '@astryxdesign/core/Layout';
import {Card} from '@astryxdesign/core/Card';
import {Text, Heading} from '@astryxdesign/core/Text';
import {Banner} from '@astryxdesign/core/Banner';
import {Button} from '@astryxdesign/core/Button';
import {Icon} from '@astryxdesign/core/Icon';
import {AsyncBoundary} from '@/components/data/AsyncBoundary';
import {SkeletonRows} from '@/components/patterns/LoadingState';
import {EmptyPanel} from '@/components/patterns/EmptyPanel';
import {useResource} from '@/lib/api/useResource';
import {endpoints} from '@/lib/api/client';
import {useWorkspace} from '@/components/shell/WorkspaceProvider';
import {ICONS} from '@/lib/icons';
import type {InsightSeverity} from '@/lib/api/contracts';

/**
 * Reads the SAME briefing endpoint the dashboard does.
 *
 * This panel used to hold hardcoded Phase-1 copy, which was harmless while the
 * dashboard had no narrative of its own. Now that it does, static copy here is
 * actively wrong: the panel claimed "3 rewards expire in 48 hours" beside a
 * dashboard saying one, from the same screen. Two AI surfaces disagreeing about
 * the business is worse than one of them not existing.
 *
 * Scope comes from WorkspaceProvider, so the Copilot follows the store and
 * period the merchant is looking at rather than reporting on something else.
 */
const BANNER_STATUS: Record<
  InsightSeverity,
  'error' | 'warning' | 'info' | 'success'
> = {
  error: 'error',
  warning: 'warning',
  info: 'info',
  success: 'success',
};

export function AiTab() {
  const {storeId, range} = useWorkspace();
  const briefing = useResource(endpoints.dashboardBriefing({range, storeId}));

  return (
    <VStack gap={4} padding={4}>
      <AsyncBoundary resource={briefing} loading={<SkeletonRows count={6} />}>
        {(b) => (
          <VStack gap={4}>
            <Card variant="muted">
              <VStack gap={2}>
                <HStack gap={2} vAlign="center">
                  <Icon icon={ICONS.ai} size="sm" />
                  <Heading level={3}>Summary</Heading>
                </HStack>
                <Text size="sm" color="secondary">
                  {b.summary || 'Not enough activity in this period to summarise.'}
                </Text>
              </VStack>
            </Card>

            <VStack gap={2}>
              <Text size="sm" color="secondary">
                Needs attention
              </Text>
              {b.alerts.length === 0 ? (
                <EmptyPanel
                  icon="present"
                  title="All clear"
                  description="Nothing in this scope needs a decision right now."
                />
              ) : (
                b.alerts.map((a) => (
                  <Banner
                    key={a.id}
                    status={BANNER_STATUS[a.severity]}
                    title={a.title}
                    description={a.body}
                    endContent={
                      a.action ? (
                        <Button
                          variant="secondary"
                          size="sm"
                          label={a.action.label}
                          href={a.action.href}
                        />
                      ) : undefined
                    }
                  />
                ))
              )}
            </VStack>

            <VStack gap={2}>
              <Text size="sm" color="secondary">
                Open tasks
              </Text>
              {b.tasks
                .filter((t) => !t.isDone)
                .map((t) => (
                  <Card key={t.id}>
                    <VStack gap={1.5}>
                      <HStack gap={2} vAlign="center" hAlign="between">
                        <Text weight="medium">{t.label}</Text>
                        <Text size="xsm" color="secondary" textWrap="nowrap">
                          {t.due}
                        </Text>
                      </HStack>
                      {t.detail ? (
                        <Text size="sm" color="secondary">
                          {t.detail}
                        </Text>
                      ) : null}
                    </VStack>
                  </Card>
                ))}
            </VStack>
          </VStack>
        )}
      </AsyncBoundary>
    </VStack>
  );
}
