import Box from '@material-hu/mui/Box';
import Stack from '@material-hu/mui/Stack';
import Typography from '@material-hu/mui/Typography';

import { useLokaliseTranslation } from 'src/utils/i18n';

import { formatTimestamp } from '../../utils/formatters';

type TranscriptMessage = {
  role: string;
  message: string;
  time_in_call_secs?: number;
};

type TranscriptCardProps = {
  transcript: TranscriptMessage[];
  employeeName: string;
};

export function TranscriptCard({
  transcript,
  employeeName,
}: TranscriptCardProps) {
  const { t } = useLokaliseTranslation('backoffice_only');

  const filtered = transcript.filter(msg => msg.message?.trim());

  if (filtered.length === 0) return null;

  return (
    <Box
      sx={{
        border: ({ palette }) =>
          `1px solid ${palette.new.border.neutral.default}`,
        borderRadius: 4,
        p: 2.5,
        backgroundColor: ({ palette }) =>
          palette.new.background.layout.tertiary,
      }}
    >
      <Typography
        variant="globalM"
        fontWeight="fontWeightSemiBold"
        sx={{
          color: ({ palette }) => palette.new.text.neutral.default,
          mb: 2,
        }}
      >
        {t('tali.conversation_detail.transcript')}
      </Typography>

      <Box sx={{ maxHeight: 600, overflowY: 'auto' }}>
        {filtered.map((msg, idx) => {
          const speakerName = msg.role === 'agent' ? 'Oli' : employeeName;

          return (
            <Stack
              key={idx}
              sx={{
                flexDirection: 'row',
                gap: 2,
                py: 1,
                borderBottom:
                  idx < filtered.length - 1
                    ? ({ palette }) =>
                        `1px solid ${palette.new.border.neutral.divider}`
                    : 'none',
              }}
            >
              <Stack sx={{ width: 140, flexShrink: 0 }}>
                <Typography
                  variant="globalXS"
                  fontWeight="fontWeightSemiBold"
                  sx={{
                    color: ({ palette }) => palette.new.text.neutral.default,
                  }}
                >
                  {speakerName}
                </Typography>
                <Typography
                  variant="globalXXS"
                  sx={{
                    color: ({ palette }) => palette.new.text.neutral.lighter,
                  }}
                >
                  {formatTimestamp(msg.time_in_call_secs)}
                </Typography>
              </Stack>

              <Typography
                variant="globalXS"
                sx={{
                  fontStyle: 'italic',
                  lineHeight: 1.6,
                  color: ({ palette }) => palette.new.text.neutral.lighter,
                  flex: 1,
                }}
              >
                {msg.message}
              </Typography>
            </Stack>
          );
        })}
      </Box>
    </Box>
  );
}
