import React, { useState, useEffect } from 'react';
import {
  Box,
  Container,
  Typography,
  Card,
  CardContent,
  Grid,
  Button,
  Table,
  TableBody,
  TableCell,
  TableContainer,
  TableHead,
  TableRow,
  Paper,
  Chip,
  CircularProgress,
  Alert,
  Dialog,
  DialogTitle,
  DialogContent,
  DialogActions,
  TextField,
  IconButton,
  Tooltip
} from '@mui/material';
import {
  Archive,
  Delete,
  Download,
  Security,
  VerifiedUser,
  Warning,
  CleaningServices,
  Storage,
  Refresh,
  CheckCircle,
  Error as ErrorIcon,
  ArrowBack
} from '@mui/icons-material';
import { useTranslation } from 'react-i18next';
import { useAuthStore } from '../store/authStore';
import { useNavigate } from 'react-router-dom';
import { useErrorNotification } from './ErrorNotificationProvider';
import axios from 'axios';
import { format } from 'date-fns';

const LogManagementDashboard = () => {
  const { t } = useTranslation();
  const { token, user } = useAuthStore();
  const navigate = useNavigate();
  const { showError, showSuccess, showWarning } = useErrorNotification();
  
  const [loading, setLoading] = useState(true);
  const [statistics, setStatistics] = useState(null);
  const [archives, setArchives] = useState([]);
  const [cleanupDialogOpen, setCleanupDialogOpen] = useState(false);
  const [retentionDays, setRetentionDays] = useState(90);
  const [verifyDialogOpen, setVerifyDialogOpen] = useState(false);
  const [integrityResult, setIntegrityResult] = useState(null);
  const [actionLoading, setActionLoading] = useState(false);

  useEffect(() => {
    if (!user || user.role !== 'admin') {
      navigate('/');
      return;
    }
    
    fetchData();
  }, [user, navigate]);

  const fetchData = async () => {
    setLoading(true);
    try {
      const [statsRes, archivesRes] = await Promise.all([
        axios.get('/api/log-management/statistics', {
          headers: { Authorization: `Bearer ${token}` }
        }),
        axios.get('/api/log-management/archives', {
          headers: { Authorization: `Bearer ${token}` }
        })
      ]);
      
      setStatistics(statsRes.data.data);
      setArchives(archivesRes.data.data);
    } catch (err) {
      if (err.response?.status !== 401) {
        showError(err, {
          title: t('errors.general.title'),
          defaultMessage: 'Failed to load log management data'
        });
      }
    } finally {
      setLoading(false);
    }
  };

  const handleManualCleanup = async () => {
    setActionLoading(true);
    try {
      const response = await axios.post('/api/log-management/cleanup', 
        { retentionDays },
        { headers: { Authorization: `Bearer ${token}` } }
      );
      
      showSuccess(response.data.message, { duration: 5000 });
      setCleanupDialogOpen(false);
      fetchData();
    } catch (err) {
      showError(err, {
        title: t('errors.general.title'),
        defaultMessage: 'Failed to perform cleanup'
      });
    } finally {
      setActionLoading(false);
    }
  };

  const handleVerifyIntegrity = async () => {
    setActionLoading(true);
    try {
      const response = await axios.post('/api/log-management/verify-integrity', {}, {
        headers: { Authorization: `Bearer ${token}` }
      });
      
      setIntegrityResult(response.data.data);
      setVerifyDialogOpen(true);
      
      if (response.data.alert) {
        showWarning(response.data.message, { 
          title: 'Security Alert',
          duration: 10000 
        });
      } else {
        showSuccess(response.data.message);
      }
    } catch (err) {
      showError(err, {
        title: t('errors.general.title'),
        defaultMessage: 'Failed to verify log integrity'
      });
    } finally {
      setActionLoading(false);
    }
  };

  const handleDownloadArchive = (filename) => {
    window.location.href = `/api/log-management/archives/download/${filename}?token=${token}`;
  };

  const handleDeleteArchive = async (filename) => {
    if (!confirm(`Delete archive "${filename}"? This action cannot be undone.`)) {
      return;
    }
    
    try {
      await axios.delete(`/api/log-management/archives/${filename}`, {
        headers: { Authorization: `Bearer ${token}` }
      });
      
      showSuccess('Archive deleted successfully');
      fetchData();
    } catch (err) {
      showError(err, {
        title: t('errors.general.title'),
        defaultMessage: 'Failed to delete archive'
      });
    }
  };

  if (loading) {
    return (
      <Container maxWidth="xl" sx={{ mt: 4, mb: 4 }}>
        <Box sx={{ display: 'flex', justifyContent: 'center', alignItems: 'center', height: '50vh' }}>
          <CircularProgress />
        </Box>
      </Container>
    );
  }

  const totalLogs = statistics?.sources?.reduce((sum, s) => sum + s.total, 0) || 0;
  const archiveSize = statistics?.archives?.totalSizeMB || 0;
  const archiveCount = statistics?.archives?.count || 0;

  return (
    <Container maxWidth="xl" sx={{ mt: 4, mb: 4 }}>
      {/* Header with Back Button */}
      <Box sx={{ mb: 4, display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
        <Box sx={{ display: 'flex', alignItems: 'center', gap: 2 }}>
          <IconButton
            onClick={() => navigate('/security')}
            color="primary"
            size="large"
          >
            <ArrowBack />
          </IconButton>
          <Archive sx={{ fontSize: 40, color: 'primary.main' }} />
          <Box>
            <Typography variant="h4" fontWeight="bold">
              {t('logManagement.title')}
            </Typography>
            <Typography variant="body2" color="text.secondary">
              {t('logManagement.subtitle')}
            </Typography>
          </Box>
        </Box>
        <Button
          variant="outlined"
          startIcon={<Refresh />}
          onClick={fetchData}
        >
          {t('common.refresh')}
        </Button>
      </Box>

      <Alert severity="info" sx={{ mb: 3 }}>
        <strong>CWE-53 Compliance:</strong> Automated log retention, archival, and integrity verification are active.
        Logs are preserved securely with tamper detection and encrypted archives.
      </Alert>

      {/* Statistics Cards */}
      <Grid container spacing={3} sx={{ mb: 4 }}>
        <Grid item xs={12} md={3}>
          <Card>
            <CardContent>
              <Box sx={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
                <Box>
                  <Typography variant="caption" color="text.secondary">
                    {t('logManagement.totalLogs')}
                  </Typography>
                  <Typography variant="h4" fontWeight="bold">
                    {totalLogs.toLocaleString()}
                  </Typography>
                </Box>
                <Storage sx={{ fontSize: 40, color: 'primary.main', opacity: 0.5 }} />
              </Box>
            </CardContent>
          </Card>
        </Grid>

        <Grid item xs={12} md={3}>
          <Card>
            <CardContent>
              <Box sx={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
                <Box>
                  <Typography variant="caption" color="text.secondary">
                    {t('logManagement.archives')}
                  </Typography>
                  <Typography variant="h4" fontWeight="bold">
                    {archiveCount}
                  </Typography>
                  <Typography variant="caption" color="text.secondary">
                    {archiveSize} MB
                  </Typography>
                </Box>
                <Archive sx={{ fontSize: 40, color: 'success.main', opacity: 0.5 }} />
              </Box>
            </CardContent>
          </Card>
        </Grid>

        <Grid item xs={12} md={3}>
          <Card>
            <CardContent>
              <Box sx={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
                <Box>
                  <Typography variant="caption" color="text.secondary">
                    {t('logManagement.retention')}
                  </Typography>
                  <Typography variant="h4" fontWeight="bold">
                    90
                  </Typography>
                  <Typography variant="caption" color="text.secondary">
                    {t('logManagement.days')}
                  </Typography>
                </Box>
                <CleaningServices sx={{ fontSize: 40, color: 'warning.main', opacity: 0.5 }} />
              </Box>
            </CardContent>
          </Card>
        </Grid>

        <Grid item xs={12} md={3}>
          <Card>
            <CardContent>
              <Box sx={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
                <Box>
                  <Typography variant="caption" color="text.secondary">
                    {t('logManagement.integrity')}
                  </Typography>
                  <Typography variant="h4" fontWeight="bold" color="success.main">
                    ✓
                  </Typography>
                  <Typography variant="caption" color="text.secondary">
                    {t('logManagement.protected')}
                  </Typography>
                </Box>
                <VerifiedUser sx={{ fontSize: 40, color: 'success.main', opacity: 0.5 }} />
              </Box>
            </CardContent>
          </Card>
        </Grid>
      </Grid>

      {/* Action Buttons */}
      <Grid container spacing={2} sx={{ mb: 4 }}>
        <Grid item xs={12} md={6}>
          <Button
            fullWidth
            variant="contained"
            color="warning"
            startIcon={<CleaningServices />}
            onClick={() => setCleanupDialogOpen(true)}
            sx={{ py: 1.5 }}
          >
            {t('logManagement.manualCleanup')}
          </Button>
        </Grid>
        <Grid item xs={12} md={6}>
          <Button
            fullWidth
            variant="contained"
            color="primary"
            startIcon={<Security />}
            onClick={handleVerifyIntegrity}
            disabled={actionLoading}
            sx={{ py: 1.5 }}
          >
            {actionLoading ? <CircularProgress size={24} /> : t('logManagement.verifyIntegrity')}
          </Button>
        </Grid>
      </Grid>

      {/* Archives Table */}
      <Card>
        <CardContent>
          <Typography variant="h6" fontWeight="bold" sx={{ mb: 2 }}>
            {t('logManagement.archivesList')}
          </Typography>
          
          {archives.length === 0 ? (
            <Alert severity="info">{t('logManagement.noArchives')}</Alert>
          ) : (
            <TableContainer>
              <Table>
                <TableHead>
                  <TableRow>
                    <TableCell><strong>{t('logManagement.filename')}</strong></TableCell>
                    <TableCell><strong>{t('logManagement.size')}</strong></TableCell>
                    <TableCell><strong>{t('logManagement.created')}</strong></TableCell>
                    <TableCell align="right"><strong>{t('common.actions')}</strong></TableCell>
                  </TableRow>
                </TableHead>
                <TableBody>
                  {archives.map((archive) => (
                    <TableRow key={archive.filename} hover>
                      <TableCell>
                        <Typography variant="body2" fontFamily="monospace">
                          {archive.filename}
                        </Typography>
                      </TableCell>
                      <TableCell>
                        <Chip 
                          label={`${archive.sizeMB} MB`} 
                          size="small"
                          color="primary"
                          variant="outlined"
                        />
                      </TableCell>
                      <TableCell>
                        {format(new Date(archive.created), 'PPpp')}
                      </TableCell>
                      <TableCell align="right">
                        <Tooltip title={t('common.download')}>
                          <IconButton
                            size="small"
                            color="primary"
                            onClick={() => handleDownloadArchive(archive.filename)}
                          >
                            <Download />
                          </IconButton>
                        </Tooltip>
                        <Tooltip title={t('common.delete')}>
                          <IconButton
                            size="small"
                            color="error"
                            onClick={() => handleDeleteArchive(archive.filename)}
                          >
                            <Delete />
                          </IconButton>
                        </Tooltip>
                      </TableCell>
                    </TableRow>
                  ))}
                </TableBody>
              </Table>
            </TableContainer>
          )}
        </CardContent>
      </Card>

      {/* Cleanup Dialog */}
      <Dialog open={cleanupDialogOpen} onClose={() => setCleanupDialogOpen(false)}>
        <DialogTitle>{t('logManagement.manualCleanup')}</DialogTitle>
        <DialogContent>
          <Box sx={{ pt: 2 }}>
            <Alert severity="warning" sx={{ mb: 2 }}>
              {t('logManagement.cleanupWarning')}
            </Alert>
            <TextField
              fullWidth
              type="number"
              label={t('logManagement.retentionDays')}
              value={retentionDays}
              onChange={(e) => setRetentionDays(parseInt(e.target.value) || 90)}
              inputProps={{ min: 7, max: 365 }}
              helperText={t('logManagement.retentionHelp')}
            />
          </Box>
        </DialogContent>
        <DialogActions>
          <Button onClick={() => setCleanupDialogOpen(false)}>
            {t('common.cancel')}
          </Button>
          <Button
            variant="contained"
            color="warning"
            onClick={handleManualCleanup}
            disabled={actionLoading}
          >
            {actionLoading ? <CircularProgress size={24} /> : t('logManagement.performCleanup')}
          </Button>
        </DialogActions>
      </Dialog>

      {/* Integrity Result Dialog */}
      <Dialog open={verifyDialogOpen} onClose={() => setVerifyDialogOpen(false)} maxWidth="sm" fullWidth>
        <DialogTitle>
          <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
            {integrityResult?.tampered > 0 ? (
              <ErrorIcon color="error" />
            ) : (
              <CheckCircle color="success" />
            )}
            {t('logManagement.integrityResults')}
          </Box>
        </DialogTitle>
        <DialogContent>
          {integrityResult && (
            <Box sx={{ pt: 2 }}>
              <Grid container spacing={2}>
                <Grid item xs={6}>
                  <Card variant="outlined">
                    <CardContent>
                      <Typography variant="caption" color="text.secondary">
                        {t('logManagement.verified')}
                      </Typography>
                      <Typography variant="h4" color="success.main">
                        {integrityResult.verified}
                      </Typography>
                    </CardContent>
                  </Card>
                </Grid>
                <Grid item xs={6}>
                  <Card variant="outlined">
                    <CardContent>
                      <Typography variant="caption" color="text.secondary">
                        {t('logManagement.tampered')}
                      </Typography>
                      <Typography variant="h4" color="error.main">
                        {integrityResult.tampered}
                      </Typography>
                    </CardContent>
                  </Card>
                </Grid>
              </Grid>

              {integrityResult.tampered > 0 && (
                <Alert severity="error" sx={{ mt: 2 }}>
                  <strong>{t('logManagement.securityAlert')}:</strong> {integrityResult.tampered} tampered logs detected. 
                  Immediate investigation required!
                </Alert>
              )}

              {integrityResult.tampered === 0 && (
                <Alert severity="success" sx={{ mt: 2 }}>
                  {t('logManagement.allLogsVerified')}
                </Alert>
              )}
            </Box>
          )}
        </DialogContent>
        <DialogActions>
          <Button onClick={() => setVerifyDialogOpen(false)} variant="contained">
            {t('common.close')}
          </Button>
        </DialogActions>
      </Dialog>
    </Container>
  );
};

export default LogManagementDashboard;
