import React, { useState, useEffect } from 'react';
import {
  Box,
  Paper,
  Typography,
  Button,
  List,
  ListItem,
  ListItemText,
  ListItemSecondaryAction,
  IconButton,
  CircularProgress,
  Alert,
  Dialog,
  DialogTitle,
  DialogContent,
  DialogActions,
  DialogContentText,
  Chip,
  Divider,
  LinearProgress
} from '@mui/material';
import {
  Backup as BackupIcon,
  Restore as RestoreIcon,
  Delete as DeleteIcon,
  Download as DownloadIcon,
  CloudUpload as UploadIcon,
  Info as InfoIcon
} from '@mui/icons-material';
import { useTranslation } from 'react-i18next';
import axios from 'axios';
import { useAuthStore } from '../store/authStore';

const BackupRestore = () => {
  const { t } = useTranslation();
  const { token } = useAuthStore();
  const [backups, setBackups] = useState([]);
  const [loading, setLoading] = useState(false);
  const [creating, setCreating] = useState(false);
  const [restoring, setRestoring] = useState(false);
  const [error, setError] = useState('');
  const [success, setSuccess] = useState('');
  const [deleteDialogOpen, setDeleteDialogOpen] = useState(false);
  const [restoreDialogOpen, setRestoreDialogOpen] = useState(false);
  const [selectedBackup, setSelectedBackup] = useState(null);
  const [uploadProgress, setUploadProgress] = useState(0);

  useEffect(() => {
    fetchBackups();
  }, []);

  const fetchBackups = async () => {
    try {
      setLoading(true);
      const response = await axios.get('/api/backup/list', {
        headers: { Authorization: `Bearer ${token}` }
      });
      setBackups(response.data);
    } catch (err) {
      setError(t('backup.fetchError'));
      console.error('Failed to fetch backups:', err);
    } finally {
      setLoading(false);
    }
  };

  const handleCreateBackup = async () => {
    try {
      setCreating(true);
      setError('');
      setSuccess('');
      
      const response = await axios.post('/api/backup/create', {}, {
        headers: { Authorization: `Bearer ${token}` }
      });
      
      setSuccess(t('backup.createSuccess'));
      fetchBackups();
    } catch (err) {
      setError(t('backup.createError'));
      console.error('Failed to create backup:', err);
    } finally {
      setCreating(false);
    }
  };

  const handleDownloadBackup = (backup) => {
    window.open(`/api/backup/download/${backup.filename}?token=${token}`, '_blank');
  };

  const handleDeleteBackup = async () => {
    if (!selectedBackup) return;
    
    try {
      await axios.delete(`/api/backup/${selectedBackup.filename}`, {
        headers: { Authorization: `Bearer ${token}` }
      });
      
      setSuccess(t('backup.deleteSuccess'));
      setDeleteDialogOpen(false);
      setSelectedBackup(null);
      fetchBackups();
    } catch (err) {
      setError(t('backup.deleteError'));
      console.error('Failed to delete backup:', err);
    }
  };

  const handleRestoreBackup = async () => {
    if (!selectedBackup) return;
    
    try {
      setRestoring(true);
      setError('');
      setSuccess('');
      
      const response = await axios.post(
        `/api/backup/restore/${selectedBackup.filename}`,
        {},
        { headers: { Authorization: `Bearer ${token}` } }
      );
      
      setSuccess(
        `${t('backup.restoreSuccess')}: ${response.data.stats.playlists} playlists, ${response.data.stats.channels} channels, ${response.data.stats.favorites} favorites`
      );
      setRestoreDialogOpen(false);
      setSelectedBackup(null);
      
      // Refresh page after 2 seconds to show restored data
      setTimeout(() => window.location.reload(), 2000);
    } catch (err) {
      setError(t('backup.restoreError'));
      console.error('Failed to restore backup:', err);
    } finally {
      setRestoring(false);
    }
  };

  const handleUploadBackup = async (event) => {
    const file = event.target.files[0];
    if (!file) return;
    
    try {
      setLoading(true);
      setError('');
      setSuccess('');
      setUploadProgress(0);
      
      const formData = new FormData();
      formData.append('backup', file);
      
      await axios.post('/api/backup/upload', formData, {
        headers: {
          Authorization: `Bearer ${token}`,
          'Content-Type': 'multipart/form-data'
        },
        onUploadProgress: (progressEvent) => {
          const percentCompleted = Math.round((progressEvent.loaded * 100) / progressEvent.total);
          setUploadProgress(percentCompleted);
        }
      });
      
      setSuccess(t('backup.uploadSuccess'));
      fetchBackups();
    } catch (err) {
      setError(t('backup.uploadError'));
      console.error('Failed to upload backup:', err);
    } finally {
      setLoading(false);
      setUploadProgress(0);
      event.target.value = null;
    }
  };

  const formatFileSize = (bytes) => {
    if (bytes === 0) return '0 Bytes';
    const k = 1024;
    const sizes = ['Bytes', 'KB', 'MB', 'GB'];
    const i = Math.floor(Math.log(bytes) / Math.log(k));
    return Math.round(bytes / Math.pow(k, i) * 100) / 100 + ' ' + sizes[i];
  };

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

  return (
    <Paper sx={{ p: 2 }}>
      <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', mb: 2 }}>
        <Typography variant="h6" sx={{ fontSize: '1rem', fontWeight: 600 }}>
          {t('backup.title')}
        </Typography>
        <Box sx={{ display: 'flex', gap: 1 }}>
          <Button
            variant="outlined"
            size="small"
            component="label"
            startIcon={<UploadIcon fontSize="small" />}
            disabled={loading}
          >
            {t('backup.upload')}
            <input
              type="file"
              hidden
              accept=".zip"
              onChange={handleUploadBackup}
            />
          </Button>
          <Button
            variant="contained"
            size="small"
            onClick={handleCreateBackup}
            startIcon={creating ? <CircularProgress size={16} /> : <BackupIcon fontSize="small" />}
            disabled={creating || loading}
          >
            {t('backup.create')}
          </Button>
        </Box>
      </Box>

      {uploadProgress > 0 && (
        <Box sx={{ mb: 2 }}>
          <LinearProgress variant="determinate" value={uploadProgress} />
          <Typography variant="caption" sx={{ mt: 0.5 }}>
            {t('backup.uploading')}: {uploadProgress}%
          </Typography>
        </Box>
      )}

      {error && (
        <Alert severity="error" onClose={() => setError('')} sx={{ mb: 2, fontSize: '0.75rem' }}>
          {error}
        </Alert>
      )}

      {success && (
        <Alert severity="success" onClose={() => setSuccess('')} sx={{ mb: 2, fontSize: '0.75rem' }}>
          {success}
        </Alert>
      )}

      <Alert severity="info" icon={<InfoIcon fontSize="small" />} sx={{ mb: 2, fontSize: '0.75rem' }}>
        {t('backup.description')}
      </Alert>

      {loading && !uploadProgress ? (
        <Box sx={{ display: 'flex', justifyContent: 'center', py: 3 }}>
          <CircularProgress size={24} />
        </Box>
      ) : backups.length === 0 ? (
        <Box sx={{ textAlign: 'center', py: 3 }}>
          <Typography variant="body2" color="text.secondary">
            {t('backup.noBackups')}
          </Typography>
        </Box>
      ) : (
        <List disablePadding>
          {backups.map((backup, index) => (
            <React.Fragment key={backup.filename}>
              {index > 0 && <Divider />}
              <ListItem
                sx={{
                  px: 0,
                  py: 1.5,
                  flexDirection: { xs: 'column', sm: 'row' },
                  alignItems: { xs: 'flex-start', sm: 'center' }
                }}
              >
                <ListItemText
                  primary={
                    <Box sx={{ display: 'flex', alignItems: 'center', gap: 1, flexWrap: 'wrap' }}>
                      <Typography variant="body2" sx={{ fontWeight: 500 }}>
                        {t('backup.backup')} #{backups.length - index}
                      </Typography>
                      <Chip 
                        label={formatFileSize(backup.size)} 
                        size="small" 
                        sx={{ height: '20px', fontSize: '0.7rem' }}
                      />
                    </Box>
                  }
                  secondary={
                    <Typography variant="caption" color="text.secondary">
                      {t('backup.created')}: {formatDate(backup.created)}
                    </Typography>
                  }
                  sx={{ mb: { xs: 1, sm: 0 } }}
                />
                <ListItemSecondaryAction sx={{ position: { xs: 'relative', sm: 'absolute' }, right: 0 }}>
                  <Box sx={{ display: 'flex', gap: 0.5 }}>
                    <IconButton
                      size="small"
                      onClick={() => handleDownloadBackup(backup)}
                      title={t('backup.download')}
                    >
                      <DownloadIcon fontSize="small" />
                    </IconButton>
                    <IconButton
                      size="small"
                      onClick={() => {
                        setSelectedBackup(backup);
                        setRestoreDialogOpen(true);
                      }}
                      title={t('backup.restore')}
                      color="primary"
                    >
                      <RestoreIcon fontSize="small" />
                    </IconButton>
                    <IconButton
                      size="small"
                      onClick={() => {
                        setSelectedBackup(backup);
                        setDeleteDialogOpen(true);
                      }}
                      title={t('backup.delete')}
                      color="error"
                    >
                      <DeleteIcon fontSize="small" />
                    </IconButton>
                  </Box>
                </ListItemSecondaryAction>
              </ListItem>
            </React.Fragment>
          ))}
        </List>
      )}

      {/* Delete Confirmation Dialog */}
      <Dialog open={deleteDialogOpen} onClose={() => setDeleteDialogOpen(false)} maxWidth="xs" fullWidth>
        <DialogTitle>{t('backup.deleteTitle')}</DialogTitle>
        <DialogContent>
          <DialogContentText>
            {t('backup.deleteConfirm')}
          </DialogContentText>
        </DialogContent>
        <DialogActions>
          <Button onClick={() => setDeleteDialogOpen(false)} size="small">
            {t('common.cancel')}
          </Button>
          <Button onClick={handleDeleteBackup} color="error" variant="contained" size="small">
            {t('common.delete')}
          </Button>
        </DialogActions>
      </Dialog>

      {/* Restore Confirmation Dialog */}
      <Dialog open={restoreDialogOpen} onClose={() => !restoring && setRestoreDialogOpen(false)} maxWidth="xs" fullWidth>
        <DialogTitle>{t('backup.restoreTitle')}</DialogTitle>
        <DialogContent>
          <DialogContentText>
            {t('backup.restoreConfirm')}
          </DialogContentText>
          <Alert severity="warning" sx={{ mt: 2, fontSize: '0.75rem' }}>
            {t('backup.restoreWarning')}
          </Alert>
        </DialogContent>
        <DialogActions>
          <Button onClick={() => setRestoreDialogOpen(false)} size="small" disabled={restoring}>
            {t('common.cancel')}
          </Button>
          <Button
            onClick={handleRestoreBackup}
            color="primary"
            variant="contained"
            size="small"
            disabled={restoring}
            startIcon={restoring ? <CircularProgress size={16} /> : <RestoreIcon fontSize="small" />}
          >
            {t('backup.restore')}
          </Button>
        </DialogActions>
      </Dialog>
    </Paper>
  );
};

export default BackupRestore;
