'use client';
import { useState } from 'react';
import { useLocale, useTranslations } from 'next-intl';
import { Box, Chip, Stack, TextField, Typography } from '@mui/material';
import { AdminDataTable, AdminEmptyState, AdminPageHeader, type AdminTableColumn } from '@/components/admin';
import { AppLink } from '@/components';
import { ROUTES } from '@/constants';
import { useUserSearch } from '@/services/admin';
import { useDebouncedValue } from '@/services/search';
import type { AdminUserSummary, DirectoryUserRole } from '@/services/admin/types';

const SEARCH_DEBOUNCE_MS = 300;
const MIN_QUERY_LENGTH = 2;

/** Directory role → chip label key. */
const ROLE_LABEL_KEY: Record<DirectoryUserRole, string> = {
  customer: 'user_role_customer',
  nurse: 'user_role_nurse',
  admin: 'user_role_admin',
  partner: 'user_role_partner',
};

/**
 * Read-first admin user directory (phase §3.8) — search by name/phone over the same admin user-directory
 * seam `UserPicker`/`NursePicker` use (REQ-061, gap — mock-backed until delivered). Built because the REQ
 * this console depends on is filed and mocked-behind-the-seam this same phase; it becomes real the moment
 * `services/admin`'s seam flips. Each row links into the audit log filtered to that user (the one console
 * that already supports an entity filter) — a ticket-queue deep link isn't offered because the admin
 * ticket queue has no actor/user filter to land on (would be a dishonest link).
 */
export default function AdminUsersPage() {
  const t = useTranslations('admin');
  const locale = useLocale();
  const [query, setQuery] = useState('');
  const debounced = useDebouncedValue(query, SEARCH_DEBOUNCE_MS);
  const search = useUserSearch(debounced);
  const items = search.data ?? [];
  const hasQuery = debounced.trim().length >= MIN_QUERY_LENGTH;

  const columns: AdminTableColumn<AdminUserSummary>[] = [
    { key: 'name', header: t('user_col_name'), render: (u) => u.displayName, minWidth: 180 },
    {
      key: 'phone',
      header: t('user_col_phone'),
      render: (u) => (
        <Box component="span" dir="ltr">
          {u.maskedPhone}
        </Box>
      ),
    },
    { key: 'id', header: t('user_col_id'), render: (u) => `#${u.id}` },
    {
      key: 'roles',
      header: t('user_col_roles'),
      render: (u) => (
        <Stack direction="row" sx={{ gap: 0.5, flexWrap: 'wrap' }}>
          {u.roles.map((r) => (
            <Chip key={r} size="small" variant="outlined" label={t(ROLE_LABEL_KEY[r])} />
          ))}
        </Stack>
      ),
    },
    {
      key: 'actions',
      header: '',
      align: 'right' as const,
      render: (u) => (
        <AppLink to={`/${locale}${ROUTES.ADMIN_AUDIT}?entityType=User&entityId=${u.id}`}>{t('user_view_audit')}</AppLink>
      ),
    },
  ];

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

      <TextField
        size="small"
        label={t('user_search_label')}
        placeholder={t('user_picker_search_ph')}
        value={query}
        onChange={(e) => setQuery(e.target.value)}
        sx={{ maxWidth: 360 }}
      />

      {!hasQuery ? (
        <Typography variant="body2" sx={{ color: 'text.secondary' }}>
          {t('user_search_hint')}
        </Typography>
      ) : search.isFetching ? (
        <Typography variant="body2" sx={{ color: 'text.secondary' }}>
          {t('user_picker_loading')}
        </Typography>
      ) : items.length === 0 ? (
        <AdminEmptyState icon="users" title={t('user_empty')} />
      ) : (
        <AdminDataTable columns={columns} rows={items} getRowKey={(u) => u.id} ariaLabel={t('user_title')} />
      )}
    </Box>
  );
}
