'use client';
import { FunctionComponent, KeyboardEvent, useState } from 'react';
import CircularProgress from '@mui/material/CircularProgress';
import IconButton from '@mui/material/IconButton';
import Stack from '@mui/material/Stack';
import TextField from '@mui/material/TextField';
import Typography from '@mui/material/Typography';
import { useTranslations } from 'next-intl';
import { AppIcon } from '@/components/common';
import { usePostMessage } from '@/services/tickets';

export interface MessageComposerProps {
  ticketId: number;
  /** True when the ticket is closed / the user can't post — the input + send are disabled. */
  disabled?: boolean;
}

/** A client-generated id so the optimistic bubble reconciles to the server message (never a double-render). */
function makeClientMessageId(): string {
  if (typeof crypto !== 'undefined' && typeof crypto.randomUUID === 'function') return crypto.randomUUID();
  return `c-${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`;
}

/**
 * The sticky thread composer. Send is **optimistic** (`usePostMessage`): the bubble appears instantly. The
 * draft is **kept until the server confirms** — cleared only in `onSuccess` — so a failure leaves the text in
 * place to retry without retyping (the pending bubble is rolled back by the mutation; §3.5). Submit is
 * disabled while sending; Enter sends, Shift+Enter newlines.
 * @component MessageComposer
 */
const MessageComposer: FunctionComponent<MessageComposerProps> = ({ ticketId, disabled }) => {
  const t = useTranslations('tickets');
  const [draft, setDraft] = useState('');
  const postMessage = usePostMessage(ticketId);
  const sending = postMessage.isPending;

  const submit = () => {
    const body = draft.trim();
    if (!body || sending || disabled) return;
    postMessage.mutate(
      { body, clientMessageId: makeClientMessageId() },
      { onSuccess: () => setDraft('') }, // clear the draft ONLY on server confirm (§3.5)
    );
  };

  const onKeyDown = (event: KeyboardEvent<HTMLDivElement>) => {
    if (event.key === 'Enter' && !event.shiftKey) {
      event.preventDefault();
      submit();
    }
  };

  return (
    <Stack sx={{ gap: 0.5 }}>
      {postMessage.isError ? (
        <Typography variant="caption" sx={{ color: 'var(--bal-error)' }} data-testid="composer-send-failed">
          {t('send_failed')}
        </Typography>
      ) : null}
      <Stack direction="row" sx={{ gap: 1, alignItems: 'flex-end' }}>
        <TextField
          fullWidth
          multiline
          maxRows={4}
          size="small"
          placeholder={t('composer_placeholder')}
          value={draft}
          onChange={(event) => setDraft(event.target.value)}
          onKeyDown={onKeyDown}
          disabled={disabled}
        />
        <IconButton
          onClick={submit}
          disabled={disabled || sending || draft.trim().length === 0}
          aria-label={t('send')}
          sx={{
            bgcolor: 'var(--bal-primary)',
            color: 'var(--bal-primary-contrast)',
            '&:hover': { bgcolor: 'var(--bal-primary-dark)' },
            '&.Mui-disabled': { bgcolor: 'var(--bal-divider)', color: 'var(--bal-text-secondary)' },
          }}
        >
          {sending ? (
            <CircularProgress size={18} sx={{ color: 'var(--bal-primary-contrast)' }} />
          ) : (
            <AppIcon icon="send" size={18} color="var(--bal-primary-contrast)" />
          )}
        </IconButton>
      </Stack>
    </Stack>
  );
};

export default MessageComposer;
