'use client';
import { FunctionComponent } from 'react';
import { useLocale, useTranslations } from 'next-intl';
import { Chip, Paper, Stack, Typography } from '@mui/material';
import { formatShamsiDateTime } from '@/utils';
import type { SupportAlert, SupportAlertSeverity } from '@/services/admin/types';
import AppButton from '../common/AppButton';
import StatusChip, { type StatusKind } from '../StatusChip';

export interface SupportAlertCardProps {
  alert: SupportAlert;
  /** Whether the current admin may act (assign/resolve). Server enforces; this only hides controls. */
  canAct?: boolean;
  onAssignSelf?: (alert: SupportAlert) => void;
  onResolve?: (alert: SupportAlert) => void;
}

/** Alert status → semantic chip kind. */
const STATUS_KIND: Record<SupportAlert['status'], StatusKind> = {
  open: 'pending',
  assigned: 'info',
  resolved: 'verified',
};

/** Severity → the inline-start accent token. */
const SEVERITY_ACCENT: Record<SupportAlertSeverity, string> = {
  high: 'var(--bal-error)',
  medium: 'var(--bal-warning)',
  low: 'var(--bal-divider)',
};

/**
 * A single internal support-alert card for the triage board. Shows the alert type, a severity accent, the
 * linked entity reference, the owner, the raised time (Shamsi), and — for a non-resolved alert — assign/
 * resolve actions (only when `canAct`). **Internal-only**: this card is rendered exclusively inside admin
 * routes and its data never reaches a non-admin surface (phase §5). Enum labels come from the `admin`
 * namespace keyed off the stable code.
 * @component SupportAlertCard
 */
const SupportAlertCard: FunctionComponent<SupportAlertCardProps> = ({ alert, canAct = false, onAssignSelf, onResolve }) => {
  const t = useTranslations('admin');
  const locale = useLocale();

  const entityLabel = alert.bookingId != null
    ? t('alert_link_booking', { id: alert.bookingId })
    : alert.reviewId != null
      ? t('alert_link_review', { id: alert.reviewId })
      : t('alert_link_entity', { type: alert.entityType, id: alert.entityId });

  return (
    <Paper
      elevation={0}
      data-alert-id={alert.id}
      sx={{
        p: 2,
        borderRadius: 2,
        border: '1px solid',
        borderColor: 'divider',
        borderInlineStart: '4px solid',
        borderInlineStartColor: SEVERITY_ACCENT[alert.severity],
      }}
    >
      <Stack direction="row" sx={{ gap: 1, alignItems: 'center', flexWrap: 'wrap', mb: 1 }}>
        <Typography variant="subtitle2" sx={{ fontWeight: 800 }}>
          {t(`atype_${alert.type}`)}
        </Typography>
        <StatusChip status={STATUS_KIND[alert.status]} label={t(`astatus_${alert.status}`)} />
        <Chip size="small" variant="outlined" label={t(`sev_${alert.severity}`)} />
      </Stack>

      <Stack direction="row" sx={{ gap: 2, flexWrap: 'wrap', color: 'text.secondary' }}>
        <Typography variant="body2">{entityLabel}</Typography>
        <Typography variant="body2">
          {alert.ownerUserId != null ? `#${alert.ownerUserId}` : t('alert_unassigned')}
        </Typography>
        <Typography variant="body2">{formatShamsiDateTime(alert.createdAt, locale)}</Typography>
      </Stack>

      {alert.status === 'resolved' && alert.resolutionNote ? (
        <Typography variant="body2" sx={{ mt: 1, fontStyle: 'italic', color: 'text.secondary' }}>
          {alert.resolutionNote}
        </Typography>
      ) : null}

      {canAct && alert.status !== 'resolved' ? (
        <Stack direction="row" sx={{ gap: 1, mt: 1.5, flexWrap: 'wrap' }}>
          {alert.status === 'open' ? (
            <AppButton variant="outlined" color="primary" startIcon="assign" onClick={() => onAssignSelf?.(alert)}>
              {t('alert_assign_me')}
            </AppButton>
          ) : null}
          <AppButton variant="contained" color="primary" startIcon="verified" onClick={() => onResolve?.(alert)}>
            {t('alert_resolve')}
          </AppButton>
        </Stack>
      ) : null}
    </Paper>
  );
};

export default SupportAlertCard;
