'use client';
import { useState } from 'react';
import { useTranslations } from 'next-intl';
import { Box, Skeleton, Stack, TextField } from '@mui/material';
import { AppButton } from '@/components';
import { AdminEmptyState, AdminErrorState, AdminPageHeader, AdminPager, AuditLogRow } from '@/components/admin';
import { AUDIT_PAGE_SIZE } from '@/services/admin/constants';
import type { AuditFilters } from '@/services/admin/types';
import { useAuditLogs } from '@/services/admin';

const EMPTY: AuditFilters = {};

/**
 * Append-only audit-log viewer (f15) — a read-only, filtered, paginated table of every admin state change,
 * each row expandable to its `changed_fields` diff. There is **no** edit/delete affordance (phase §5). The
 * filter draft is committed to the query only on Apply, so typing never refetches; the applied filters +
 * page are the cache key, so switching filters/pages never refetches data already held.
 */
export default function AdminAuditPage() {
  const t = useTranslations('admin');
  const [draft, setDraft] = useState<AuditFilters>(EMPTY);
  const [applied, setApplied] = useState<AuditFilters>(EMPTY);
  const [page, setPage] = useState(1);

  const audit = useAuditLogs(applied, page);
  const items = audit.data?.items ?? [];
  const pageCount = Math.max(1, Math.ceil((audit.data?.total ?? 0) / AUDIT_PAGE_SIZE));

  const apply = () => {
    setApplied(draft);
    setPage(1);
  };
  const clear = () => {
    setDraft(EMPTY);
    setApplied(EMPTY);
    setPage(1);
  };

  return (
    <Box sx={{ display: 'flex', flexDirection: 'column', gap: 3 }}>
      <AdminPageHeader title={t('audit_title')} subtitle={t('audit_subtitle')} />

      <Stack
        direction="row"
        sx={{ gap: 1.5, flexWrap: 'wrap', alignItems: 'center', p: 2, border: '1px solid', borderColor: 'divider', borderRadius: 2 }}
      >
        <TextField
          size="small"
          label={t('audit_col_entity')}
          placeholder={t('audit_entity_type_ph')}
          value={draft.entityType ?? ''}
          onChange={(e) => setDraft((d) => ({ ...d, entityType: e.target.value || undefined }))}
          sx={{ minWidth: 200 }}
        />
        <TextField
          size="small"
          label="ID"
          placeholder={t('audit_entity_id_ph')}
          value={draft.entityId ?? ''}
          onChange={(e) => setDraft((d) => ({ ...d, entityId: e.target.value || undefined }))}
          sx={{ minWidth: 120 }}
        />
        <TextField
          size="small"
          type="date"
          label={t('audit_from')}
          value={draft.from ?? ''}
          onChange={(e) => setDraft((d) => ({ ...d, from: e.target.value || undefined }))}
          slotProps={{ inputLabel: { shrink: true } }}
        />
        <TextField
          size="small"
          type="date"
          label={t('audit_to')}
          value={draft.to ?? ''}
          onChange={(e) => setDraft((d) => ({ ...d, to: e.target.value || undefined }))}
          slotProps={{ inputLabel: { shrink: true } }}
        />
        <AppButton variant="contained" color="primary" onClick={apply}>
          {t('apply')}
        </AppButton>
        <AppButton variant="text" color="inherit" onClick={clear}>
          {t('clear')}
        </AppButton>
      </Stack>

      {audit.isLoading ? (
        <Stack sx={{ gap: 1 }}>{[0, 1, 2, 3].map((k) => <Skeleton key={k} variant="rounded" height={56} />)}</Stack>
      ) : audit.isError ? (
        <AdminErrorState message={t('error_generic')} retryLabel={t('retry')} onRetry={() => audit.refetch()} />
      ) : items.length === 0 ? (
        <AdminEmptyState icon="audit" title={t('audit_empty')} />
      ) : (
        <Stack sx={{ gap: 1 }}>
          {items.map((entry) => (
            <AuditLogRow key={entry.id} entry={entry} />
          ))}
        </Stack>
      )}

      <AdminPager
        page={page}
        pageCount={pageCount}
        onPrev={() => setPage((p) => Math.max(1, p - 1))}
        onNext={() => setPage((p) => Math.min(pageCount, p + 1))}
        prevLabel={t('prev_page')}
        nextLabel={t('next_page')}
        indicator={t('page_indicator', { page })}
      />
    </Box>
  );
}
