import React, { useState, useEffect } from 'react';
import {
  Box,
  Card,
  CardContent,
  Typography,
  Button,
  Alert,
  CircularProgress,
  List,
  ListItem,
  ListItemText,
  ListItemSecondaryAction,
  IconButton,
  Dialog,
  DialogTitle,
  DialogContent,
  DialogActions,
  TextField,
  Chip,
  Stack,
  Divider
} from '@mui/material';
import {
  Upload,
  Delete,
  PowerSettingsNew,
  CheckCircle,
  Public,
  Router,
  Info,
  CloudUpload
} from '@mui/icons-material';
import { useTranslation } from 'react-i18next';
import { useAuthStore } from '../store/authStore';

const VPNConfigManager = () => {
  const { t } = useTranslation();
  const token = useAuthStore((state) => state.token);
  const [configs, setConfigs] = useState([]);
  const [loading, setLoading] = useState(true);
  const [uploadDialogOpen, setUploadDialogOpen] = useState(false);
  const [selectedFile, setSelectedFile] = useState(null);
  const [configName, setConfigName] = useState('');
  const [uploading, setUploading] = useState(false);
  const [message, setMessage] = useState({ type: '', text: '' });
  const [deleteDialogOpen, setDeleteDialogOpen] = useState(false);
  const [configToDelete, setConfigToDelete] = useState(null);
  const [connecting, setConnecting] = useState(null); // configId being connected/disconnected

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

  const loadConfigs = async () => {
    try {
      const response = await fetch('/api/vpn-configs/configs', {
        headers: {
          'Authorization': `Bearer ${token}`
        }
      });

      if (response.ok) {
        const data = await response.json();
        setConfigs(data.configs || []);
      }
    } catch (error) {
      console.error('Failed to load configs:', error);
      setMessage({ type: 'error', text: t('vpnConfig.loadFailed') || 'Failed to load configurations' });
    } finally {
      setLoading(false);
    }
  };

  const handleFileSelect = (event) => {
    const file = event.target.files[0];
    if (file) {
      const ext = file.name.split('.').pop().toLowerCase();
      if (ext === 'conf' || ext === 'ovpn') {
        setSelectedFile(file);
        // Auto-fill name from filename
        const name = file.name.replace(/\.(conf|ovpn)$/, '');
        setConfigName(name);
      } else {
        setMessage({ type: 'error', text: t('vpnConfig.invalidFileType') || 'Only .conf and .ovpn files are supported' });
      }
    }
  };

  const handleUpload = async () => {
    if (!selectedFile || !configName.trim()) {
      setMessage({ type: 'error', text: t('vpnConfig.nameRequired') || 'Configuration name is required' });
      return;
    }

    setUploading(true);
    setMessage({ type: '', text: '' });

    try {
      const formData = new FormData();
      formData.append('config', selectedFile);
      formData.append('name', configName.trim());

      const response = await fetch('/api/vpn-configs/configs/upload', {
        method: 'POST',
        headers: {
          'Authorization': `Bearer ${token}`
        },
        body: formData
      });

      let data = {};
      try {
        data = await response.json();
      } catch (e) {
        data = { error: 'Server error' };
      }

      if (response.ok) {
        setMessage({ type: 'success', text: t('vpnConfig.uploadSuccess') || 'Configuration uploaded successfully!' });
        setUploadDialogOpen(false);
        setSelectedFile(null);
        setConfigName('');
        await loadConfigs();
      } else {
        const errorMsg = typeof data.error === 'string' ? data.error : t('vpnConfig.uploadFailed') || 'Failed to upload configuration';
        setMessage({ type: 'error', text: errorMsg });
      }
    } catch (error) {
      const errorMsg = error.message || t('vpnConfig.uploadError') || 'Error uploading configuration';
      setMessage({ type: 'error', text: errorMsg });
    } finally {
      setUploading(false);
    }
  };

  const handleConnect = async (configId) => {
    setMessage({ type: '', text: '' });
    setConnecting(configId);

    try {
      console.log('[VPNConfigManager] Connecting to config:', configId);
      
      const response = await fetch(`/api/vpn-configs/configs/${configId}/connect`, {
        method: 'POST',
        headers: {
          'Authorization': `Bearer ${token}`,
          'Content-Type': 'application/json'
        }
      });

      console.log('[VPNConfigManager] Response status:', response.status);
      
      let data = {};
      try {
        data = await response.json();
      } catch (e) {
        console.error('[VPNConfigManager] Failed to parse response:', e);
        data = { error: 'Invalid server response' };
      }

      if (response.ok) {
        console.log('[VPNConfigManager] Connected successfully');
        setMessage({ type: 'success', text: t('vpnConfig.connected') || 'Connected to VPN successfully!' });
        await loadConfigs();
      } else {
        console.error('[VPNConfigManager] Connection failed:', data);
        const errorMsg = typeof data.error === 'string' ? data.error : t('vpnConfig.connectFailed') || 'Failed to connect';
        setMessage({ type: 'error', text: errorMsg });
      }
    } catch (error) {
      console.error('[VPNConfigManager] Connect error:', error);
      const errorMsg = error.message || t('vpnConfig.connectError') || 'Error connecting to VPN';
      setMessage({ type: 'error', text: errorMsg });
    } finally {
      setConnecting(null);
    }
  };

  const handleDisconnect = async (configId) => {
    setMessage({ type: '', text: '' });
    setConnecting(configId);

    try {
      console.log('[VPNConfigManager] Disconnecting from config:', configId);
      
      const response = await fetch(`/api/vpn-configs/configs/${configId}/disconnect`, {
        method: 'POST',
        headers: {
          'Authorization': `Bearer ${token}`,
          'Content-Type': 'application/json'
        }
      });

      let data = {};
      try {
        data = await response.json();
      } catch (e) {
        console.error('[VPNConfigManager] Failed to parse response:', e);
        data = { error: 'Invalid server response' };
      }

      if (response.ok) {
        console.log('[VPNConfigManager] Disconnected successfully');
        setMessage({ type: 'success', text: t('vpnConfig.disconnected') || 'Disconnected from VPN successfully!' });
        await loadConfigs();
      } else {
        console.error('[VPNConfigManager] Disconnect failed:', data);
        const errorMsg = typeof data.error === 'string' ? data.error : t('vpnConfig.disconnectFailed') || 'Failed to disconnect';
        setMessage({ type: 'error', text: errorMsg });
      }
    } catch (error) {
      console.error('[VPNConfigManager] Disconnect error:', error);
      const errorMsg = error.message || t('vpnConfig.disconnectError') || 'Error disconnecting from VPN';
      setMessage({ type: 'error', text: errorMsg });
    } finally {
      setConnecting(null);
    }
  };

  const handleDelete = async () => {
    if (!configToDelete) return;

    try {
      const response = await fetch(`/api/vpn-configs/configs/${configToDelete}`, {
        method: 'DELETE',
        headers: {
          'Authorization': `Bearer ${token}`
        }
      });

      const data = await response.json();

      if (response.ok) {
        setMessage({ type: 'success', text: t('vpnConfig.deleteSuccess') || 'Configuration deleted successfully' });
        setDeleteDialogOpen(false);
        setConfigToDelete(null);
        await loadConfigs();
      } else {
        setMessage({ type: 'error', text: data.error || t('vpnConfig.deleteFailed') || 'Failed to delete configuration' });
      }
    } catch (error) {
      setMessage({ type: 'error', text: t('vpnConfig.deleteError') || 'Error deleting configuration' });
    }
  };

  const getCountryFlag = (countryCode) => {
    const flags = {
      'US': '🇺🇸', 'NL': '🇳🇱', 'JP': '🇯🇵', 'GB': '🇬🇧',
      'DE': '🇩🇪', 'FR': '🇫🇷', 'CA': '🇨🇦', 'CH': '🇨🇭',
      'SE': '🇸🇪', 'RO': '🇷🇴'
    };
    return flags[countryCode] || '🌍';
  };

  if (loading) {
    return (
      <Box sx={{ display: 'flex', justifyContent: 'center', p: 3 }}>
        <CircularProgress />
      </Box>
    );
  }

  return (
    <Box sx={{ p: 3 }}>
      <Stack direction="row" justifyContent="space-between" alignItems="center" mb={3}>
        <Typography variant="h4" sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
          <Router /> {t('vpnConfig.title') || 'VPN Configurations'}
        </Typography>
        <Button
          variant="contained"
          startIcon={<CloudUpload />}
          onClick={() => setUploadDialogOpen(true)}
        >
          {t('vpnConfig.uploadConfig') || 'Upload Config'}
        </Button>
      </Stack>

      {message.text && (
        <Alert severity={message.type} sx={{ mb: 3 }} onClose={() => setMessage({ type: '', text: '' })}>
          {message.text}
        </Alert>
      )}

      <Alert severity="warning" sx={{ mb: 3 }}>
        {t('vpnConfig.dockerLimitationWarning')}
      </Alert>

      <Alert severity="info" sx={{ mb: 3 }} icon={<Info />}>
        {t('vpnConfig.infoText') || 'Upload VPN configuration files (.conf for WireGuard, .ovpn for OpenVPN) to easily manage multiple VPN connections.'}
      </Alert>

      {configs.length === 0 ? (
        <Card>
          <CardContent sx={{ textAlign: 'center', py: 6 }}>
            <CloudUpload sx={{ fontSize: 64, color: 'text.secondary', mb: 2 }} />
            <Typography variant="h6" color="text.secondary" gutterBottom>
              {t('vpnConfig.noConfigs') || 'No VPN configurations yet'}
            </Typography>
            <Typography variant="body2" color="text.secondary" mb={3}>
              {t('vpnConfig.uploadFirst') || 'Upload your first VPN configuration file to get started'}
            </Typography>
            <Button
              variant="outlined"
              startIcon={<CloudUpload />}
              onClick={() => setUploadDialogOpen(true)}
            >
              {t('vpnConfig.uploadConfig') || 'Upload Config'}
            </Button>
          </CardContent>
        </Card>
      ) : (
        <Card>
          <List>
            {configs.map((config, index) => (
              <React.Fragment key={config.id}>
                {index > 0 && <Divider />}
                <ListItem>
                  <ListItemText
                    primary={
                      <Stack direction="row" spacing={1} alignItems="center">
                        <Typography variant="body1" fontWeight={config.is_active ? 600 : 400}>
                          {config.name}
                        </Typography>
                        {config.is_active && (
                          <Chip
                            size="small"
                            icon={<CheckCircle />}
                            label={t('vpnConfig.active') || 'Active'}
                            color="success"
                          />
                        )}
                        <Chip
                          size="small"
                          label={config.config_type.toUpperCase()}
                          variant="outlined"
                        />
                      </Stack>
                    }
                    secondary={
                      <Stack direction="row" spacing={2} mt={0.5}>
                        {config.country && (
                          <Typography variant="caption" sx={{ display: 'flex', alignItems: 'center', gap: 0.5 }}>
                            <Public sx={{ fontSize: 14 }} />
                            {getCountryFlag(config.country)} {config.country}
                          </Typography>
                        )}
                        {config.server_name && (
                          <Typography variant="caption" sx={{ display: 'flex', alignItems: 'center', gap: 0.5 }}>
                            <Router sx={{ fontSize: 14 }} />
                            {config.server_name}
                          </Typography>
                        )}
                        <Typography variant="caption" color="text.secondary">
                          {new Date(config.created_at).toLocaleDateString()}
                        </Typography>
                      </Stack>
                    }
                  />
                  <ListItemSecondaryAction>
                    <Stack direction="row" spacing={1}>
                      {config.is_active ? (
                        <Button
                          size="small"
                          variant="outlined"
                          color="error"
                          startIcon={connecting === config.id ? <CircularProgress size={16} /> : <PowerSettingsNew />}
                          onClick={() => handleDisconnect(config.id)}
                          disabled={connecting === config.id}
                        >
                          {connecting === config.id 
                            ? (t('vpnConfig.disconnecting') || 'Disconnecting...') 
                            : (t('vpnConfig.disconnect') || 'Disconnect')}
                        </Button>
                      ) : (
                        <Button
                          size="small"
                          variant="contained"
                          color="success"
                          startIcon={connecting === config.id ? <CircularProgress size={16} /> : <PowerSettingsNew />}
                          onClick={() => handleConnect(config.id)}
                          disabled={connecting === config.id}
                        >
                          {connecting === config.id 
                            ? (t('vpnConfig.connecting') || 'Connecting...') 
                            : (t('vpnConfig.connect') || 'Connect')}
                        </Button>
                      )}
                      <IconButton
                        edge="end"
                        onClick={() => {
                          setConfigToDelete(config.id);
                          setDeleteDialogOpen(true);
                        }}
                        disabled={config.is_active || connecting === config.id}
                      >
                        <Delete />
                      </IconButton>
                    </Stack>
                  </ListItemSecondaryAction>
                </ListItem>
              </React.Fragment>
            ))}
          </List>
        </Card>
      )}

      {/* Upload Dialog */}
      <Dialog
        open={uploadDialogOpen}
        onClose={() => !uploading && setUploadDialogOpen(false)}
        maxWidth="sm"
        fullWidth
      >
        <DialogTitle>{t('vpnConfig.uploadConfig') || 'Upload VPN Configuration'}</DialogTitle>
        <DialogContent>
          <Stack spacing={3} mt={1}>
            <TextField
              fullWidth
              label={t('vpnConfig.configName') || 'Configuration Name'}
              value={configName}
              onChange={(e) => setConfigName(e.target.value)}
              placeholder="My VPN Config"
              helperText={t('vpnConfig.nameHelper') || 'A friendly name to identify this configuration'}
            />

            <Box>
              <input
                accept=".conf,.ovpn"
                style={{ display: 'none' }}
                id="vpn-config-file"
                type="file"
                onChange={handleFileSelect}
              />
              <label htmlFor="vpn-config-file">
                <Button
                  component="span"
                  variant="outlined"
                  fullWidth
                  startIcon={<Upload />}
                >
                  {selectedFile
                    ? selectedFile.name
                    : (t('vpnConfig.selectFile') || 'Select .conf or .ovpn file')}
                </Button>
              </label>
              <Typography variant="caption" display="block" mt={1} color="text.secondary">
                {t('vpnConfig.fileTypes') || 'Supported: WireGuard (.conf) and OpenVPN (.ovpn) configuration files'}
              </Typography>
            </Box>

            {message.text && uploadDialogOpen && (
              <Alert severity={message.type}>{message.text}</Alert>
            )}
          </Stack>
        </DialogContent>
        <DialogActions>
          <Button onClick={() => setUploadDialogOpen(false)} disabled={uploading}>
            {t('cancel') || 'Cancel'}
          </Button>
          <Button
            onClick={handleUpload}
            variant="contained"
            disabled={!selectedFile || !configName.trim() || uploading}
            startIcon={uploading ? <CircularProgress size={16} /> : <CloudUpload />}
          >
            {t('vpnConfig.upload') || 'Upload'}
          </Button>
        </DialogActions>
      </Dialog>

      {/* Delete Confirmation Dialog */}
      <Dialog open={deleteDialogOpen} onClose={() => setDeleteDialogOpen(false)}>
        <DialogTitle>{t('vpnConfig.deleteConfirmTitle') || 'Delete Configuration?'}</DialogTitle>
        <DialogContent>
          <Typography>
            {t('vpnConfig.deleteConfirmText') || 'Are you sure you want to delete this VPN configuration? This action cannot be undone.'}
          </Typography>
        </DialogContent>
        <DialogActions>
          <Button onClick={() => setDeleteDialogOpen(false)}>{t('cancel') || 'Cancel'}</Button>
          <Button onClick={handleDelete} color="error" variant="contained">
            {t('delete') || 'Delete'}
          </Button>
        </DialogActions>
      </Dialog>
    </Box>
  );
};

export default VPNConfigManager;
