'use client';
import { Suspense, useState } from 'react';
import { useTranslations } from 'next-intl';
import { useSnackbar } from 'notistack';
import { Box, MenuItem, Skeleton, Stack, TextField } from '@mui/material';
import { AppLoading } from '@/components';
import { AdminEmptyState, AdminErrorState, AdminPageHeader, AdminPager, ConfirmDialog, SupportAlertCard } from '@/components/admin';
import { useAdminCapabilities, useAdminListState } 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';

interface AlertFilters {
  status?: SupportAlertStatus;
  type?: SupportAlertType;
}

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',
];

const EMPTY: AlertFilters = { status: 'open' };

function parseFilters(params: URLSearchParams): AlertFilters {
  const status = params.get('status') as SupportAlertStatus | null;
  const type = params.get('type') as SupportAlertType | null;
  return {
    status: status && STATUSES.includes(status) ? status : undefined,
    type: type && TYPES.includes(type) ? type : undefined,
  };
}

function serializeFilters(filters: AlertFilters): Record<string, string> {
  const r: Record<string, string> = {};
  if (filters.status) r.status = filters.status;
  if (filters.type) r.type = filters.type;
  return r;
}

/**
 * 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() {
  return (
    <Suspense fallback={<AppLoading />}>
      <AdminAlertsPageInner />
    </Suspense>
  );
}

function AdminAlertsPageInner() {
  const t = useTranslations('admin');
  const caps = useAdminCapabilities();
  const { enqueueSnackbar } = useSnackbar();
  const [authState] = useAuth();
  const meId = authState.currentUser?.id;

  const listState = useAdminListState<AlertFilters>({ parse: parseFilters, serialize: serializeFilters, empty: EMPTY });
  const { applied: filters, page } = listState;
  const [resolving, setResolving] = useState<SupportAlert | null>(null);

  const alerts = useSupportAlerts(filters, page);
  const assign = useAssignSupportAlert();
  const resolve = useResolveSupportAlert();

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

  // Assign-to-self MUST NEVER default to a guessed user (the fixed defect: `?? 1`) — the button is simply
  // disabled with a "loading your account" tooltip until the real id has hydrated.
  const onAssignSelf = (alert: SupportAlert) => {
    if (meId == null) return;
    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);
        },
      },
    );
  };

  const setStatusFilter = (value: SupportAlertStatus | '') =>
    listState.applyFilters({ ...filters, status: value || undefined });
  const setTypeFilter = (value: SupportAlertType | '') =>
    listState.applyFilters({ ...filters, type: value || undefined });

  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={filters.status ?? ''}
              onChange={(e) => setStatusFilter(e.target.value as SupportAlertStatus | '')}
              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={filters.type ?? ''}
              onChange={(e) => setTypeFilter(e.target.value as SupportAlertType | '')}
              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}
              assignSelfDisabled={meId == null}
              assignSelfDisabledTitle={t('assign_me_loading')}
            />
          ))}
        </Stack>
      )}

      <AdminPager
        page={page}
        pageCount={pageCount}
        onPrev={() => listState.goToPage(Math.max(1, page - 1))}
        onNext={() => listState.goToPage(Math.min(pageCount, page + 1))}
        prevLabel={t('prev_page')}
        nextLabel={t('next_page')}
        indicator={t('page_indicator', { page, total: pageCount })}
      />

      <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>
  );
}
