import { Button, Flex, Tabs, Typography } from 'antd';
import { useMemo, useState } from 'react';
import type { SampleMeta } from '../../../widgets/core';
import { PreviewerUI } from '../PreviewerUI';

const { Paragraph, Text } = Typography;

export const sampleMeta: SampleMeta = {
  id: 'previewer-ui',
  componentId: 'previewer-ui',
  title: 'Previewer UI',
  description:
    'text, json, code, image를 공통 레이아웃으로 렌더링하고 markdown, empty 같은 추가 preview 타입도 지원하는 공통 previewer 컴포넌트입니다.',
  category: 'Display',
  kind: 'feature',
  variantLabel: 'Showcase',
  order: 70,
  features: ['docs'],
};

const sampleImage =
  'data:image/svg+xml;utf8,' +
  encodeURIComponent(`
    <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 800 420">
      <defs>
        <linearGradient id="bg" x1="0%" y1="0%" x2="100%" y2="100%">
          <stop offset="0%" stop-color="#165dff"/>
          <stop offset="100%" stop-color="#28c76f"/>
        </linearGradient>
      </defs>
      <rect width="800" height="420" rx="32" fill="url(#bg)"/>
      <rect x="66" y="72" width="668" height="276" rx="24" fill="rgba(255,255,255,0.16)"/>
      <circle cx="120" cy="122" r="14" fill="#fff"/>
      <circle cx="162" cy="122" r="14" fill="#fff" opacity="0.72"/>
      <rect x="110" y="174" width="240" height="24" rx="12" fill="#fff"/>
      <rect x="110" y="214" width="430" height="18" rx="9" fill="#fff" opacity="0.78"/>
      <rect x="110" y="246" width="360" height="18" rx="9" fill="#fff" opacity="0.6"/>
      <rect x="560" y="176" width="120" height="96" rx="18" fill="rgba(255,255,255,0.24)"/>
    </svg>
  `);

export function Sample() {
  const [activeKey, setActiveKey] = useState('text');
  const [codeLanguage, setCodeLanguage] = useState('typescript');
  const codeExamples = useMemo(
    () => ({
      typescript: `type WindowState = {\n  id: string;\n  title: string;\n  active: boolean;\n};\n\nconst activateWindow = (windows: WindowState[], id: string) =>\n  windows.map((window) => ({\n    ...window,\n    active: window.id === id,\n  }));`,
      json: `{\n  "status": "ok",\n  "activeWindow": "inventory-board",\n  "layout": "grid",\n  "windows": [\n    {\n      "id": "inventory-board",\n      "zIndex": 4\n    }\n  ]\n}`,
      html: `<section class="window-panel">\n  <header class="window-panel__header">\n    <h1>Inventory Board</h1>\n    <button type="button">Open</button>\n  </header>\n  <main class="window-panel__body">\n    <p>입고 검수 대기 12건</p>\n  </main>\n</section>`,
      css: `.window-panel {\n  display: grid;\n  gap: 12px;\n  padding: 16px;\n  border-radius: 18px;\n  background: linear-gradient(180deg, #eff6ff 0%, #ffffff 100%);\n}\n\n.window-panel__header {\n  display: flex;\n  justify-content: space-between;\n}`,
      bash: `npm run build\ndocker compose restart app\nnpm run capture:component -- previewer-ui 2026-04-02`,
      sql: `select\n  window_id,\n  title,\n  z_index,\n  updated_at\nfrom ui_window_state\nwhere active = true\norder by z_index desc;`,
      yaml: `previewer:\n  type: code\n  language: typescript\n  height: 320\n  toolbar:\n    copy: true\n    download: false`,
    }),
    [],
  );
  const previewItems = useMemo(
    () => [
      {
        key: 'text',
        label: 'Text',
        node: (
          <PreviewerUI
            type="text"
            title="Text Preview"
            description="로그, 설명, 사용자 메시지를 바로 읽을 수 있는 기본 text preview"
            value={'배송 지연 알림\n- 부산 센터 출고 지연\n- 오후 3시 재처리 예정'}
          />
        ),
      },
      {
        key: 'json',
        label: 'JSON',
        node: (
          <PreviewerUI
            type="json"
            title="JSON Preview"
            description="응답 payload, 설정 객체, 샘플 데이터를 JSON 형태로 표시"
            value={{
              status: 'ok',
              warehouse: 'ICN-01',
              pendingTasks: 12,
              operators: ['Kim', 'Lee', 'Park'],
            }}
          />
        ),
      },
      {
        key: 'code',
        label: 'Code',
        node: (
          <PreviewerUI
            type="code"
            title="Code Preview"
            description="언어를 선택하면 VSCode 스타일로 토큰 색상을 적용해 코드 미리보기"
            language={codeLanguage}
            languageOptions={[
              { label: 'TypeScript', value: 'typescript' },
              { label: 'JSON', value: 'json' },
              { label: 'HTML', value: 'html' },
              { label: 'CSS', value: 'css' },
              { label: 'Bash', value: 'bash' },
              { label: 'SQL', value: 'sql' },
              { label: 'YAML', value: 'yaml' },
            ]}
            onLanguageChange={setCodeLanguage}
            value={codeExamples[codeLanguage as keyof typeof codeExamples]}
          />
        ),
      },
      {
        key: 'image',
        label: 'Image',
        node: (
          <PreviewerUI
            type="image"
            title="Image Preview"
            description="썸네일, 캡처 이미지, 리치 미디어 미리보기"
            value={sampleImage}
            imageAlt="preview sample"
          />
        ),
      },
      {
        key: 'markdown',
        label: 'Markdown',
        node: (
          <PreviewerUI
            type="markdown"
            title="Markdown Preview"
            description="작업일지, 가이드 문서를 가볍게 확인하는 markdown preview"
            value={`# 작업 메모\n## 오늘 처리\n- 입고 검수\n- 피킹 대기 해소\n\n\`\`\`ts\nconst ready = true;\n\`\`\``}
          />
        ),
      },
      {
        key: 'empty',
        label: 'Empty',
        node: (
          <PreviewerUI
            type="empty"
            title="Empty Preview"
            description="데이터가 없을 때도 동일한 레이아웃에서 빈 상태를 표현"
            value="선택된 파일이 없습니다."
            toolbar={<Button size="small">업로드</Button>}
          />
        ),
      },
    ],
    [activeKey, codeExamples, codeLanguage],
  );

  return (
    <Flex vertical gap={16}>
      <Paragraph>
        공통 previewer 하나로 <Text strong>text</Text>, <Text strong>json</Text>, <Text strong>code</Text>,{' '}
        <Text strong>image</Text>를 처리하고, 추가로 유용한 <Text strong>markdown</Text>,{' '}
        <Text strong>empty</Text> 타입도 함께 제공합니다.
      </Paragraph>

      <Tabs
        activeKey={activeKey}
        onChange={setActiveKey}
        items={previewItems.map((item) => ({
          key: item.key,
          label: item.label,
          children: item.node,
        }))}
      />
    </Flex>
  );
}
