'use client';
import { FunctionComponent } from 'react';
import { useLocale, useTranslations } from 'next-intl';
import { Box, Chip, Stack, Typography } from '@mui/material';
import { formatShamsiDateTime } from '@/utils';
import type { AdminTicketMessage } from '@/services/tickets/types';

export interface AdminMessageBubbleProps {
  message: AdminTicketMessage;
  /** Already-translated author-role label. */
  authorLabel: string;
}

/**
 * One message in the **admin** ticket thread. Unlike the user-side `MessageBubble`, this renders
 * `isInternal` notes **distinctly** (dashed warning-tinted panel + an "Internal note" badge) so staff can
 * never confuse an internal note with a participant-visible reply. Internal notes exist only on the admin
 * surface — the user-app types never carry `isInternal` (phase §5). Aligns start/end by `isMine`
 * (RTL-safe via `alignSelf`); a pending/failed optimistic send is dimmed/marked.
 * @component AdminMessageBubble
 */
const AdminMessageBubble: FunctionComponent<AdminMessageBubbleProps> = ({ message, authorLabel }) => {
  const t = useTranslations('admin');
  const locale = useLocale();

  const internal = message.isInternal;
  const mine = message.isMine;

  return (
    <Box
      data-internal={internal}
      sx={{
        alignSelf: mine ? 'flex-end' : 'flex-start',
        maxWidth: { xs: '90%', sm: '75%' },
        opacity: message.sendStatus === 'sending' ? 0.6 : 1,
      }}
    >
      <Box
        sx={{
          p: 1.5,
          borderRadius: 2,
          border: internal ? '1px dashed' : '1px solid',
          borderColor: internal ? 'var(--bal-warning)' : 'divider',
          bgcolor: internal ? 'var(--bal-secondary-soft)' : mine ? 'var(--bal-primary-soft)' : 'background.paper',
        }}
      >
        <Stack direction="row" sx={{ gap: 1, alignItems: 'center', mb: 0.5, flexWrap: 'wrap' }}>
          <Typography variant="caption" sx={{ fontWeight: 700, color: 'text.secondary' }}>
            {authorLabel}
          </Typography>
          {internal ? (
            <Chip
              size="small"
              label={t('ticket_internal_badge')}
              sx={{ height: 20, bgcolor: 'var(--bal-warning)', color: 'var(--bal-warning-contrast)', fontWeight: 700 }}
            />
          ) : null}
        </Stack>
        <Typography variant="body2" sx={{ whiteSpace: 'pre-wrap', wordBreak: 'break-word' }}>
          {message.body}
        </Typography>
        <Typography variant="caption" sx={{ color: 'text.secondary', display: 'block', mt: 0.5 }}>
          {formatShamsiDateTime(message.createdAt, locale)}
          {message.sendStatus === 'failed' ? ` · ${t('error_generic')}` : ''}
        </Typography>
      </Box>
    </Box>
  );
};

export default AdminMessageBubble;
