'use client';
import { FunctionComponent } from 'react';
import Skeleton from '@mui/material/Skeleton';
import Stack from '@mui/material/Stack';
import Typography from '@mui/material/Typography';
import { useLocale, useTranslations } from 'next-intl';
import { useTicketThread } from '@/services/tickets';
import { formatShamsiDateTime } from '@/utils';
import MessageBubble from './MessageBubble';
import { authorLabelKey } from './authorLabel';

export interface TicketMessageListProps {
  ticketId: number;
}

/**
 * The message list of a thread — a `select` over the ticket detail (`useTicketThread`), so it re-renders on a
 * new (optimistic) message without re-rendering the thread header. Empty ("no messages yet — start
 * coordinating"), skeleton, and populated states. Each bubble's author label + Shamsi time are resolved here;
 * the bubbles never render an internal note (there are none in the user view — §5).
 * @component TicketMessageList
 */
const TicketMessageList: FunctionComponent<TicketMessageListProps> = ({ ticketId }) => {
  const t = useTranslations('tickets');
  const locale = useLocale();
  const { data: messages, isLoading } = useTicketThread(ticketId);

  if (isLoading) {
    return (
      <Stack sx={{ gap: 1 }}>
        {[0, 1, 2].map((i) => (
          <Skeleton key={i} variant="rounded" height={56} sx={{ width: '70%', alignSelf: i % 2 ? 'flex-end' : 'flex-start' }} />
        ))}
      </Stack>
    );
  }

  if (!messages || messages.length === 0) {
    return (
      <Stack sx={{ gap: 0.5, alignItems: 'center', py: 4 }}>
        <Typography variant="subtitle2" sx={{ fontWeight: 700 }}>
          {t('thread_empty_title')}
        </Typography>
        <Typography variant="body2" sx={{ color: 'var(--bal-text-secondary)' }}>
          {t('thread_empty_body')}
        </Typography>
      </Stack>
    );
  }

  return (
    <Stack sx={{ gap: 1 }}>
      {messages.map((message) => (
        <MessageBubble
          key={message.clientMessageId ?? String(message.id)}
          message={message}
          authorLabel={t(authorLabelKey(message.authorRole))}
          timeLabel={formatShamsiDateTime(message.createdAt, locale)}
          sendingLabel={t('sending')}
        />
      ))}
    </Stack>
  );
};

export default TicketMessageList;
