import { useState } from 'react'
import { useTranslation } from 'react-i18next'
import { Link } from '@tanstack/react-router'
import { Badge, Button, LoadingBlock, QueryErrorState } from '@/ui'
import { CaretLeftIcon, CaretRightIcon, ArrowSquareOutIcon } from '@phosphor-icons/react'
import { useRecordDependents } from '@/api/queries'
import type { OnCloseAction } from '@/api/client'

type Props = {
  dictionaryName: string
  businessKey: string | undefined
}

const onCloseVariant = (a: OnCloseAction): 'neutral' | 'warning' | 'error' => {
  if (a === 'CASCADE') return 'error'
  if (a === 'WARN') return 'warning'
  return 'neutral'
}

/**
 * Record-level dependents card — "На эту запись ссылаются:".
 *
 * <p>Показывает per-source summary (count + onClose mode) + paginated list
 * actual referencing records. Используется в RecordHistoryDrawer на странице
 * детали записи.
 *
 * <p>Hidden если record имеет 0 dependents (most records).
 *
 * <p>Pagination: prev/next через page state, default size=20. Server cap = 200.
 */
export const RecordDependentsPanel = ({ dictionaryName, businessKey }: Props) => {
  const { t } = useTranslation()
  const [page, setPage] = useState(0)
  const size = 20
  const { data, isLoading, error, refetch } = useRecordDependents(
    dictionaryName,
    businessKey,
    page,
    size,
  )

  if (!businessKey) return null
  if (isLoading) return <LoadingBlock size="sm" label={t('loading')} />
  if (error) {
    return <QueryErrorState error={error} onRetry={() => refetch()} />
  }
  if (!data || data.total === 0) return null

  const totalPages = Math.max(1, Math.ceil(data.total / size))

  // Staleness: show если MV active + last refresh > 2 min ago.
  // <2 min — fresh enough, не отвлекаем UI'ем.
  const stale =
    data.lineageMeta?.mvEnabled && data.lineageMeta.lastRefreshedAt
      ? Math.max(
          0,
          Math.floor(
            (Date.now() - new Date(data.lineageMeta.lastRefreshedAt).getTime()) /
              60000,
          ),
        )
      : null

  return (
    <section className="space-y-3">
      <div className="flex items-center justify-between">
        <h3 className="text-body font-sans text-ink">
          {t('lineage.refs.title')}
        </h3>
        <div className="flex items-center gap-2">
          {stale !== null && stale >= 2 && (
            <span
              className="text-cell text-mute px-2 py-0.5 rounded-sm border border-line"
              title={t('lineage.refs.staleHint')}
            >
              {t('lineage.refs.stale', { minutes: stale })}
            </span>
          )}
          <span className="text-cell text-mute">
            {t('lineage.refs.total', { count: data.total })}
          </span>
        </div>
      </div>

      {/* Per-source summary chips */}
      <ul className="flex flex-wrap gap-1.5">
        {data.perSource.map((s) => (
          <li
            key={`${s.sourceDict}.${s.sourceField}`}
            className="flex items-center gap-1.5 px-2 py-1 rounded-sm border border-line bg-line/30 text-cell"
          >
            <Link
              to="/dictionaries/$name"
              params={{ name: s.sourceDict }}
              className="text-accent hover:underline font-mono"
            >
              {s.sourceDisplayName ?? s.sourceDict}
            </Link>
            <span className="font-mono text-ink-2">.{s.sourceField}</span>
            <Badge variant="neutral">{s.count}</Badge>
            <Badge variant={onCloseVariant(s.onClose)}>
              {t(`lineage.onClose.${s.onClose}`)}
            </Badge>
          </li>
        ))}
      </ul>

      {/* Items list */}
      {data.items.length > 0 && (
        <ul className="divide-y divide-regolith border border-line rounded-sm">
          {data.items.map((r) => (
            <li
              key={r.id}
              className="flex items-center justify-between gap-3 px-3 py-2 text-cell"
            >
              <div className="min-w-0 flex-1">
                <div className="flex items-center gap-2">
                  <span className="font-mono text-ink-2">{r.sourceDict}</span>
                  <span className="text-mute/70">/</span>
                  <Link
                    to="/dictionaries/$name"
                    params={{ name: r.sourceDict }}
                    search={{ q: r.businessKey }}
                    className="text-accent hover:underline font-mono truncate"
                    aria-label={t('lineage.refs.openSourceRecord', {
                      key: r.businessKey,
                    })}
                  >
                    {r.businessKey}
                  </Link>
                  <ArrowSquareOutIcon
                    weight="bold"
                    size={12}
                    className="text-mute/70 shrink-0"
                  />
                </div>
                <div className="text-mute mt-0.5">
                  {t('lineage.refs.field', { field: r.sourceField })} ·{' '}
                  {t('lineage.refs.created', {
                    when: new Date(r.createdAt).toLocaleString(),
                  })}
                </div>
              </div>
            </li>
          ))}
        </ul>
      )}

      {/* Pagination */}
      {totalPages > 1 && (
        <div className="flex items-center justify-between text-cell">
          <Button
            variant="secondary"
            size="sm"
            leftIcon={<CaretLeftIcon weight="bold" size={12} />}
            disabled={page === 0}
            onClick={() => setPage((p) => Math.max(0, p - 1))}
          >
            {t('pagination.prev')}
          </Button>
          <span className="text-ink-2">
            {t('pagination.pageOf', { page: page + 1, total: totalPages })}
          </span>
          <Button
            variant="secondary"
            size="sm"
            rightIcon={<CaretRightIcon weight="bold" size={12} />}
            disabled={page >= totalPages - 1}
            onClick={() => setPage((p) => p + 1)}
          >
            {t('pagination.next')}
          </Button>
        </div>
      )}
    </section>
  )
}
