import React, { useState, useEffect } from 'react';
import {
  Box,
  Card,
  CardContent,
  Typography,
  TextField,
  Button,
  Alert,
  CircularProgress,
  Switch,
  FormControlLabel,
  Divider,
  Chip,
  Stack
} from '@mui/material';
import {
  VpnKey,
  Public,
  NetworkCheck,
  Router,
  Dns,
  CheckCircle,
  Error as ErrorIcon,
  Info
} from '@mui/icons-material';
import { useTranslation } from 'react-i18next';

const WireGuardSettings = () => {
  const { t } = useTranslation();
  const [settings, setSettings] = useState({
    privateKey: '',
    serverPublicKey: '',
    serverEndpoint: '',
    clientAddress: '',
    dnsServer: ''
  });
  const [status, setStatus] = useState({
    connected: false,
    publicIP: '',
    interface: '',
    loading: false
  });
  const [message, setMessage] = useState({ type: '', text: '' });
  const [loading, setLoading] = useState(false);
  const [configParsed, setConfigParsed] = useState(false);

  useEffect(() => {
    loadSettings();
    checkStatus();
    const interval = setInterval(checkStatus, 10000); // Check status every 10s
    return () => clearInterval(interval);
  }, []);

  const loadSettings = async () => {
    try {
      const response = await fetch('/api/wireguard/settings', {
        headers: {
          'Authorization': `Bearer ${localStorage.getItem('token')}`
        }
      });
      if (response.ok) {
        const data = await response.json();
        if (data.settings) {
          setSettings({
            privateKey: '********', // Don't show actual key
            serverPublicKey: data.settings.server_public_key || '',
            serverEndpoint: data.settings.server_endpoint || '',
            clientAddress: data.settings.client_address || '',
            dnsServer: data.settings.dns_server || ''
          });
          setConfigParsed(true);
        }
      }
    } catch (error) {
      console.error('Failed to load WireGuard settings:', error);
    }
  };

  const checkStatus = async () => {
    try {
      const response = await fetch('/api/wireguard/status', {
        headers: {
          'Authorization': `Bearer ${localStorage.getItem('token')}`
        }
      });
      if (response.ok) {
        const data = await response.json();
        setStatus({
          connected: data.connected,
          publicIP: data.publicIP || '',
          interface: data.interface || '',
          loading: false
        });
      }
    } catch (error) {
      console.error('Failed to check status:', error);
      setStatus(prev => ({ ...prev, loading: false }));
    }
  };

  const parseConfig = (configText) => {
    const lines = configText.split('\n');
    const parsed = {
      privateKey: '',
      serverPublicKey: '',
      serverEndpoint: '',
      clientAddress: '',
      dnsServer: ''
    };

    let inInterface = false;
    let inPeer = false;

    lines.forEach(line => {
      const trimmed = line.trim();
      if (trimmed === '[Interface]') {
        inInterface = true;
        inPeer = false;
      } else if (trimmed === '[Peer]') {
        inInterface = false;
        inPeer = true;
      } else if (trimmed.startsWith('PrivateKey') && inInterface) {
        parsed.privateKey = trimmed.split('=')[1]?.trim() || '';
      } else if (trimmed.startsWith('Address') && inInterface) {
        parsed.clientAddress = trimmed.split('=')[1]?.trim() || '';
      } else if (trimmed.startsWith('DNS') && inInterface) {
        parsed.dnsServer = trimmed.split('=')[1]?.trim() || '';
      } else if (trimmed.startsWith('PublicKey') && inPeer) {
        parsed.serverPublicKey = trimmed.split('=')[1]?.trim() || '';
      } else if (trimmed.startsWith('Endpoint') && inPeer) {
        parsed.serverEndpoint = trimmed.split('=')[1]?.trim() || '';
      }
    });

    return parsed;
  };

  const handleConfigPaste = (e) => {
    const configText = e.target.value;
    if (configText.includes('[Interface]') && configText.includes('[Peer]')) {
      const parsed = parseConfig(configText);
      setSettings(parsed);
      setConfigParsed(true);
      setMessage({ type: 'success', text: t('wireguard.configParsed') || 'Configuration parsed successfully!' });
    }
  };

  const handleSaveSettings = async () => {
    setLoading(true);
    setMessage({ type: '', text: '' });

    try {
      const response = await fetch('/api/wireguard/settings', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${localStorage.getItem('token')}`
        },
        body: JSON.stringify(settings)
      });

      const data = await response.json();

      if (response.ok) {
        setMessage({ type: 'success', text: t('wireguard.settingsSaved') || 'Settings saved successfully!' });
        setConfigParsed(true);
      } else {
        setMessage({ type: 'error', text: data.error || t('wireguard.saveFailed') || 'Failed to save settings' });
      }
    } catch (error) {
      setMessage({ type: 'error', text: t('wireguard.saveError') || 'Error saving settings' });
    } finally {
      setLoading(false);
    }
  };

  const handleConnect = async () => {
    setStatus(prev => ({ ...prev, loading: true }));
    setMessage({ type: '', text: '' });

    try {
      const response = await fetch('/api/wireguard/connect', {
        method: 'POST',
        headers: {
          'Authorization': `Bearer ${localStorage.getItem('token')}`
        }
      });

      const data = await response.json();

      if (response.ok) {
        setMessage({ type: 'success', text: t('wireguard.connected') || 'Connected to WireGuard VPN!' });
        setTimeout(checkStatus, 2000);
      } else {
        setMessage({ type: 'error', text: data.error || t('wireguard.connectFailed') || 'Failed to connect' });
        setStatus(prev => ({ ...prev, loading: false }));
      }
    } catch (error) {
      setMessage({ type: 'error', text: t('wireguard.connectError') || 'Error connecting to VPN' });
      setStatus(prev => ({ ...prev, loading: false }));
    }
  };

  const handleDisconnect = async () => {
    setStatus(prev => ({ ...prev, loading: true }));
    setMessage({ type: '', text: '' });

    try {
      const response = await fetch('/api/wireguard/disconnect', {
        method: 'POST',
        headers: {
          'Authorization': `Bearer ${localStorage.getItem('token')}`
        }
      });

      const data = await response.json();

      if (response.ok) {
        setMessage({ type: 'info', text: t('wireguard.disconnected') || 'Disconnected from VPN' });
        setTimeout(checkStatus, 2000);
      } else {
        setMessage({ type: 'error', text: data.error || t('wireguard.disconnectFailed') || 'Failed to disconnect' });
        setStatus(prev => ({ ...prev, loading: false }));
      }
    } catch (error) {
      setMessage({ type: 'error', text: t('wireguard.disconnectError') || 'Error disconnecting from VPN' });
      setStatus(prev => ({ ...prev, loading: false }));
    }
  };

  return (
    <Box sx={{ p: 3 }}>
      <Typography variant="h4" gutterBottom sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
        <VpnKey /> {t('wireguard.title') || 'WireGuard VPN'}
      </Typography>

      {/* Status Card */}
      <Card sx={{ mb: 3, bgcolor: status.connected ? 'success.light' : 'grey.100' }}>
        <CardContent>
          <Stack direction="row" spacing={2} alignItems="center" justifyContent="space-between">
            <Box sx={{ display: 'flex', alignItems: 'center', gap: 2 }}>
              {status.loading ? (
                <CircularProgress size={24} />
              ) : status.connected ? (
                <CheckCircle color="success" />
              ) : (
                <ErrorIcon color="disabled" />
              )}
              <Box>
                <Typography variant="h6">
                  {status.connected ? (t('wireguard.status.connected') || 'Connected') : (t('wireguard.status.disconnected') || 'Disconnected')}
                </Typography>
                {status.connected && (
                  <>
                    <Typography variant="body2" color="text.secondary">
                      <Public sx={{ fontSize: 14, mr: 0.5, verticalAlign: 'middle' }} />
                      {t('wireguard.publicIP') || 'Public IP'}: {status.publicIP || t('wireguard.checking') || 'Checking...'}
                    </Typography>
                    <Typography variant="body2" color="text.secondary">
                      <Router sx={{ fontSize: 14, mr: 0.5, verticalAlign: 'middle' }} />
                      {t('wireguard.interface') || 'Interface'}: {status.interface}
                    </Typography>
                  </>
                )}
              </Box>
            </Box>
            <Box>
              {status.connected ? (
                <Button
                  variant="contained"
                  color="error"
                  onClick={handleDisconnect}
                  disabled={status.loading}
                >
                  {t('wireguard.disconnect') || 'Disconnect'}
                </Button>
              ) : (
                <Button
                  variant="contained"
                  color="success"
                  onClick={handleConnect}
                  disabled={status.loading || !configParsed}
                >
                  {t('wireguard.connect') || 'Connect'}
                </Button>
              )}
            </Box>
          </Stack>
        </CardContent>
      </Card>

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

      {/* Configuration Card */}
      <Card>
        <CardContent>
          <Typography variant="h6" gutterBottom>
            {t('wireguard.configuration') || 'Configuration'}
          </Typography>
          
          <Alert severity="info" sx={{ mb: 3 }} icon={<Info />}>
            {t('wireguard.pasteConfigHint') || 'Paste your complete WireGuard configuration file below, or enter details manually.'}
          </Alert>

          <TextField
            fullWidth
            multiline
            rows={6}
            label={t('wireguard.configFile') || 'WireGuard Config File'}
            placeholder="[Interface]&#10;PrivateKey = ...&#10;Address = ...&#10;DNS = ...&#10;&#10;[Peer]&#10;PublicKey = ...&#10;AllowedIPs = ...&#10;Endpoint = ..."
            onChange={handleConfigPaste}
            sx={{ mb: 3 }}
          />

          <Divider sx={{ my: 3 }}>
            <Chip label={t('wireguard.or') || 'OR'} />
          </Divider>

          <Stack spacing={3}>
            <TextField
              fullWidth
              type="password"
              label={t('wireguard.privateKey') || 'Private Key'}
              value={settings.privateKey}
              onChange={(e) => setSettings({ ...settings, privateKey: e.target.value })}
              placeholder="base64-encoded private key"
              InputProps={{
                startAdornment: <VpnKey sx={{ mr: 1, color: 'action.active' }} />
              }}
            />

            <TextField
              fullWidth
              label={t('wireguard.serverPublicKey') || 'Server Public Key'}
              value={settings.serverPublicKey}
              onChange={(e) => setSettings({ ...settings, serverPublicKey: e.target.value })}
              placeholder="base64-encoded public key"
              InputProps={{
                startAdornment: <VpnKey sx={{ mr: 1, color: 'action.active' }} />
              }}
            />

            <TextField
              fullWidth
              label={t('wireguard.serverEndpoint') || 'Server Endpoint'}
              value={settings.serverEndpoint}
              onChange={(e) => setSettings({ ...settings, serverEndpoint: e.target.value })}
              placeholder="IP:PORT (e.g., 185.163.110.98:51820)"
              InputProps={{
                startAdornment: <NetworkCheck sx={{ mr: 1, color: 'action.active' }} />
              }}
            />

            <TextField
              fullWidth
              label={t('wireguard.clientAddress') || 'Client Address'}
              value={settings.clientAddress}
              onChange={(e) => setSettings({ ...settings, clientAddress: e.target.value })}
              placeholder="10.2.0.2/32"
              InputProps={{
                startAdornment: <Router sx={{ mr: 1, color: 'action.active' }} />
              }}
            />

            <TextField
              fullWidth
              label={t('wireguard.dnsServer') || 'DNS Server'}
              value={settings.dnsServer}
              onChange={(e) => setSettings({ ...settings, dnsServer: e.target.value })}
              placeholder="10.2.0.1"
              InputProps={{
                startAdornment: <Dns sx={{ mr: 1, color: 'action.active' }} />
              }}
            />

            <Button
              variant="contained"
              onClick={handleSaveSettings}
              disabled={loading || !settings.privateKey || !settings.serverEndpoint}
              fullWidth
            >
              {loading ? <CircularProgress size={24} /> : (t('wireguard.saveSettings') || 'Save Settings')}
            </Button>
          </Stack>
        </CardContent>
      </Card>
    </Box>
  );
};

export default WireGuardSettings;
