import React, { useState, useEffect } from 'react';
import {
  Card,
  Typography,
  Button,
  Box,
  Table,
  TableBody,
  TableCell,
  TableContainer,
  TableHead,
  TableRow,
  Paper,
  Chip,
  Grid,
  CircularProgress
} from '@mui/material';
import DeleteIcon from '@mui/icons-material/Delete';
import WarningIcon from '@mui/icons-material/Warning';
import InfoIcon from '@mui/icons-material/Info';

const DeletionLogSection = () => {
  const [deletions, setDeletions] = useState([]);
  const [statistics, setStatistics] = useState(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);
  const [showAll, setShowAll] = useState(false);

  useEffect(() => {
    loadDeletionLog();
    loadStatistics();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [showAll]);

  const loadDeletionLog = async () => {
    try {
      setLoading(true);
      const endpoint = showAll 
        ? '/api/admin/deletion-log/all' 
        : '/api/admin/deletion-log?limit=10';
      
      const response = await fetch(endpoint);
      
      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`);
      }
      
      const data = await response.json();
      setDeletions(data.deletions || []);
      setError(null);
    } catch (error) {
      console.error('Fehler beim Laden des Lösch-Logs:', error);
      setError('Fehler beim Laden des Lösch-Logs');
    } finally {
      setLoading(false);
    }
  };

  const loadStatistics = async () => {
    try {
      const response = await fetch('/api/admin/deletion-log/stats');
      
      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`);
      }
      
      const data = await response.json();
      setStatistics(data.statistics || null);
    } catch (error) {
      console.error('Fehler beim Laden der Statistiken:', error);
    }
  };

  const formatDate = (dateString) => {
    if (!dateString) return '-';
    const date = new Date(dateString);
    return date.toLocaleString('de-DE', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit'
    });
  };

  const formatFileSize = (bytes) => {
    if (!bytes || bytes === 0) return '0 KB';
    
    const k = 1024;
    const sizes = ['Bytes', 'KB', 'MB', 'GB'];
    const i = Math.floor(Math.log(bytes) / Math.log(k));
    
    return `${(bytes / Math.pow(k, i)).toFixed(2)} ${sizes[i]}`;
  };

  const getReasonIcon = (reason) => {
    if (reason && reason.includes('unapproved')) {
      return <WarningIcon fontSize="small" color="warning" />;
    }
    return <DeleteIcon fontSize="small" color="action" />;
  };

  if (loading) {
    return (
      <Box sx={{ textAlign: 'center', py: 4 }}>
        <CircularProgress size={40} />
        <Typography variant="body2" sx={{ mt: 2, color: '#666' }}>
          Lade Lösch-Historie...
        </Typography>
      </Box>
    );
  }

  return (
    <Box sx={{ mt: 6, mb: 4 }}>
      <Box sx={{ mb: 3 }}>
        <Typography variant="h5" component="h2" gutterBottom sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
          <DeleteIcon />
          Lösch-Historie
        </Typography>
        <Typography variant="body2" color="text.secondary">
          Automatisch gelöschte Gruppen (nicht innerhalb von 7 Tagen freigegeben)
        </Typography>
      </Box>

      {error && (
        <Card sx={{ p: 2, mb: 3, backgroundColor: '#ffebee' }}>
          <Typography color="error">{error}</Typography>
        </Card>
      )}

      {/* Statistics Cards */}
      {statistics && (
        <Grid container spacing={2} sx={{ mb: 3 }}>
          <Grid item xs={12} sm={4}>
            <Card sx={{ p: 2, textAlign: 'center', backgroundColor: '#f5f5f5' }}>
              <Typography variant="h4" color="primary" fontWeight="bold">
                {statistics.totalGroupsDeleted || 0}
              </Typography>
              <Typography variant="body2" color="text.secondary">
                Gelöschte Gruppen
              </Typography>
            </Card>
          </Grid>
          <Grid item xs={12} sm={4}>
            <Card sx={{ p: 2, textAlign: 'center', backgroundColor: '#f5f5f5' }}>
              <Typography variant="h4" color="secondary" fontWeight="bold">
                {statistics.totalImagesDeleted || 0}
              </Typography>
              <Typography variant="body2" color="text.secondary">
                Gelöschte Bilder
              </Typography>
            </Card>
          </Grid>
          <Grid item xs={12} sm={4}>
            <Card sx={{ p: 2, textAlign: 'center', backgroundColor: '#f5f5f5' }}>
              <Typography variant="h4" color="success.main" fontWeight="bold">
                {statistics.totalStorageFreed || '0 KB'}
              </Typography>
              <Typography variant="body2" color="text.secondary">
                Speicher freigegeben
              </Typography>
            </Card>
          </Grid>
        </Grid>
      )}

      {/* Toggle Button */}
      <Box sx={{ mb: 2, display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
        <Typography variant="subtitle1" fontWeight="bold">
          {showAll ? 'Alle Einträge' : 'Letzte 10 Einträge'}
        </Typography>
        <Button 
          variant="outlined" 
          size="small"
          onClick={() => setShowAll(!showAll)}
          startIcon={<InfoIcon />}
        >
          {showAll ? 'Nur letzte 10' : 'Alle anzeigen'}
        </Button>
      </Box>

      {/* Deletion Log Table */}
      {deletions.length === 0 ? (
        <Card sx={{ p: 3, textAlign: 'center' }}>
          <InfoIcon sx={{ fontSize: 48, color: '#bdbdbd', mb: 1 }} />
          <Typography variant="body1" color="text.secondary">
            Keine Lösch-Einträge gefunden
          </Typography>
          <Typography variant="body2" color="text.secondary">
            Es wurden bisher keine Gruppen automatisch gelöscht.
          </Typography>
        </Card>
      ) : (
        <TableContainer component={Paper}>
          <Table size="small">
            <TableHead>
              <TableRow sx={{ backgroundColor: '#f5f5f5' }}>
                <TableCell><strong>Gruppe ID</strong></TableCell>
                <TableCell><strong>Jahr</strong></TableCell>
                <TableCell align="right"><strong>Bilder</strong></TableCell>
                <TableCell><strong>Upload-Datum</strong></TableCell>
                <TableCell><strong>Gelöscht am</strong></TableCell>
                <TableCell><strong>Grund</strong></TableCell>
                <TableCell align="right"><strong>Größe</strong></TableCell>
              </TableRow>
            </TableHead>
            <TableBody>
              {deletions.map((row) => (
                <TableRow 
                  key={row.id}
                  sx={{ '&:hover': { backgroundColor: '#fafafa' } }}
                >
                  <TableCell>
                    <Chip 
                      label={row.group_id} 
                      size="small" 
                      variant="outlined"
                    />
                  </TableCell>
                  <TableCell>{row.year || '-'}</TableCell>
                  <TableCell align="right">{row.image_count || 0}</TableCell>
                  <TableCell>{formatDate(row.upload_date)}</TableCell>
                  <TableCell>{formatDate(row.deleted_at)}</TableCell>
                  <TableCell>
                    <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
                      {getReasonIcon(row.deletion_reason)}
                      <Typography variant="body2">
                        {row.deletion_reason || 'Unbekannt'}
                      </Typography>
                    </Box>
                  </TableCell>
                  <TableCell align="right">
                    <Typography variant="body2" color="text.secondary">
                      {formatFileSize(row.total_file_size)}
                    </Typography>
                  </TableCell>
                </TableRow>
              ))}
            </TableBody>
          </Table>
        </TableContainer>
      )}

      {/* Info Box */}
      <Card sx={{ mt: 3, p: 2, backgroundColor: '#e3f2fd' }}>
        <Box sx={{ display: 'flex', alignItems: 'flex-start', gap: 2 }}>
          <InfoIcon color="info" />
          <Box>
            <Typography variant="body2" fontWeight="bold" gutterBottom>
              Automatische Löschung
            </Typography>
            <Typography variant="body2" color="text.secondary">
              Der Cleanup läuft täglich um 10:00 Uhr. Gruppen, die nicht innerhalb von 7 Tagen 
              freigegeben werden, werden automatisch gelöscht. Alle Lösch-Vorgänge werden hier protokolliert.
            </Typography>
          </Box>
        </Box>
      </Card>
    </Box>
  );
};

export default DeletionLogSection;
