import React, { useState } from 'react';
import { 
  Box, 
  Paper, 
  Typography, 
  Button, 
  Stack, 
  Divider, 
  Alert, 
  LinearProgress,
  IconButton,
  Table,
  TableBody,
  TableCell,
  TableContainer,
  TableRow,
  Avatar
} from '@mui/material';
import { 
  CloudDownload, 
  CloudUpload, 
  Storage, 
  CheckCircle,
  Error as ErrorIcon,
  Close
} from '@mui/icons-material';
import { SchemaService } from '../services/api';
import { useAppStore } from '../store/useAppStore';

interface TransferContentProps {
  mode?: 'import' | 'export' | 'both';
}

const TransferContent: React.FC<TransferContentProps> = ({ mode = 'both' }) => {
  const { activeDatabase, activeTable, darkMode } = useAppStore();
  const [loading, setLoading] = useState(false);
  const [success, setSuccess] = useState<string | null>(null);
  const [error, setError] = useState<string | null>(null);
  const [file, setFile] = useState<File | null>(null);

  const handleExport = async () => {
    setLoading(true);
    setError(null);
    setSuccess(null);
    try {
      const response = await SchemaService.exportDatabase(activeDatabase || undefined, activeTable || undefined);
      const url = window.URL.createObjectURL(new Blob([response.data]));
      const link = document.createElement('a');
      link.href = url;
      const filename = activeTable 
        ? `${activeTable}-${new Date().toISOString().split('T')[0]}.sql` 
        : `backup-${activeDatabase || 'all'}-${new Date().toISOString().split('T')[0]}.sql`;
      link.setAttribute('download', filename);
      document.body.appendChild(link);
      link.click();
      setSuccess(`${activeTable ? 'Table' : 'Database'} exported successfully!`);
    } catch (err: any) {
      setError('Export failed: ' + (err.response?.data?.error || err.message));
    } finally {
      setLoading(false);
    }
  };

  const handleFileChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    if (e.target.files && e.target.files[0]) {
      setFile(e.target.files[0]);
    }
  };

  const handleImport = async () => {
    if (!file) return;
    setLoading(true);
    setError(null);
    setSuccess(null);
    try {
      const formData = new FormData();
      formData.append('file', file);
      if (activeDatabase) formData.append('database', activeDatabase);
      if (activeTable) formData.append('table', activeTable);

      await SchemaService.importDatabase(formData);
      setSuccess(`${activeTable ? 'Table' : 'Database'} imported successfully!`);
      setFile(null);
    } catch (err: any) {
      setError('Import failed: ' + (err.response?.data?.error || err.message));
    } finally {
      setLoading(false);
    }
  };

  return (
    <Box sx={{ flexGrow: 1, p: 4, bgcolor: 'background.default', display: 'flex', justifyContent: 'center' }}>
      <Stack spacing={4} sx={{ width: '100%', maxWidth: 800 }}>
        <Box>
          <Typography variant="h4" sx={{ fontWeight: 800, mb: 1 }}>{activeTable ? 'Table' : 'Database'} Transfer</Typography>
          <Typography variant="body1" color="text.secondary">
            Export your {activeTable ? 'table' : 'database'} to a SQL file or import an existing SQL dump using <strong>mysqldump</strong>.
          </Typography>
        </Box>

        {(success || error) && (
          <Alert 
            severity={success ? "success" : "error"}
            icon={success ? <CheckCircle /> : <ErrorIcon />}
            action={
              <IconButton size="small" onClick={() => { setSuccess(null); setError(null); }}>
                <Close fontSize="small" />
              </IconButton>
            }
            sx={{ 
              borderRadius: 2, 
              boxShadow: '0 4px 12px rgba(0,0,0,0.05)',
              '& .MuiAlert-message': { whiteSpace: 'pre-line' }
            }}
          >
            {success || error}
          </Alert>
        )}

        <TableContainer component={Paper} sx={{ 
          borderRadius: 4, 
          border: 1, 
          borderColor: 'divider',
          bgcolor: 'background.paper',
          overflow: 'hidden',
          boxShadow: 'none'
        }}>
          <Table>
            <TableBody>
              {/* Export Row */}
              {(mode === 'export' || mode === 'both') && (
                <TableRow sx={{ '&:hover': { bgcolor: 'rgba(255,255,255,0.02)' } }}>
                  <TableCell sx={{ width: 80, verticalAlign: 'top', pt: 3 }}>
                    <Avatar sx={{ bgcolor: 'primary.main', color: 'white', width: 48, height: 48 }}>
                      <CloudDownload />
                    </Avatar>
                  </TableCell>
                  <TableCell sx={{ py: 3 }}>
                    <Typography variant="h6" sx={{ fontWeight: 700, mb: 0.5 }}>Export {activeTable ? 'Table' : 'Database'}</Typography>
                    <Typography variant="body2" color="text.secondary">
                      Create a full backup of the current {activeTable ? 'table' : 'database'}: <br/>
                      <Box component="span" sx={{ color: 'primary.main', fontWeight: 600 }}>
                        {activeTable ? `${activeDatabase}.${activeTable}` : (activeDatabase || 'All Databases')}
                      </Box>
                    </Typography>
                  </TableCell>
                  <TableCell align="right" sx={{ py: 3 }}>
                    <Button 
                      variant="contained" 
                      startIcon={<CloudDownload />}
                      onClick={handleExport}
                      disabled={loading}
                      sx={{ borderRadius: 2, px: 3, py: 1, fontWeight: 700, minWidth: 160 }}
                    >
                      Start Export
                    </Button>
                  </TableCell>
                </TableRow>
              )}

              {/* Import Row */}
              {(mode === 'import' || mode === 'both') && (
                <TableRow sx={{ '&:hover': { bgcolor: 'rgba(255,255,255,0.02)' } }}>
                  <TableCell sx={{ width: 80, verticalAlign: 'top', pt: 3 }}>
                    <Avatar sx={{ bgcolor: 'secondary.main', color: 'white', width: 48, height: 48 }}>
                      <CloudUpload />
                    </Avatar>
                  </TableCell>
                  <TableCell sx={{ py: 3 }}>
                    <Typography variant="h6" sx={{ fontWeight: 700, mb: 0.5 }}>Import {activeTable ? 'Table' : 'Database'}</Typography>
                    <Typography variant="body2" color="text.secondary" sx={{ mb: 2 }}>
                      Upload a .sql file to restore or migrate your {activeTable ? 'table' : 'database'}.
                    </Typography>
                    
                    <Box sx={{ 
                      maxWidth: 400,
                      p: 1.5, 
                      border: '2px dashed', 
                      borderColor: file ? 'secondary.main' : 'divider',
                      borderRadius: 2,
                      bgcolor: 'rgba(0,0,0,0.02)',
                      cursor: 'pointer',
                      position: 'relative',
                      display: 'flex',
                      alignItems: 'center',
                      gap: 1
                    }}>
                      <input 
                        type="file" 
                        accept=".sql" 
                        onChange={handleFileChange}
                        style={{ position: 'absolute', top: 0, left: 0, width: '100%', height: '100%', opacity: 0, cursor: 'pointer', zIndex: 1 }}
                      />
                      <CloudUpload fontSize="small" color={file ? "secondary" : "disabled"} />
                      <Typography variant="caption" sx={{ fontWeight: 600 }}>
                        {file ? file.name : "Select or drag .sql file here"}
                      </Typography>
                    </Box>
                  </TableCell>
                  <TableCell align="right" sx={{ py: 3 }}>
                    <Button 
                      variant="outlined" 
                      color="secondary"
                      startIcon={<CloudUpload />}
                      onClick={handleImport}
                      disabled={loading || !file}
                      sx={{ borderRadius: 2, px: 3, py: 1, fontWeight: 700, minWidth: 160 }}
                    >
                      Start Import
                    </Button>
                  </TableCell>
                </TableRow>
              )}
            </TableBody>
          </Table>
        </TableContainer>

        {loading && (
          <Box sx={{ width: '100%' }}>
            <Typography variant="caption" sx={{ mb: 1, display: 'block', textAlign: 'center' }}>
              Processing... This may take a while for large databases.
            </Typography>
            <LinearProgress sx={{ borderRadius: 5, height: 8 }} />
          </Box>
        )}

        <Box sx={{ p: 3, borderRadius: 3, bgcolor: 'rgba(0, 0, 0, 0.03)', border: 1, borderColor: 'divider' }}>
          <Stack direction="row" spacing={2} sx={{ alignItems: 'center' }}>
            <Storage color="primary" />
            <Box>
              <Typography variant="subtitle2" sx={{ fontWeight: 700 }}>System Requirements</Typography>
              <Typography variant="caption" color="text.secondary">
                This system requires <code>mysqldump</code> and <code>mysql</code> clients to be installed and available in the server's PATH.
              </Typography>
            </Box>
          </Stack>
        </Box>
      </Stack>
    </Box>
  );
};

export default TransferContent;
