import { useState } from 'react'
import {
  Box,
  Button,
  FormControl,
  FormHelperText,
  IconButton,
  InputBase,
  Menu,
  MenuItem,
  Typography,
} from '@mui/material'
import {
  ArrowUpwardOutlined,
  StopCircleOutlined,
  KeyboardArrowDown,
} from '@mui/icons-material'
import type { ChatFooterProps } from '../types'
import { styles } from './styles'

const DEFAULT_CAPTION =
  'Responses are AI-generated. Please verify key information.'

export function ChatFooter({
  value,
  onChange,
  onSend,
  onStop,
  isGenerating = false,
  disabled = false,
  placeholder = 'Type a message...',
  labels = {},
  caption = DEFAULT_CAPTION,
  models,
  selectedModel,
  onModelChange,
  startToolbarSlot,
  endToolbarSlot,
  sx,
}: ChatFooterProps) {
  const [modelAnchor, setModelAnchor] = useState<HTMLElement | null>(null)
  const canSend = value.trim() && !disabled && !isGenerating
  // Only worth showing when there's an actual choice — a single option is dead UI.
  const showModelSelector = (models?.length ?? 0) > 1
  const modelLabel = labels.model ?? 'Select model'
  // Visible trigger text: the matched option's label, the raw value as a
  // fallback, or the placeholder when nothing is selected yet.
  const selectedLabel =
    models?.find((m) => m.value === selectedModel)?.label ??
    (selectedModel && selectedModel.length > 0 ? selectedModel : modelLabel)

  // The slots row (start slot + model selector + end slot) renders under the input
  // only when there's something to show; otherwise the grid is just input | send.
  const hasSlots =
    showModelSelector || Boolean(startToolbarSlot) || Boolean(endToolbarSlot)

  const handleKeyDown = (e: React.KeyboardEvent) => {
    if (e.key === 'Enter' && !e.shiftKey) {
      e.preventDefault()
      if (canSend) {
        onSend()
      }
    }
  }

  const sendButton =
    isGenerating && onStop ? (
      <IconButton
        size='small'
        onClick={onStop}
        disabled={disabled}
        aria-label={labels.stop ?? 'Stop'}
      >
        <StopCircleOutlined />
      </IconButton>
    ) : (
      <IconButton
        size='small'
        variant='contained'
        color='primary'
        onClick={onSend}
        disabled={!canSend}
        aria-label={labels.send ?? 'Send'}
      >
        <ArrowUpwardOutlined />
      </IconButton>
    )

  return (
    <FormControl fullWidth sx={{ ...styles.footerWrapper, ...sx }}>
      {/* Two grid areas: [input + slots] | [send button, aligned to the end]. */}
      <Box sx={styles.footerBox}>
        <Box sx={styles.footerMain}>
          <InputBase
            multiline
            minRows={1}
            maxRows={8}
            value={value}
            onChange={(e) => onChange(e.target.value)}
            onKeyDown={handleKeyDown}
            placeholder={placeholder}
            disabled={disabled || isGenerating}
            sx={styles.footerInput}
          />
          {hasSlots && (
            <Box sx={styles.footerSlots}>
              {startToolbarSlot}
              {showModelSelector && (
                <>
                  <Button
                    size='small'
                    variant='text'
                    color='inherit'
                    disabled={disabled || isGenerating}
                    onClick={(e) => setModelAnchor(e.currentTarget)}
                    aria-label={modelLabel}
                    aria-haspopup='menu'
                    aria-expanded={modelAnchor ? 'true' : undefined}
                    endIcon={<KeyboardArrowDown />}
                    sx={styles.modelSelector}
                  >
                    <Typography
                      variant='caption'
                      component='span'
                      color='inherit'
                      sx={styles.modelSelectorLabel}
                    >
                      {selectedLabel}
                    </Typography>
                  </Button>
                  <Menu
                    anchorEl={modelAnchor}
                    open={Boolean(modelAnchor)}
                    onClose={() => setModelAnchor(null)}
                    variant='menu'
                    elevation={8}
                    anchorOrigin={{ vertical: 'top', horizontal: 'left' }}
                    transformOrigin={{ vertical: 'bottom', horizontal: 'left' }}
                  >
                    {models?.map((m) => (
                      <MenuItem
                        key={m.value}
                        selected={m.value === selectedModel}
                        onClick={() => {
                          onModelChange?.(m.value)
                          setModelAnchor(null)
                        }}
                      >
                        {m.label}
                      </MenuItem>
                    ))}
                  </Menu>
                </>
              )}
              {endToolbarSlot}
            </Box>
          )}
        </Box>
        <Box sx={styles.footerSend}>{sendButton}</Box>
      </Box>
      {caption ? (
        <FormHelperText sx={styles.footerCaption}>{caption}</FormHelperText>
      ) : null}
    </FormControl>
  )
}
