import { useTranslation } from 'react-i18next'
import { Alert, Badge, Drawer, LoadingBlock } from '@/ui'
import { useRecordHistory } from '@/api/queries'
import { RecordDependentsPanel } from '@/components/lineage/RecordDependentsPanel'

type Props = {
  open: boolean
  onClose: () => void
  dictionaryName: string
  businessKey: string | undefined
}

export const RecordHistoryDrawer = ({ open, onClose, dictionaryName, businessKey }: Props) => {
  const { t } = useTranslation()
  const { data, isLoading, error } = useRecordHistory(dictionaryName, open ? businessKey : undefined)

  return (
    <Drawer
      isOpen={open}
      onClose={onClose}
      title={businessKey ? `${t('history.title')}: ${businessKey}` : t('history.title')}
      side="right"
      widthClassName="w-full max-w-2xl"
    >
      <div className="space-y-4">
        {/* Phase 1 dict-relationships-v2: surface incoming references first.
            Component сам hide'ится при 0 dependents — для большинства записей
            этот блок не появится. */}
        {open && (
          <RecordDependentsPanel
            dictionaryName={dictionaryName}
            businessKey={businessKey}
          />
        )}

        {isLoading && <LoadingBlock size="md" label={t('loading')} />}
        {error && (
          <Alert variant="error" title={t('error.failed')}>
            {String(error)}
          </Alert>
        )}
        {data && data.length === 0 && (
          <p className="text-body text-mute">{t('history.empty')}</p>
        )}
        {data && data.length > 0 && (
          <ol className="relative border-l-2 border-line pl-5 space-y-4">
            {data.map((rec, idx) => {
              const isLatest = idx === 0
              const displayVersion = data.length - idx
              const now = new Date()
              const from = new Date(rec.validFrom)
              const to = new Date(rec.validTo)
              const farFuture = to.getFullYear() >= 9999
              // Статус по реальному времени:
              //   future  — validFrom ещё впереди (запланирована)
              //   active  — сейчас в её диапазоне
              //   expired — validTo уже прошла (закрыта)
              const status = from > now
                ? 'future'
                : !farFuture && to <= now
                  ? 'expired'
                  : 'active'
              return (
                <li key={rec.id} className="relative">
                  <span
                    className={`absolute -left-[27px] top-1 h-3 w-3 rounded-full border-2 ${
                      isLatest && status === 'active'
                        ? 'bg-accent border-accent'
                        : status === 'future'
                          ? 'bg-warn border-horizon'
                          : status === 'expired'
                            ? 'bg-white border-ink/40'
                            : 'bg-aurora border-aurora'
                    }`}
                  />
                  <div className="flex items-center gap-2 mb-1">
                    <span className="text-body font-sans text-accent">v{displayVersion}</span>
                    {isLatest && status === 'active' && (
                      <Badge variant="primary">{t('history.current')}</Badge>
                    )}
                    {status === 'future' && <Badge variant="info">{t('history.scheduled')}</Badge>}
                    {status === 'expired' && <Badge variant="neutral">{t('history.closed')}</Badge>}
                    {status === 'active' && !isLatest && (
                      <Badge variant="success">{t('history.active')}</Badge>
                    )}
                  </div>
                  <div className="text-cell text-ink-2 space-y-0.5">
                    <div>
                      <span className="font-mono">{t('history.validFrom')}:</span>{' '}
                      {new Date(rec.validFrom).toLocaleString()}
                    </div>
                    {!farFuture && (
                      <div>
                        <span className="font-mono">{t('history.validTo')}:</span>{' '}
                        {new Date(rec.validTo).toLocaleString()}
                      </div>
                    )}
                    {rec.updatedBy && (
                      <div>
                        <span className="font-mono">{t('history.updatedBy')}:</span> {rec.updatedBy}
                      </div>
                    )}
                  </div>
                  <details className="mt-2">
                    <summary className="text-cell text-accent cursor-pointer hover:underline">
                      {t('history.viewData')}
                    </summary>
                    <pre className="text-mono mt-1 bg-line/30 rounded p-2 overflow-x-auto">
                      {JSON.stringify(rec.data, null, 2)}
                    </pre>
                  </details>
                </li>
              )
            })}
          </ol>
        )}
      </div>
    </Drawer>
  )
}
