'use client';
import { FunctionComponent, KeyboardEvent } 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 useMediaQuery from '@mui/material/useMediaQuery';
import { useTranslations } from 'next-intl';
import { AppIcon, AppIconButton } from '@/components/common';
import { TICKETS_ATTACHMENTS_ENABLED } from '@/services/tickets/constants';

export interface MessageComposerProps {
  value: string;
  onChange: (value: string) => void;
  onSubmit: () => void;
  sending: boolean;
  /** True when the ticket is closed / the user can't post — the input + send are disabled. */
  disabled?: boolean;
}

/**
 * The sticky thread composer — a controlled input (the draft lives in `TicketConversationPanel`, which
 * owns the send/retry/discard mutation so a failed bubble and the composer share one source of truth).
 * **Enter semantics are input-modality aware** (§3.3): on a fine pointer (desktop) Enter sends and
 * Shift+Enter inserts a newline; on a coarse pointer (touch) Enter always inserts a newline — the mobile
 * shell has no Shift+Enter, so the explicit send button is the only send path there. The attachment
 * affordance is designed but rendered only behind `TICKETS_ATTACHMENTS_ENABLED` (off — REQ-060 gate).
 * @component MessageComposer
 */
const MessageComposer: FunctionComponent<MessageComposerProps> = ({ value, onChange, onSubmit, sending, disabled }) => {
  const t = useTranslations('tickets');
  const isCoarsePointer = useMediaQuery('(pointer: coarse)');

  const onKeyDown = (event: KeyboardEvent<HTMLDivElement>) => {
    if (isCoarsePointer) return; // touch keyboards: Enter always inserts a newline; the send button sends
    if (event.key === 'Enter' && !event.shiftKey) {
      event.preventDefault();
      onSubmit();
    }
  };

  return (
    <Stack direction="row" sx={{ gap: 1, alignItems: 'flex-end' }}>
      {TICKETS_ATTACHMENTS_ENABLED ? (
        <AppIconButton icon="attachment" title={t('attach_photo')} disabled={disabled || sending} />
      ) : null}
      <TextField
        fullWidth
        multiline
        maxRows={4}
        size="small"
        placeholder={t('composer_placeholder')}
        value={value}
        onChange={(event) => onChange(event.target.value)}
        onKeyDown={onKeyDown}
        disabled={disabled}
      />
      <IconButton
        onClick={onSubmit}
        disabled={disabled || sending || value.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>
  );
};

export default MessageComposer;
