import { useState } from 'react'
import { useQuery } from '@tanstack/react-query'
import { api } from '@/lib/api'
import { ListPageShell } from '@/components/ListPageShell'
import { DataTable } from '@/components/DataTable'
import { Pagination } from '@/components/Pagination'
import { SearchBar } from '@/components/SearchBar'
import { Field, Select } from '@/components/Field'
import type { PagedResult } from '@/lib/types'

interface AuditRow {
  id: string
  createdAt: string
  userId: string | null
  userName: string | null
  action: string
  entityType: string
  entityId: string | null
  changesJson: string
}

const ACTIONS = [
  { value: '', label: 'Все' },
  { value: 'create', label: 'Создание' },
  { value: 'update', label: 'Изменение' },
  { value: 'delete', label: 'Удаление' },
]

const ENTITY_TYPES = [
  { value: '', label: 'Все' },
  { value: 'Supply', label: 'Приёмки' },
  { value: 'SupplierReturn', label: 'Возвраты поставщикам' },
  { value: 'RetailSale', label: 'Чеки розничные' },
  { value: 'Demand', label: 'Оптовые отгрузки' },
  { value: 'Product', label: 'Товары' },
  { value: 'Counterparty', label: 'Контрагенты' },
]

/** Журнал мутаций tenant'а — кто, что и когда менял. Read-only.
 * Запись делает OrgAuditInterceptor автоматически на каждом SaveChanges. */
export function OrgAuditLogPage() {
  const [page, setPage] = useState(1)
  const [entityType, setEntityType] = useState('')
  const [action, setAction] = useState('')
  const [search, setSearch] = useState('')

  const params = new URLSearchParams({ page: String(page), pageSize: '50' })
  if (entityType) params.set('entityType', entityType)
  if (action) params.set('action', action)

  const rep = useQuery({
    queryKey: ['audit-log', page, entityType, action],
    queryFn: async () => (await api.get<PagedResult<AuditRow>>(`/api/admin/audit-log?${params}`)).data,
    placeholderData: (prev) => prev,
  })

  const filtered = (rep.data?.items ?? []).filter((r) => {
    if (!search) return true
    const s = search.toLowerCase()
    return (r.userName ?? '').toLowerCase().includes(s)
      || r.entityType.toLowerCase().includes(s)
      || r.changesJson.toLowerCase().includes(s)
  })

  return (
    <ListPageShell
      title="Журнал изменений"
      description={rep.data ? `${rep.data.total.toLocaleString('ru')} событий` : 'Все мутации документов и справочников.'}
      actions={
        <>
          <SearchBar value={search} onChange={setSearch} placeholder="По имени, типу, тексту…" />
        </>
      }
      footer={rep.data && rep.data.total > 0 && (
        <Pagination page={page} pageSize={rep.data.pageSize} total={rep.data.total} onPageChange={setPage} />
      )}
    >
      <div className="flex gap-3 mb-3 max-w-2xl">
        <Field label="Тип сущности">
          <Select value={entityType} onChange={(e) => { setEntityType(e.target.value); setPage(1) }}>
            {ENTITY_TYPES.map((t) => <option key={t.value} value={t.value}>{t.label}</option>)}
          </Select>
        </Field>
        <Field label="Действие">
          <Select value={action} onChange={(e) => { setAction(e.target.value); setPage(1) }}>
            {ACTIONS.map((a) => <option key={a.value} value={a.value}>{a.label}</option>)}
          </Select>
        </Field>
      </div>

      <DataTable
        rows={filtered}
        isLoading={rep.isLoading}
        rowKey={(r) => r.id}
        columns={[
          { header: 'Когда', width: '170px', cell: (r) => new Date(r.createdAt).toLocaleString('ru') },
          { header: 'Кто', width: '180px', cell: (r) => r.userName ?? <span className="text-slate-400">система</span> },
          { header: 'Тип', width: '140px', cell: (r) => r.entityType },
          { header: 'Действие', width: '110px', cell: (r) => (
            <span className={`text-xs px-2 py-0.5 rounded ${
              r.action === 'create' ? 'bg-green-50 text-green-700' :
              r.action === 'delete' ? 'bg-red-50 text-red-700' :
              'bg-slate-100 text-slate-700'
            }`}>{r.action}</span>
          )},
          { header: 'EntityId', width: '110px', cell: (r) => (
            r.entityId ? <span className="font-mono text-xs text-slate-500">{r.entityId.slice(0, 8)}</span> : '—'
          )},
          { header: 'Изменения', cell: (r) => (
            <details className="text-xs">
              <summary className="cursor-pointer text-slate-500 hover:text-slate-700">показать diff</summary>
              <pre className="mt-1 p-2 bg-slate-50 dark:bg-slate-800 rounded text-[10px] max-w-2xl overflow-x-auto">{
                (() => {
                  try { return JSON.stringify(JSON.parse(r.changesJson), null, 2) }
                  catch { return r.changesJson }
                })()
              }</pre>
            </details>
          )},
        ]}
        empty="Событий пока нет."
      />
    </ListPageShell>
  )
}
