import { useState } from 'react'
import { useTranslation } from 'react-i18next'
import { Badge, Tabs, type TabItem } from '@/ui'
import { generateEventPreviews } from './eventPreview'
import type { DataScope, JsonSchema } from '@/api/client'

type Props = {
  dictionaryName: string
  dataScope: DataScope
  bundle: string
  schema: JsonSchema
  businessKeyField?: string
}

/**
 * Preview tab inside DictionaryEditorDialog. Показывает sample JSON envelope
 * для каждого event type, который Kafka получит после save'а dict / records.
 *
 * <p>Помогает integrators (Альтум, Геопортал, etc) понять shape события до
 * того как dict published. Без этого они вынуждены ждать live event'а
 * чтобы посмотреть payload.
 *
 * <p>Pure client-side preview — не отправляет ничего в Kafka. Sample data
 * генерится из schema properties (string → "sample", integer → 42, и т.д.).
 */
export const EventsPreviewTab = ({
  dictionaryName,
  dataScope,
  bundle,
  schema,
  businessKeyField,
}: Props) => {
  const { t } = useTranslation()
  const previews = generateEventPreviews(
    dictionaryName || 'sample_dict',
    dataScope,
    bundle || 'cuod',
    schema,
    businessKeyField,
  )
  const [active, setActive] = useState(previews[0]?.eventType ?? 'RecordCreated')
  const current = previews.find((p) => p.eventType === active) ?? previews[0]
  const tabs: TabItem[] = previews.map((p) => ({
    id: p.eventType,
    label: p.label,
  }))

  return (
    <div className="space-y-3">
      <p className="text-sm text-carbon/70">
        {t('schema.events.intro')}
      </p>

      <Tabs items={tabs} value={active} onValueChange={setActive} />

      {current && (
        <div className="space-y-2">
          <div className="flex items-center gap-2 flex-wrap">
            <Badge variant="info">{current.eventType}</Badge>
            <span className="text-2xs text-carbon/70">
              {t('schema.events.topic')}:
            </span>
            <code className="text-2xs font-mono text-ultramarain">
              {current.topic}
            </code>
          </div>
          <p className="text-2xs text-carbon/60">{current.description}</p>
          <pre className="bg-regolith/30 rounded p-3 text-2xs font-mono overflow-x-auto whitespace-pre-wrap">
            {JSON.stringify(current.envelope, null, 2)}
          </pre>
          <p className="text-2xs text-carbon/50">
            {t('schema.events.disclaimer')}
          </p>
        </div>
      )}
    </div>
  )
}
