import { useState } from 'react'
import {
  Box,
  Paper,
  Typography,
  List,
  ListItem,
  ListItemText,
  Chip,
  IconButton,
  Collapse,
  LinearProgress,
} from '@mui/material'
import { ExpandMore, ExpandLess, PlayArrow, Stop } from '@mui/icons-material'

interface Operation {
  id: string
  type: 'backtest' | 'optimization' | 'strategy' | 'order'
  name: string
  status: 'running' | 'queued' | 'completed' | 'failed'
  progress?: number
  startTime?: Date
  estimatedTimeRemaining?: number
}

interface OperationsPanelProps {
  operations?: Operation[]
  onCancel?: (id: string) => void
}

export default function OperationsPanel({ operations = [], onCancel }: OperationsPanelProps) {
  const [expanded, setExpanded] = useState(true)

  const runningOperations = operations.filter((op) => op.status === 'running' || op.status === 'queued')
  const completedOperations = operations.filter((op) => op.status === 'completed' || op.status === 'failed')

  if (operations.length === 0) {
    return null
  }

  return (
    <Paper sx={{ p: 2 }}>
      <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', mb: 1 }}>
        <Typography variant="h6">
          Operations ({runningOperations.length} running)
        </Typography>
        <IconButton size="small" onClick={() => setExpanded(!expanded)}>
          {expanded ? <ExpandLess /> : <ExpandMore />}
        </IconButton>
      </Box>

      <Collapse in={expanded}>
        <List dense>
          {runningOperations.map((op) => (
            <ListItem key={op.id}>
              <ListItemText
                primary={op.name}
                secondary={
                  <Box>
                    <Chip
                      label={op.status}
                      size="small"
                      color={op.status === 'running' ? 'primary' : 'default'}
                      sx={{ mr: 1 }}
                    />
                    {op.progress !== undefined && (
                      <Box sx={{ mt: 1, width: '100%' }}>
                        <LinearProgress variant="determinate" value={op.progress} />
                        <Typography variant="caption" color="text.secondary">
                          {op.progress}%
                        </Typography>
                      </Box>
                    )}
                  </Box>
                }
              />
              {onCancel && op.status === 'running' && (
                <IconButton size="small" onClick={() => onCancel(op.id)}>
                  <Stop fontSize="small" />
                </IconButton>
              )}
            </ListItem>
          ))}
          {runningOperations.length === 0 && (
            <ListItem>
              <ListItemText
                primary="No running operations"
                secondary="All operations are idle"
              />
            </ListItem>
          )}
        </List>
      </Collapse>
    </Paper>
  )
}

