import { useQuery } from '@tanstack/react-query'
import {
  Box,
  Paper,
  Typography,
  Table,
  TableBody,
  TableCell,
  TableContainer,
  TableHead,
  TableRow,
  Chip,
  CircularProgress,
} from '@mui/material'
import { alertsApi, AlertResponse } from '../api/alerts'
import DataFreshness from './DataFreshness'
import { settingsApi } from '../api/settings'
import { formatDate } from '../utils/formatters'

export default function AlertHistory() {
  const { data: alerts, isLoading } = useQuery({
    queryKey: ['alerts'],
    queryFn: () => alertsApi.listAlerts(false),
    refetchInterval: 5000,
  })

  const { data: generalSettings } = useQuery({
    queryKey: ['general-settings'],
    queryFn: () => settingsApi.getGeneralSettings(),
  })

  const triggeredAlerts = alerts?.filter((alert) => alert.triggered) || []

  if (isLoading) {
    return (
      <Box sx={{ display: 'flex', justifyContent: 'center', p: 5 }}>
        <CircularProgress />
      </Box>
    )
  }

  return (
    <Box>
      <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', mb: 2 }}>
        <Typography variant="h6">Alert History</Typography>
        {alerts && alerts.length > 0 && (
          <DataFreshness timestamp={alerts[0]?.updated_at} />
        )}
      </Box>

      {triggeredAlerts.length === 0 ? (
        <Paper sx={{ p: 3 }}>
          <Typography variant="body1" color="text.secondary" align="center">
            No alerts have been triggered yet
          </Typography>
        </Paper>
      ) : (
        <TableContainer component={Paper}>
          <Table>
            <TableHead>
              <TableRow>
                <TableCell>Alert Name</TableCell>
                <TableCell>Type</TableCell>
                <TableCell>Condition</TableCell>
                <TableCell>Triggered At</TableCell>
                <TableCell>Status</TableCell>
              </TableRow>
            </TableHead>
            <TableBody>
              {triggeredAlerts.map((alert: AlertResponse) => (
                <TableRow key={alert.id}>
                  <TableCell>{alert.name}</TableCell>
                  <TableCell>
                    <Chip label={alert.alert_type} size="small" variant="outlined" />
                  </TableCell>
                  <TableCell>
                    {alert.condition?.symbol || 'N/A'}
                    {alert.condition?.price_threshold && ` @ $${alert.condition.price_threshold}`}
                  </TableCell>
                  <TableCell>
                    {formatDate(alert.triggered_at || '', generalSettings)}
                  </TableCell>
                  <TableCell>
                    <Chip
                      label={alert.enabled ? 'Enabled' : 'Disabled'}
                      color={alert.enabled ? 'success' : 'default'}
                      size="small"
                    />
                  </TableCell>
                </TableRow>
              ))}
            </TableBody>
          </Table>
        </TableContainer>
      )}
    </Box>
  )
}

