import { useState, useEffect } from 'react';
import {
  Box,
  Card,
  CardContent,
  Typography,
  Button,
  Table,
  TableBody,
  TableCell,
  TableContainer,
  TableHead,
  TableRow,
  Chip,
  Dialog,
  DialogTitle,
  DialogContent,
  DialogActions,
  Grid,
  TextField,
} from '@mui/material';
import {
  Warning as WarningIcon,
  Refresh as RefreshIcon,
  Add as AddIcon,
} from '@mui/icons-material';
import { useI18n } from '../contexts/I18nContext';
import { apiJson, apiFetch } from '../lib/api';
import { logger } from '../lib/logger';

interface AlertThreshold {
  id: number;
  name: string;
  subscription_id?: number;
  metric_type: string;
  threshold_value: number;
  comparison_operator: string;
  action: string;
  notification_channels: string[];
  is_active: boolean;
  last_triggered?: string;
}

interface AlertHistoryItem {
  id: number;
  threshold_id: number;
  threshold_name: string;
  actual_value: number;
  triggered_at: string;
  action_taken?: string;
  notification_sent: boolean;
}

const metricLabels: Record<string, string> = {
  cpu: 'CPU',
  ram: 'Memory (RAM)',
  disk: 'Disk Storage',
  bandwidth: 'Bandwidth',
  database: 'Database',
  requests: 'Requests',
  emails: 'Emails',
};

const operatorLabels: Record<string, string> = {
  '>': 'Greater than',
  '>=': 'Greater or equal',
  '<': 'Less than',
  '<=': 'Less or equal',
  '=': 'Equal to',
};

const unitLabels: Record<string, string> = {
  cpu: '%',
  ram: 'GB',
  disk: 'GB',
  bandwidth: 'GB',
  database: 'MB',
  requests: 'count',
  emails: 'count',
};

const AlertsPage: React.FC = () => {
  const { t } = useI18n();
  const [thresholds, setThresholds] = useState<AlertThreshold[]>([]);
  const [history, setHistory] = useState<AlertHistoryItem[]>([]);
  const [, setLoading] = useState(false);
  const [dialogOpen, setDialogOpen] = useState(false);
  const [editingThreshold, setEditingThreshold] = useState<AlertThreshold | null>(null);

  useEffect(() => {
    fetchThresholds();
    fetchHistory();
  }, []);

  const fetchThresholds = async () => {
    setLoading(true);
    try {
      const data = await apiJson<AlertThreshold[]>('/alerts/thresholds');
      setThresholds(data);
    } catch (error) {
      logger.error('Failed to fetch thresholds:', error);
    } finally {
      setLoading(false);
    }
  };

  const fetchHistory = async () => {
    try {
      const data = await apiJson<AlertHistoryItem[]>('/alerts/history');
      setHistory(data);
    } catch (error) {
      logger.error('Failed to fetch history:', error);
    }
  };

  const handleOpenDialog = (threshold?: AlertThreshold) => {
    if (threshold) {
      setEditingThreshold(threshold);
    } else {
      setEditingThreshold({
        id: 0,
        name: '',
        metric_type: 'cpu',
        threshold_value: 80,
        comparison_operator: '>',
        action: 'notify',
        notification_channels: ['email'],
        is_active: true,
      });
    }
    setDialogOpen(true);
  };

  const handleCloseDialog = () => {
    setDialogOpen(false);
    setEditingThreshold(null);
  };

  const handleSave = async () => {
    try {
      if (!editingThreshold) return;
      if (editingThreshold.id === 0) {
        await apiFetch('/alerts/thresholds', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify(editingThreshold),
        });
      } else {
        await apiFetch(`/alerts/thresholds/${editingThreshold.id}`, {
          method: 'PUT',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify(editingThreshold),
        });
      }
      fetchThresholds();
      handleCloseDialog();
    } catch (error) {
      logger.error('Failed to save threshold:', error);
    }
  };

  const handleDelete = async (id: number) => {
    try {
      await apiFetch(`/alerts/thresholds/${id}`, { method: 'DELETE' });
      fetchThresholds();
    } catch (error) {
      logger.error('Failed to delete threshold:', error);
    }
  };

  return (
    <Box sx={{ flexGrow: 1 }}>
      <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', mb: 3 }}>
        <Typography variant="h4">{t('alerts.title')}</Typography>
        <Box sx={{ display: 'flex', gap: 1 }}>
          <Button 
            variant="contained" 
            startIcon={<AddIcon />}
            onClick={() => handleOpenDialog()}
          >
            {t('alerts.addThreshold')}
          </Button>
          <Button 
            variant="contained" 
            startIcon={<RefreshIcon />}
            onClick={fetchThresholds}
          >
            {t('alerts.refresh')}
          </Button>
        </Box>
      </Box>

      <Grid container spacing={3}>
        <Grid item xs={12} md={8}>
          <Card>
            <CardContent>
              <Typography variant="h6" gutterBottom>{t('alerts.thresholds')}</Typography>
              <TableContainer>
                <Table>
                  <TableHead>
                    <TableRow>
                      <TableCell>{t('alerts.colName')}</TableCell>
                      <TableCell>{t('alerts.colMetric')}</TableCell>
                      <TableCell>{t('alerts.colThreshold')}</TableCell>
                      <TableCell>{t('alerts.colAction')}</TableCell>
                      <TableCell>{t('alerts.colStatus')}</TableCell>
                      <TableCell>{t('alerts.colLastTriggered')}</TableCell>
                      <TableCell>{t('alerts.colActions')}</TableCell>
                    </TableRow>
                  </TableHead>
                  <TableBody>
                    {thresholds.length === 0 ? (
                      <TableRow>
                        <TableCell colSpan={7} align="center">
                          <Typography variant="body2" color="textSecondary">
                            {t('alerts.noThresholds')}
                          </Typography>
                        </TableCell>
                      </TableRow>
                    ) : (
                      thresholds.map((threshold) => (
                        <TableRow key={threshold.id}>
                          <TableCell>{threshold.name}</TableCell>
                          <TableCell>
                            <Chip label={metricLabels[threshold.metric_type] || threshold.metric_type} size="small" color="primary" />
                          </TableCell>
                          <TableCell>
                            <Typography variant="body2">
                              {threshold.comparison_operator} {threshold.threshold_value} {unitLabels[threshold.metric_type]}
                            </Typography>
                          </TableCell>
                          <TableCell>{threshold.action}</TableCell>
                          <TableCell>
                            <Chip 
                              label={threshold.is_active ? t('alerts.active') : t('alerts.inactive')} 
                              color={threshold.is_active ? 'success' : 'default'} 
                              size="small"
                            />
                          </TableCell>
                          <TableCell>
                            {threshold.last_triggered 
                              ? new Date(threshold.last_triggered).toLocaleDateString() 
                              : '-'}
                          </TableCell>
                          <TableCell>
                            <Box sx={{ display: 'flex', gap: 0.5 }}>
                              <Button
                                size="small"
                                variant="outlined"
                                onClick={() => handleOpenDialog(threshold)}
                              >
                                {t('common.edit')}
                              </Button>
                              <Button
                                size="small"
                                variant="outlined"
                                color="error"
                                onClick={() => handleDelete(threshold.id)}
                              >
                                {t('common.delete')}
                              </Button>
                            </Box>
                          </TableCell>
                        </TableRow>
                      ))
                    )}
                  </TableBody>
                </Table>
              </TableContainer>
            </CardContent>
          </Card>
        </Grid>

        <Grid item xs={12} md={4}>
          <Card>
            <CardContent>
              <Typography variant="h6" gutterBottom>{t('alerts.recentAlerts')}</Typography>
              <Box sx={{ height: 400, overflow: 'auto' }}>
                {history.length === 0 ? (
                  <Typography variant="body2" color="textSecondary">
                    {t('alerts.noRecentAlerts')}
                  </Typography>
                ) : (
                  history.slice(0, 20).map((alert) => (
                    <Box key={alert.id} sx={{ mb: 2, p: 2, bgcolor: '#f5f5f5', borderRadius: 1 }}>
                      <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
                        <WarningIcon color="warning" fontSize="small" />
                        <Typography variant="body2" fontWeight={600} noWrap>
                          {alert.threshold_name}
                        </Typography>
                      </Box>
                      <Typography variant="caption" color="textSecondary">
                        {t('alerts.value')}: {alert.actual_value} ({t('alerts.triggeredAt')} {new Date(alert.triggered_at).toLocaleString()})
                      </Typography>
                      {alert.action_taken && (
                        <Typography variant="caption" color="textPrimary" sx={{ display: 'block', mt: 0.5 }}>
                          {t('alerts.action')}: {alert.action_taken}
                        </Typography>
                      )}
                    </Box>
                  ))
                )}
              </Box>
            </CardContent>
          </Card>
        </Grid>
      </Grid>

      <Dialog open={dialogOpen} onClose={handleCloseDialog} maxWidth="sm" fullWidth>
        <DialogTitle>
          {editingThreshold?.id === 0 ? t('alerts.addThresholdTitle') : t('alerts.editThresholdTitle')}
        </DialogTitle>
        <DialogContent>
          <Box component="form" sx={{ mt: 2 }}>
            <TextField
              fullWidth
              label={t('alerts.name')}
              value={editingThreshold?.name || ''}
              onChange={(e) => setEditingThreshold({ ...editingThreshold!, name: e.target.value })}
              margin="normal"
            />
            
            <TextField
              fullWidth
              select
              label={t('alerts.metricType')}
              value={editingThreshold?.metric_type || 'cpu'}
              onChange={(e) => setEditingThreshold({ ...editingThreshold!, metric_type: e.target.value })}
              margin="normal"
            >
              {Object.keys(metricLabels).map((key) => (
                <option key={key} value={key}>{metricLabels[key]}</option>
              ))}
            </TextField>

            <Grid container spacing={2}>
              <Grid item xs={8}>
                <TextField
                  fullWidth
                  type="number"
                  label={t('alerts.thresholdValue')}
                  value={editingThreshold?.threshold_value}
                  onChange={(e) => setEditingThreshold({ ...editingThreshold!, threshold_value: parseFloat(e.target.value) })}
                  margin="normal"
                />
              </Grid>
              <Grid item xs={4}>
                <TextField
                  fullWidth
                  select
                  label={t('alerts.unit')}
                  value={unitLabels[editingThreshold?.metric_type || 'cpu'] || ''}
                  disabled
                  margin="normal"
                >
                  <option>{unitLabels[editingThreshold?.metric_type || 'cpu'] || ''}</option>
                </TextField>
              </Grid>
            </Grid>

            <TextField
              fullWidth
              select
              label={t('alerts.comparison')}
              value={editingThreshold?.comparison_operator || '>'}
              onChange={(e) => setEditingThreshold({ ...editingThreshold!, comparison_operator: e.target.value })}
              margin="normal"
            >
              {Object.keys(operatorLabels).map((op) => (
                <option key={op} value={op}>{operatorLabels[op]}</option>
              ))}
            </TextField>

            <TextField
              fullWidth
              select
              label={t('alerts.action')}
              value={editingThreshold?.action || 'notify'}
              onChange={(e) => setEditingThreshold({ ...editingThreshold!, action: e.target.value })}
              margin="normal"
            >
              <option value="notify">{t('alerts.notifyOnly')}</option>
              <option value="notify_and_suspend">{t('alerts.notifySuspend')}</option>
              <option value="notify_and_limit">{t('alerts.notifyLimit')}</option>
            </TextField>

            <TextField
              fullWidth
              select
              label={t('alerts.subscription')}
              value={editingThreshold?.subscription_id || ''}
              onChange={(e) => setEditingThreshold({ ...editingThreshold!, subscription_id: e.target.value ? parseInt(e.target.value) : undefined })}
              margin="normal"
            >
              <option value="">{t('alerts.allSubscriptions')}</option>
              {/* Add subscription options here */}
            </TextField>

            <Box sx={{ display: 'flex', alignItems: 'center', mt: 2 }}>
              <input
                type="checkbox"
                checked={editingThreshold?.is_active ?? true}
                onChange={(e) => editingThreshold && setEditingThreshold({ ...editingThreshold, is_active: e.target.checked })}
              />
              <Typography variant="body2" sx={{ ml: 1 }}>{t('alerts.active')}</Typography>
            </Box>
          </Box>
        </DialogContent>
        <DialogActions>
          <Button onClick={handleCloseDialog}>{t('common.cancel')}</Button>
          <Button variant="contained" onClick={handleSave}>
            {editingThreshold?.id === 0 ? t('common.add') : t('common.save')}
          </Button>
        </DialogActions>
      </Dialog>
    </Box>
  );
};

export default AlertsPage;
