'use client';
import { useState } from 'react';
import { useTranslations } from 'next-intl';
import { useSnackbar } from 'notistack';
import { Box, MenuItem, Skeleton, Stack, TextField } from '@mui/material';
import { AdminEmptyState, AdminErrorState, AdminPageHeader, AdminPager, ConfirmDialog, SupportAlertCard } from '@/components/admin';
import { useAdminCapabilities } from '@/hooks';
import { useAuth } from '@/context/auth';
import { ADMIN_PAGE_SIZE } from '@/services/admin/constants';
import type { SupportAlert, SupportAlertStatus, SupportAlertType } from '@/services/admin/types';
import { useSupportAlerts, useAssignSupportAlert, useResolveSupportAlert } from '@/services/admin';

const STATUSES: readonly SupportAlertStatus[] = ['open', 'assigned', 'resolved'];
const TYPES: readonly SupportAlertType[] = [
  'low_rating',
  'evv_no_show',
  'evv_location_mismatch',
  'verification_expired',
  'shared_sim',
  'payment_anomaly',
  'fraud_signal',
  'nurse_clawback',
  'emergency',
];

/**
 * Support-alert triage board (f15) — the **internal-only** worklist over `support_alerts`. Filter by
 * type/status; assign to self or resolve with a note. This data appears in **no** customer/nurse/partner
 * surface (phase §5). Server enforces the role scope; `canManageAlerts` only hides the controls.
 */
export default function AdminAlertsPage() {
  const t = useTranslations('admin');
  const caps = useAdminCapabilities();
  const { enqueueSnackbar } = useSnackbar();
  const [authState] = useAuth();
  const meId = authState.currentUser?.id ?? 1;

  const [status, setStatus] = useState<SupportAlertStatus | ''>('open');
  const [type, setType] = useState<SupportAlertType | ''>('');
  const [page, setPage] = useState(1);
  const [resolving, setResolving] = useState<SupportAlert | null>(null);

  const filters = { status: status || undefined, type: type || undefined };
  const alerts = useSupportAlerts(filters, page);
  const assign = useAssignSupportAlert();
  const resolve = useResolveSupportAlert();

  const items = alerts.data?.items ?? [];
  const pageCount = Math.max(1, Math.ceil((alerts.data?.total ?? 0) / ADMIN_PAGE_SIZE));

  const onAssignSelf = (alert: SupportAlert) => {
    assign.mutate(
      { alertId: alert.id, ownerUserId: meId },
      { onSuccess: () => enqueueSnackbar(t('alert_assigned'), { variant: 'success' }) },
    );
  };

  const onResolveConfirm = (note?: string) => {
    if (!resolving) return;
    resolve.mutate(
      { alertId: resolving.id, note: note ?? '' },
      {
        onSuccess: () => {
          enqueueSnackbar(t('alert_resolved'), { variant: 'success' });
          setResolving(null);
        },
      },
    );
  };

  return (
    <Box sx={{ display: 'flex', flexDirection: 'column', gap: 3 }}>
      <AdminPageHeader
        title={t('alert_title')}
        subtitle={t('alert_subtitle')}
        actions={
          <Stack direction="row" sx={{ gap: 1, flexWrap: 'wrap' }}>
            <TextField
              select
              size="small"
              label={t('alert_col_status')}
              value={status}
              onChange={(e) => {
                setStatus(e.target.value as SupportAlertStatus | '');
                setPage(1);
              }}
              sx={{ minWidth: 140 }}
            >
              <MenuItem value="">{t('filter_all')}</MenuItem>
              {STATUSES.map((s) => (
                <MenuItem key={s} value={s}>
                  {t(`astatus_${s}`)}
                </MenuItem>
              ))}
            </TextField>
            <TextField
              select
              size="small"
              label={t('alert_col_type')}
              value={type}
              onChange={(e) => {
                setType(e.target.value as SupportAlertType | '');
                setPage(1);
              }}
              sx={{ minWidth: 180 }}
            >
              <MenuItem value="">{t('filter_all')}</MenuItem>
              {TYPES.map((ty) => (
                <MenuItem key={ty} value={ty}>
                  {t(`atype_${ty}`)}
                </MenuItem>
              ))}
            </TextField>
          </Stack>
        }
      />

      {alerts.isLoading ? (
        <Stack sx={{ gap: 2 }}>{[0, 1, 2].map((k) => <Skeleton key={k} variant="rounded" height={110} />)}</Stack>
      ) : alerts.isError ? (
        <AdminErrorState message={t('error_generic')} retryLabel={t('retry')} onRetry={() => alerts.refetch()} />
      ) : items.length === 0 ? (
        <AdminEmptyState icon="alerts" title={t('alert_empty')} />
      ) : (
        <Stack sx={{ gap: 2 }}>
          {items.map((alert) => (
            <SupportAlertCard
              key={alert.id}
              alert={alert}
              canAct={caps.canManageAlerts}
              onAssignSelf={onAssignSelf}
              onResolve={setResolving}
            />
          ))}
        </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 })}
      />

      <ConfirmDialog
        open={resolving != null}
        title={t('alert_resolve_title')}
        confirmLabel={t('alert_resolve')}
        cancelLabel={t('cancel')}
        onConfirm={onResolveConfirm}
        onClose={() => setResolving(null)}
        loading={resolve.isPending}
        requireReason
        reasonLabel={t('note_label')}
        reasonPlaceholder={t('alert_resolve_note_ph')}
      />
    </Box>
  );
}
