'use client'

import { useState, useMemo } from 'react'
import Box from '@mui/material/Box'
import Typography from '@mui/material/Typography'
import Card from '@mui/material/Card'
import CardContent from '@mui/material/CardContent'
import TextField from '@mui/material/TextField'
import InputAdornment from '@mui/material/InputAdornment'
import Chip from '@mui/material/Chip'
import Table from '@mui/material/Table'
import TableBody from '@mui/material/TableBody'
import TableCell from '@mui/material/TableCell'
import TableContainer from '@mui/material/TableContainer'
import TableHead from '@mui/material/TableHead'
import TableRow from '@mui/material/TableRow'
import TableSortLabel from '@mui/material/TableSortLabel'
import type { AgentActivity } from '@/views/dashboard/types'

// Mock data — replace with API call when backend is ready
const today = new Date()
const ts = (minsAgo: number) => {
  const d = new Date(today.getTime() - minsAgo * 60000)
  return d.toLocaleString('en-GB', { day: 'numeric', month: 'short', hour: '2-digit', minute: '2-digit' })
}

const ALL_ACTIVITY: (AgentActivity & { timestamp: string; ts: number })[] = [
  { id: 'ac1',  agent: 'document_classifier', action: 'Doc classified: Jones visa extension',    matter: 'Visa — Jones',      timestamp: ts(2),    ts: 2,    color: 'primary' },
  { id: 'ac2',  agent: 'billing_agent',        action: 'Quote sent: ฿45,000',                    matter: 'BOI — Nexus Corp',  timestamp: ts(60),   ts: 60,   color: 'success' },
  { id: 'ac3',  agent: 'comms_agent',          action: 'Hearing reminder sent via LINE',          matter: 'Smith v. Nexus',    timestamp: ts(180),  ts: 180,  color: 'info' },
  { id: 'ac4',  agent: 'rag_agent',            action: 'BOI Act s.12 lookup',                    matter: 'BOI — Nexus Corp',  timestamp: ts(240),  ts: 240,  color: 'warning' },
  { id: 'ac5',  agent: 'case_analyst',         action: 'Conflict check: Rivera (new)',            matter: undefined,           timestamp: ts(300),  ts: 300,  color: 'secondary' },
  { id: 'ac6',  agent: 'document_classifier', action: 'Chanote deed classified: property title', matter: 'Land — Siriwan',    timestamp: ts(360),  ts: 360,  color: 'primary' },
  { id: 'ac7',  agent: 'billing_agent',        action: 'Invoice generated: ฿12,000',             matter: 'Visa — Tanaka K.',  timestamp: ts(480),  ts: 480,  color: 'success' },
  { id: 'ac8',  agent: 'comms_agent',          action: 'Email drafted: opposing counsel reply',  matter: 'Kim — Employment',  timestamp: ts(600),  ts: 600,  color: 'info' },
  { id: 'ac9',  agent: 'rag_agent',            action: 'Immigration Act s.37 lookup',            matter: 'Visa — Jones',      timestamp: ts(720),  ts: 720,  color: 'warning' },
  { id: 'ac10', agent: 'case_analyst',         action: 'Case strategy draft: Rivera',            matter: 'Rivera Visa',       timestamp: ts(900),  ts: 900,  color: 'secondary' },
  { id: 'ac11', agent: 'document_classifier', action: 'Employment contract classified',          matter: 'Kim — Employment',  timestamp: ts(1080), ts: 1080, color: 'primary' },
  { id: 'ac12', agent: 'billing_agent',        action: 'Retainer alert triggered: Chang Corp',  matter: 'BOI — Nexus Corp',  timestamp: ts(1440), ts: 1440, color: 'success' },
]

const AGENT_LABELS: Record<string, string> = {
  prompt_analyst:      'Prompt Analyst',
  document_classifier: 'Doc Classifier',
  case_analyst:        'Case Analyst',
  billing_agent:       'Billing Agent',
  comms_agent:         'Comms Agent',
  rag_agent:           'RAG Agent',
}

const AGENT_ICONS: Record<string, string> = {
  prompt_analyst:      'ri-user-voice-line',
  document_classifier: 'ri-file-search-line',
  case_analyst:        'ri-mind-map',
  billing_agent:       'ri-money-dollar-circle-line',
  comms_agent:         'ri-send-plane-line',
  rag_agent:           'ri-book-open-line',
}

const AGENT_TYPES = ['all', ...Object.keys(AGENT_LABELS)] as const

type SortField = 'timestamp' | 'agent' | 'action' | 'matter'
type SortDir = 'asc' | 'desc'

export default function AgentActivityView() {
  const [search, setSearch] = useState('')
  const [agentFilter, setAgentFilter] = useState<string>('all')
  const [sortField, setSortField] = useState<SortField>('timestamp')
  const [sortDir, setSortDir] = useState<SortDir>('asc')

  const handleSort = (field: SortField) => {
    if (sortField === field) {
      setSortDir(d => d === 'asc' ? 'desc' : 'asc')
    } else {
      setSortField(field)
      setSortDir('asc')
    }
  }

  const rows = useMemo(() => {
    let data = [...ALL_ACTIVITY]

    if (agentFilter !== 'all') data = data.filter(r => r.agent === agentFilter)

    if (search.trim()) {
      const q = search.toLowerCase()
      data = data.filter(r =>
        r.action.toLowerCase().includes(q) ||
        (r.matter ?? '').toLowerCase().includes(q) ||
        (AGENT_LABELS[r.agent ?? ''] ?? '').toLowerCase().includes(q)
      )
    }

    data.sort((a, b) => {
      let cmp = 0
      if (sortField === 'timestamp') cmp = a.ts - b.ts
      else if (sortField === 'agent') cmp = (a.agent ?? '').localeCompare(b.agent ?? '')
      else if (sortField === 'action') cmp = a.action.localeCompare(b.action)
      else if (sortField === 'matter') cmp = (a.matter ?? '').localeCompare(b.matter ?? '')
      return sortDir === 'asc' ? cmp : -cmp
    })

    return data
  }, [search, agentFilter, sortField, sortDir])

  const col = (field: SortField, label: string) => (
    <TableSortLabel
      active={sortField === field}
      direction={sortField === field ? sortDir : 'asc'}
      onClick={() => handleSort(field)}
    >
      {label}
    </TableSortLabel>
  )

  return (
    <Box sx={{ display: 'flex', flexDirection: 'column', gap: 2 }}>
      <Box>
        <Typography variant='h4' sx={{ fontWeight: 600 }}>Agent Activity</Typography>
        <Typography variant='body2' color='text.secondary'>Live log of all AI agent actions across matters</Typography>
      </Box>

      <Card>
        <CardContent sx={{ pb: '16px !important' }}>
          {/* Filters */}
          <Box sx={{ display: 'flex', gap: 2, mb: 2, flexWrap: 'wrap', alignItems: 'center' }}>
            <TextField
              size='small'
              placeholder='Search actions, matters…'
              value={search}
              onChange={e => setSearch(e.target.value)}
              sx={{ minWidth: 260 }}
              InputProps={{
                startAdornment: (
                  <InputAdornment position='start'>
                    <i className='ri-search-line' style={{ fontSize: '1rem', color: '#9CA3AF' }} />
                  </InputAdornment>
                ),
              }}
            />
            <Box sx={{ display: 'flex', gap: 0.75, flexWrap: 'wrap' }}>
              {AGENT_TYPES.map(a => (
                <Chip
                  key={a}
                  label={a === 'all' ? 'All Agents' : AGENT_LABELS[a as string] ?? a}
                  size='small'
                  onClick={() => setAgentFilter(a)}
                  variant={agentFilter === a ? 'filled' : 'outlined'}
                  color={agentFilter === a ? 'primary' : 'default'}
                  sx={{ cursor: 'pointer' }}
                />
              ))}
            </Box>
          </Box>

          {/* Table */}
          <TableContainer>
            <Table size='small'>
              <TableHead>
                <TableRow>
                  <TableCell sx={{ fontWeight: 600, width: 160 }}>{col('timestamp', 'Time')}</TableCell>
                  <TableCell sx={{ fontWeight: 600, width: 160 }}>{col('agent', 'Agent')}</TableCell>
                  <TableCell sx={{ fontWeight: 600 }}>{col('action', 'Action')}</TableCell>
                  <TableCell sx={{ fontWeight: 600, width: 180 }}>{col('matter', 'Matter')}</TableCell>
                </TableRow>
              </TableHead>
              <TableBody>
                {rows.length === 0 ? (
                  <TableRow>
                    <TableCell colSpan={4} align='center' sx={{ py: 4, color: 'text.disabled' }}>
                      No activity matches your filters
                    </TableCell>
                  </TableRow>
                ) : rows.map(row => (
                  <TableRow key={row.id} hover sx={{ cursor: 'default' }}>
                    <TableCell>
                      <Typography variant='caption' color='text.secondary'>{row.timestamp}</Typography>
                    </TableCell>
                    <TableCell>
                      <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
                        <i className={AGENT_ICONS[row.agent ?? ''] ?? ''} style={{ fontSize: '0.9rem', color: `var(--mui-palette-${row.color}-main)` }} />
                        <Typography variant='body2'>{AGENT_LABELS[row.agent ?? ''] ?? row.agent ?? ''}</Typography>
                      </Box>
                    </TableCell>
                    <TableCell>
                      <Typography variant='body2'>{row.action}</Typography>
                    </TableCell>
                    <TableCell>
                      <Typography variant='body2' color='text.secondary'>{row.matter ?? '—'}</Typography>
                    </TableCell>
                  </TableRow>
                ))}
              </TableBody>
            </Table>
          </TableContainer>

          <Typography variant='caption' color='text.disabled' sx={{ display: 'block', mt: 1.5 }}>
            {rows.length} of {ALL_ACTIVITY.length} events · Live feed — auto-refreshes when connected to backend
          </Typography>
        </CardContent>
      </Card>
    </Box>
  )
}
