'use client'

import { useState, useRef } from 'react'
import Card from '@mui/material/Card'
import CardHeader from '@mui/material/CardHeader'
import CardContent from '@mui/material/CardContent'
import TextField from '@mui/material/TextField'
import InputAdornment from '@mui/material/InputAdornment'
import IconButton from '@mui/material/IconButton'
import Typography from '@mui/material/Typography'
import Divider from '@mui/material/Divider'
import Box from '@mui/material/Box'
import { styled } from '@mui/material/styles'
import MuiTimeline from '@mui/lab/Timeline'
import TimelineItem from '@mui/lab/TimelineItem'
import TimelineSeparator from '@mui/lab/TimelineSeparator'
import TimelineConnector from '@mui/lab/TimelineConnector'
import TimelineContent from '@mui/lab/TimelineContent'
import TimelineDot from '@mui/lab/TimelineDot'
import type { TimelineProps } from '@mui/lab/Timeline'
import type { AgentActivity } from './types'
import { ACTIVITY_ICONS } from './toolActivityMap'
import AgentProgressBar from './AgentProgressBar'

const Timeline = styled(MuiTimeline)<TimelineProps>({
  paddingLeft: 0,
  paddingRight: 0,
  '& .MuiTimelineItem-root': {
    width: '100%',
    '&:before': { display: 'none' },
  },
})

const AiAssistantCard = ({
  recentActivity,
  onSend,
}: {
  recentActivity: AgentActivity[]
  onSend?: (message: string) => void
}) => {
  const [message, setMessage] = useState('')
  const [loading, setLoading] = useState(false)
  const inputRef = useRef<HTMLInputElement>(null)

  const handleSend = async () => {
    if (!message.trim() || loading) return
    setLoading(true)
    await onSend?.(message.trim())
    setMessage('')
    setLoading(false)
    inputRef.current?.focus()
  }

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

  return (
    <Card className='bs-full flex flex-col'>
      <CardHeader
        title='AI Assistant'
        titleTypographyProps={{ variant: 'h6' }}
        avatar={<i className='ri-sparkling-2-line text-primary-main text-xl' />}
        subheader='Agent is ready'
        subheaderTypographyProps={{ variant: 'caption', color: 'success.main' }}
      />

      <CardContent className='flex flex-col gap-4 flex-1 pt-0'>
        {/* Recent activity */}
        <div>
          <Typography variant='overline' color='text.secondary' className='tracking-wider'>
            Recent Activity
          </Typography>
          <Timeline sx={{ mt: 1, mb: 0 }}>
            {recentActivity.slice(0, 4).map((activity, i) => (
              <TimelineItem key={activity.id}>
                <TimelineSeparator>
                  <TimelineDot color={activity.color} sx={{ my: 0.5, p: 0.5 }}>
                    <i className={ACTIVITY_ICONS[activity.activityType ?? 'document'] ?? ''} style={{ fontSize: '0.7rem' }} />
                  </TimelineDot>
                  {i < Math.min(recentActivity.length, 4) - 1 && <TimelineConnector />}
                </TimelineSeparator>
                <TimelineContent sx={{ py: 0, px: 2, pb: 1.5 }}>
                  <div className='flex items-start justify-between gap-2'>
                    <div>
                      <Typography variant='caption' className='font-medium' color='text.primary'>
                        {activity.action}
                      </Typography>
                      {activity.matter && (
                        <Typography variant='caption' color='text.secondary' display='block'>
                          {activity.matter}
                        </Typography>
                      )}
                    </div>
                    <Typography variant='caption' color='text.disabled' className='whitespace-nowrap'>
                      {activity.timestamp}
                    </Typography>
                  </div>
                </TimelineContent>
              </TimelineItem>
            ))}
          </Timeline>
        </div>

        <Divider />

        {/* Prompt input */}
        <Box className='flex flex-col gap-2 mt-auto'>
          <AgentProgressBar active={loading} />
          {!loading && (
            <Typography variant='caption' color='text.secondary'>
              Ask anything — hearings, statutes, clients, drafts
            </Typography>
          )}
          <TextField
            inputRef={inputRef}
            fullWidth
            multiline
            maxRows={3}
            size='small'
            placeholder="e.g. Summarise the Smith matter before this morning's hearing..."
            value={message}
            onChange={e => setMessage(e.target.value)}
            onKeyDown={handleKeyDown}
            disabled={loading}
            InputProps={{
              endAdornment: (
                <InputAdornment position='end'>
                  <IconButton
                    size='small'
                    color='primary'
                    onClick={handleSend}
                    disabled={!message.trim() || loading}
                  >
                    <i className='ri-send-plane-line' />
                  </IconButton>
                </InputAdornment>
              ),
            }}
          />
        </Box>
      </CardContent>
    </Card>
  )
}

export default AiAssistantCard
