'use client'
import { useState, useRef, useEffect } from 'react'
import { useT } from '@/contexts/LangContext'
import Card from '@mui/material/Card'
import CardContent from '@mui/material/CardContent'
import TextField from '@mui/material/TextField'
import IconButton from '@mui/material/IconButton'
import Button from '@mui/material/Button'
import Chip from '@mui/material/Chip'
import Typography from '@mui/material/Typography'
import Box from '@mui/material/Box'
import CircularProgress from '@mui/material/CircularProgress'
import Tooltip from '@mui/material/Tooltip'
import Divider from '@mui/material/Divider'
import Collapse from '@mui/material/Collapse'
import AgentProgressBar from './AgentProgressBar'
import { TOOL_ACTIVITY_MAP, ACTIVITY_ICONS } from './toolActivityMap'

interface Message {
  role: 'user' | 'assistant'
  content: string
  toolsUsed?: string[]
}

export default function AiPromptBar() {
  const t = useT()
  const QUICK = [t.dashboard.aiQuick1, t.dashboard.aiQuick2, t.dashboard.aiQuick3, t.dashboard.aiQuick4]
  const [message, setMessage]           = useState('')
  const [files, setFiles]               = useState<File[]>([])
  const [loading, setLoading]           = useState(false)
  const [conversation, setConversation] = useState<Message[]>([])
  const [sessionId, setSessionId]       = useState<string | undefined>()
  const fileRef   = useRef<HTMLInputElement>(null)
  const bottomRef = useRef<HTMLDivElement>(null)

  useEffect(() => {
    bottomRef.current?.scrollIntoView({ behavior: 'smooth' })
  }, [conversation])

  const handleSend = async (text?: string) => {
    const msg = (text ?? message).trim()
    if (!msg || loading) return

    setConversation(prev => [...prev, { role: 'user', content: msg }])
    setMessage('')
    setFiles([])
    setLoading(true)

    try {
      const res = await fetch('/api/agent/chat', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ message: msg, sessionId }),
      })
      const data = await res.json()
      setSessionId(data.sessionId)
      setConversation(prev => [...prev, { role: 'assistant', content: data.response, toolsUsed: data.toolsUsed ?? [] }])
    } catch {
      setConversation(prev => [...prev, { role: 'assistant', content: t.dashboard.aiError }])
    } finally {
      setLoading(false)
    }
  }

  const handleFiles = (e: React.ChangeEvent<HTMLInputElement>) => {
    if (e.target.files) setFiles(prev => [...prev, ...Array.from(e.target.files!)])
  }

  const removeFile = (i: number) => setFiles(prev => prev.filter((_, idx) => idx !== i))

  return (
    <Card sx={{ background: 'linear-gradient(135deg, #0D9394 0%, #096B6C 100%)', color: '#fff' }}>
      <CardContent sx={{ p: 4 }}>

        {/* Header row */}
        <Box sx={{ display: 'flex', alignItems: 'center', gap: 1.5, mb: 2 }}>
          <i className='ri-sparkling-2-line' style={{ fontSize: '1.6rem' }} />
          <Typography variant='h5' sx={{ fontWeight: 700, color: '#fff', letterSpacing: '-0.3px' }}>
            {t.dashboard.aiTitle}
          </Typography>
          <Box sx={{ ml: 'auto', display: 'flex', gap: 1, flexWrap: 'wrap' }}>
            {QUICK.map(q => (
              <Chip key={q} label={q} size='small' onClick={() => handleSend(q)}
                sx={{
                  bgcolor: 'rgba(255,255,255,0.25)', color: '#fff',
                  fontSize: '0.72rem', fontWeight: 600, cursor: 'pointer',
                  border: '1px solid rgba(255,255,255,0.4)',
                  '&:hover': { bgcolor: 'rgba(255,255,255,0.35)' },
                }} />
            ))}
          </Box>
          {conversation.length > 0 && (
            <Tooltip title={t.dashboard.aiClearConv}>
              <IconButton size='small' onClick={() => { setConversation([]); setSessionId(undefined) }}
                sx={{ color: 'rgba(255,255,255,0.7)', '&:hover': { color: '#fff' } }}>
                <i className='ri-delete-bin-line' style={{ fontSize: '1rem' }} />
              </IconButton>
            </Tooltip>
          )}
        </Box>

        {/* Conversation thread */}
        <Collapse in={conversation.length > 0}>
          <Box sx={{
            maxHeight: 360,
            overflowY: 'auto',
            mb: 2,
            display: 'flex',
            flexDirection: 'column',
            gap: 1.5,
            pr: 0.5,
            '&::-webkit-scrollbar': { width: 4 },
            '&::-webkit-scrollbar-thumb': { bgcolor: 'rgba(255,255,255,0.3)', borderRadius: 2 },
          }}>
            {conversation.map((m, i) => (
              <Box key={i} sx={{ alignSelf: m.role === 'user' ? 'flex-end' : 'flex-start', maxWidth: '85%' }}>
                {m.role === 'user' ? (
                  <Box sx={{
                    bgcolor: 'rgba(255,255,255,0.25)',
                    border: '1px solid rgba(255,255,255,0.4)',
                    borderRadius: '12px 12px 2px 12px',
                    px: 2, py: 1,
                  }}>
                    <Typography variant='body2' sx={{ color: '#fff', fontWeight: 500 }}>
                      {m.content}
                    </Typography>
                  </Box>
                ) : (
                  <Box>
                    <Box sx={{ bgcolor: 'rgba(255,255,255,0.92)', borderRadius: '2px 12px 12px 12px', px: 2, py: 1.25 }}>
                      <Typography variant='body2' sx={{ color: '#1A2B3C', whiteSpace: 'pre-wrap', lineHeight: 1.65 }}>
                        {m.content}
                      </Typography>
                    </Box>
                    {m.toolsUsed && m.toolsUsed.length > 0 && (
                      <Box sx={{ display: 'flex', flexWrap: 'wrap', gap: 0.75, mt: 1 }}>
                        {[...new Set(m.toolsUsed)].map(tool => {
                          const meta = TOOL_ACTIVITY_MAP[tool]
                          if (!meta) return null
                          return (
                            <Box key={tool} sx={{
                              display: 'flex', alignItems: 'center', gap: 0.5,
                              bgcolor: 'rgba(255,255,255,0.18)',
                              border: '1px solid rgba(255,255,255,0.3)',
                              borderRadius: 4, px: 1, py: 0.25,
                            }}>
                              <i className={ACTIVITY_ICONS[meta.activityType]} style={{ fontSize: '0.65rem', color: 'rgba(255,255,255,0.9)' }} />
                              <Typography variant='caption' sx={{ fontSize: '0.65rem', color: 'rgba(255,255,255,0.9)', lineHeight: 1.4 }}>
                                {meta.action}
                              </Typography>
                            </Box>
                          )
                        })}
                      </Box>
                    )}
                  </Box>
                )}
              </Box>
            ))}
            {loading && (
              <Box sx={{ alignSelf: 'flex-start' }}>
                <Box sx={{ bgcolor: 'rgba(255,255,255,0.92)', borderRadius: '2px 12px 12px 12px', px: 2, py: 1.25 }}>
                  <Box sx={{ display: 'flex', gap: 0.5, alignItems: 'center' }}>
                    {[0, 1, 2].map(d => (
                      <Box key={d} sx={{
                        width: 6, height: 6, borderRadius: '50%', bgcolor: '#096B6C',
                        animation: 'pa-pulse 1.2s ease-in-out infinite',
                        animationDelay: `${d * 0.2}s`,
                        '@keyframes pa-pulse': {
                          '0%, 80%, 100%': { opacity: 0.3 },
                          '40%': { opacity: 1 },
                        },
                      }} />
                    ))}
                  </Box>
                </Box>
              </Box>
            )}
            <div ref={bottomRef} />
          </Box>
          <Divider sx={{ borderColor: 'rgba(255,255,255,0.25)', mb: 2 }} />
        </Collapse>

        {/* Progress bar */}
        {loading && (
          <Box sx={{ mb: 1.5 }}>
            <AgentProgressBar active={loading} light />
          </Box>
        )}

        {/* Attached files */}
        {files.length > 0 && (
          <Box sx={{ display: 'flex', gap: 1, mb: 1.5, flexWrap: 'wrap' }}>
            {files.map((f, i) => (
              <Chip key={i} label={f.name} size='small' onDelete={() => removeFile(i)}
                icon={<i className='ri-file-pdf-line' style={{ fontSize: '0.85rem' }} />}
                sx={{ bgcolor: 'rgba(255,255,255,0.2)', color: '#fff', '& .MuiChip-deleteIcon': { color: 'rgba(255,255,255,0.7)' } }} />
            ))}
          </Box>
        )}

        {/* Input row */}
        <Box sx={{ display: 'flex', gap: 1.5, alignItems: 'flex-end' }}>
          <TextField
            fullWidth multiline maxRows={3} size='small'
            placeholder={conversation.length ? t.dashboard.aiFollowUp : t.dashboard.aiPlaceholder}
            value={message}
            onChange={e => setMessage(e.target.value)}
            onKeyDown={e => { if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); handleSend() } }}
            disabled={loading}
            sx={{
              '& .MuiOutlinedInput-root': {
                bgcolor: '#fff', color: '#1A1F36', borderRadius: 2,
                '& fieldset': { borderColor: 'transparent' },
                '&:hover fieldset': { borderColor: 'transparent' },
                '&.Mui-focused fieldset': { borderColor: '#0D9394', borderWidth: 2 },
              },
              '& .MuiInputBase-input': { color: '#1A1F36', fontWeight: 500 },
              '& .MuiInputBase-input::placeholder': { color: '#6B7280', opacity: 1 },
            }}
          />

          <input ref={fileRef} type='file' accept='.pdf,.doc,.docx,.jpg,.png' multiple hidden onChange={handleFiles} />
          <Tooltip title={t.dashboard.aiAttach}>
            <IconButton onClick={() => fileRef.current?.click()}
              sx={{ bgcolor: 'rgba(255,255,255,0.25)', color: '#fff', border: '1px solid rgba(255,255,255,0.4)', '&:hover': { bgcolor: 'rgba(255,255,255,0.35)' }, p: 1.2 }}>
              <i className='ri-attachment-2' style={{ fontSize: '1.2rem' }} />
            </IconButton>
          </Tooltip>

          <Button variant='contained' onClick={() => handleSend()} disabled={loading || !message.trim()}
            startIcon={loading ? <CircularProgress size={16} sx={{ color: '#096B6C' }} /> : <i className='ri-send-plane-line' />}
            sx={{
              bgcolor: '#fff', color: '#096B6C', fontWeight: 700, fontSize: '0.95rem',
              whiteSpace: 'nowrap', px: 4, py: 1.2, borderRadius: 2,
              boxShadow: '0 2px 8px rgba(0,0,0,0.15)',
              '&:hover': { bgcolor: '#F0FDFD', boxShadow: '0 4px 12px rgba(0,0,0,0.2)' },
              '&.Mui-disabled': { bgcolor: 'rgba(255,255,255,0.5)', color: '#096B6C', opacity: 0.7 },
            }}>
            {loading ? t.dashboard.aiThinking : t.dashboard.aiSend}
          </Button>
        </Box>

      </CardContent>
    </Card>
  )
}
