import { ExportOutlined, LinkOutlined, ShareAltOutlined } from '@ant-design/icons';
import { App, Button, Typography } from 'antd';
import { PromptPreviewSurface } from './ChatPromptCard';
import { sharePreviewLink } from './chatUtils';
import { openChatExternalLink } from './linkNavigation';
import type { ChatMessagePart } from './types';

const { Paragraph } = Typography;

function resolveStructuredPreviewKindLabel(target: Extract<ChatMessagePart, { type: 'preview_card' }>) {
  const explicit = target.kindLabel?.trim();

  if (explicit) {
    return explicit;
  }

  switch (target.preview.type) {
    case 'markdown':
      return 'markdown card';
    case 'html':
      return 'html card';
    case 'image':
      return 'image card';
    default:
      return 'resource card';
  }
}

export function ChatStructuredPreviewCard({
  target,
  onOpen,
}: {
  target: Extract<ChatMessagePart, { type: 'preview_card' }>;
  onOpen?: (previewUrl?: string | null) => void;
}) {
  const { message } = App.useApp();
  const normalizedPreviewUrl = target.preview.url?.trim() || null;

  const handleShare = () => {
    if (!normalizedPreviewUrl) {
      message.info('이 카드는 공유할 링크가 없습니다.');
      return;
    }

    onOpen?.(normalizedPreviewUrl);
    void sharePreviewLink({
      url: normalizedPreviewUrl,
      title: target.title,
    })
      .then((result) => {
        message.success(result === 'shared' ? '카드 링크를 공유했습니다.' : '카드 링크를 복사했습니다.');
      })
      .catch((error: unknown) => {
        if (error instanceof DOMException && error.name === 'AbortError') {
          return;
        }

        message.error(error instanceof Error ? error.message : '카드 링크를 공유하지 못했습니다.');
      });
  };

  return (
    <section className="app-chat-preview-card app-chat-preview-card--structured">
      <div className="app-chat-preview-card__header">
        <div className="app-chat-preview-card__meta">
          <span className="app-chat-preview-card__glyph app-chat-preview-card__glyph--prompt" aria-hidden="true">
            <LinkOutlined />
          </span>
          <div className="app-chat-preview-card__titles">
            <span className="app-chat-preview-card__label">{target.title}</span>
            <span className="app-chat-preview-card__kind">{resolveStructuredPreviewKindLabel(target)}</span>
          </div>
        </div>
        <div className="app-chat-preview-card__actions">
          {normalizedPreviewUrl ? (
            <>
              <Button
                type="text"
                size="small"
                className="app-chat-preview-card__action"
                icon={<ShareAltOutlined />}
                aria-label={`${target.title} 카드 공유`}
                onClick={handleShare}
              />
              <Button
                type="link"
                size="small"
                className="app-chat-preview-card__open-link"
                icon={<ExportOutlined />}
                onClick={(event) => {
                  onOpen?.(normalizedPreviewUrl);
                  void openChatExternalLink(normalizedPreviewUrl, event);
                }}
              >
                {target.actionLabel?.trim() || '열기'}
              </Button>
            </>
          ) : null}
        </div>
      </div>
      <div className="app-chat-preview-card__body app-chat-preview-card__body--structured">
        {target.description ? <Paragraph className="app-chat-preview-card__description">{target.description}</Paragraph> : null}
        <div className="app-chat-prompt-card__preview-shell">
          <div className="app-chat-prompt-card__preview-body">
            <PromptPreviewSurface preview={target.preview} compact />
          </div>
        </div>
      </div>
    </section>
  );
}
