import { useState } from 'react';
import {
  Box,
  Card,
  CardContent,
  Typography,
  Button,
  TextField,
  Stepper,
  Step,
  StepLabel,
  Grid,
  FormControl,
  InputLabel,
  Select,
  MenuItem,
  Alert,
  CircularProgress,
  InputAdornment,
  IconButton,
  Dialog,
  DialogTitle,
  DialogContent,
  DialogActions,
  FormControlLabel,
  Switch,
  Chip,
} from '@mui/material';
import {
  Visibility,
  VisibilityOff,
  Cloud as PleskIcon,
  Business as SapIcon,
  Check as CheckIcon,
  Key as KeyIcon,
  Security as SecurityIcon,
} from '@mui/icons-material';
import { useI18n } from '../contexts/I18nContext';
import toast from 'react-hot-toast';

interface PleskConfig {
  host: string;
  port: number;
  username: string;
  password: string;
  api_key: string;
  use_https: boolean;
  verify_ssl: boolean;
  two_factor_enabled: boolean;
  two_factor_method: 'totp' | 'sms' | 'email' | 'none';
  two_factor_secret?: string;
}

interface SapConfig {
  host: string;
  port: number;
  company_db: string;
  username: string;
  password: string;
  use_ssl: boolean;
  timeout_seconds: number;
}

interface SyncConfig {
  sync_direction: string;
  sync_interval_minutes: number;
  conflict_resolution: string;
  auto_sync_enabled: boolean;
}

const SetupWizardPage = () => {
  const { t } = useI18n();
  const [activeStep, setActiveStep] = useState(0);
  const [loading, setLoading] = useState(false);
  const [testResults, setTestResults] = useState<{ plesk: boolean | null; sap: boolean | null }>({
    plesk: null,
    sap: null,
  });

  const [showPleskPassword, setShowPleskPassword] = useState(false);
  const [showSapPassword, setShowSapPassword] = useState(false);
  
  // 2FA Dialog State
  const [twoFactorDialogOpen, setTwoFactorDialogOpen] = useState(false);
  const [twoFactorCode, setTwoFactorCode] = useState('');
  const [twoFactorWaiting, setTwoFactorWaiting] = useState(false);
  const [twoFactorChannel, setTwoFactorChannel] = useState<string>('');
  const [twoFactorPrompt, setTwoFactorPrompt] = useState<string>('');
  const [connectionSession, setConnectionSession] = useState<string | null>(null);

  const [pleskConfig, setPleskConfig] = useState<PleskConfig>({
    host: '',
    port: 8443,
    username: '',
    password: '',
    api_key: '',
    use_https: true,
    verify_ssl: true,
    two_factor_enabled: false,
    two_factor_method: 'none',
    two_factor_secret: '',
  });

  const [sapConfig, setSapConfig] = useState<SapConfig>({
    host: '',
    port: 50000,
    company_db: '',
    username: '',
    password: '',
    use_ssl: false,
    timeout_seconds: 30,
  });

  const [syncConfig, setSyncConfig] = useState<SyncConfig>({
    sync_direction: 'sap_to_plesk',
    sync_interval_minutes: 60,
    conflict_resolution: 'timestamp_based',
    auto_sync_enabled: true,
  });

  const steps = [
    { label: t('wizard.welcome'), icon: null },
    { label: t('wizard.plesk'), icon: <PleskIcon /> },
    { label: t('wizard.sap'), icon: <SapIcon /> },
    { label: t('wizard.sync'), icon: null },
    { label: t('wizard.complete'), icon: null },
  ];

  const handleNext = () => {
    setActiveStep((prev) => prev + 1);
  };

  const handleBack = () => {
    setActiveStep((prev) => prev - 1);
  };

  const testPleskConnection = async () => {
    setLoading(true);
    setTestResults((prev) => ({ ...prev, plesk: null }));
    
    try {
      const response = await fetch('/api/config/test-plesk', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        credentials: 'include',
        body: JSON.stringify({
          ...pleskConfig,
          session_id: connectionSession,
        }),
      });
      
      const data = await response.json();
      
      // Check if 2FA is required
      if (data.requires_2fa) {
        setTwoFactorChannel(data.channel || 'app');
        setTwoFactorPrompt(data.prompt || t('wizard.2fa_enter_code'));
        setConnectionSession(data.session_id);
        setTwoFactorDialogOpen(true);
        setTwoFactorWaiting(true);
        setLoading(false);
        return;
      }
      
      const success = response.ok && data.success;
      setTestResults((prev) => ({ ...prev, plesk: success }));
      
      if (success) {
        toast.success(t('wizard.plesk_success'));
      } else {
        toast.error(data.error || t('wizard.plesk_error'));
      }
    } catch (err) {
      setTestResults((prev) => ({ ...prev, plesk: false }));
      toast.error(t('wizard.connection_failed'));
    } finally {
      setLoading(false);
    }
  };

  const submitTwoFactorCode = async () => {
    if (!twoFactorCode) {
      toast.error(t('wizard.2fa_code_required'));
      return;
    }
    
    setLoading(true);
    
    try {
      const response = await fetch('/api/config/plesk2fa', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        credentials: 'include',
        body: JSON.stringify({
          session_id: connectionSession,
          code: twoFactorCode,
          host: pleskConfig.host,
          port: pleskConfig.port,
          username: pleskConfig.username,
          password: pleskConfig.password,
          api_key: pleskConfig.api_key,
        }),
      });
      
      const data = await response.json();
      
      if (data.success) {
        setTwoFactorDialogOpen(false);
        setTwoFactorCode('');
        setConnectionSession(null);
        setTestResults((prev) => ({ ...prev, plesk: true }));
        toast.success(t('wizard.plesk_success'));
      } else if (data.requires_2fa) {
        // Still need another code
        setTwoFactorPrompt(data.prompt || t('wizard.2fa_invalid'));
        setTwoFactorCode('');
      } else {
        toast.error(data.error || t('wizard.2fa_invalid'));
      }
    } catch {
      toast.error(t('wizard.connection_failed'));
    } finally {
      setLoading(false);
    }
  };

  const cancelTwoFactor = () => {
    setTwoFactorDialogOpen(false);
    setTwoFactorCode('');
    setConnectionSession(null);
    setTwoFactorWaiting(false);
    setLoading(false);
  };

  const testSapConnection = async () => {
    setLoading(true);
    try {
      const response = await fetch('/api/config/test-sap', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        credentials: 'include',
        body: JSON.stringify(sapConfig),
      });
      
      const success = response.ok;
      setTestResults((prev) => ({ ...prev, sap: success }));
      
      if (success) {
        toast.success(t('wizard.sap_success'));
      } else {
        toast.error(t('wizard.sap_error'));
      }
    } catch {
      setTestResults((prev) => ({ ...prev, sap: false }));
      toast.error(t('wizard.connection_failed'));
    } finally {
      setLoading(false);
    }
  };

  const saveConfiguration = async () => {
    setLoading(true);
    try {
      const response = await fetch('/api/config/setup', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        credentials: 'include',
        body: JSON.stringify({
          plesk: pleskConfig,
          sap: sapConfig,
          sync: syncConfig,
        }),
      });

      if (response.ok) {
        toast.success(t('wizard.save_success'));
        handleNext();
      } else {
        toast.error(t('wizard.save_error'));
      }
    } catch {
      toast.error(t('wizard.save_error'));
    } finally {
      setLoading(false);
    }
  };

  const renderWelcomeStep = () => (
    <Box textAlign="center">
      <Typography variant="h4" gutterBottom sx={{ fontWeight: 700 }}>
        {t('wizard.welcome_title')}
      </Typography>
      <Typography variant="body1" color="textSecondary" sx={{ mb: 4, maxWidth: 600, mx: 'auto' }}>
        {t('wizard.welcome_desc')}
      </Typography>
      
      <Grid container spacing={3} sx={{ mt: 2, maxWidth: 700, mx: 'auto' }}>
        <Grid item xs={12} md={6}>
          <Card variant="outlined" sx={{ height: '100%' }}>
            <CardContent>
              <PleskIcon sx={{ fontSize: 48, color: 'primary.main', mb: 1 }} />
              <Typography variant="h6">{t('wizard.plesk_setup')}</Typography>
              <Typography variant="body2" color="textSecondary">
                {t('wizard.plesk_setup_desc')}
              </Typography>
            </CardContent>
          </Card>
        </Grid>
        <Grid item xs={12} md={6}>
          <Card variant="outlined" sx={{ height: '100%' }}>
            <CardContent>
              <SapIcon sx={{ fontSize: 48, color: 'secondary.main', mb: 1 }} />
              <Typography variant="h6">{t('wizard.sap_setup')}</Typography>
              <Typography variant="body2" color="textSecondary">
                {t('wizard.sap_setup_desc')}
              </Typography>
            </CardContent>
          </Card>
        </Grid>
      </Grid>
    </Box>
  );

  const renderPleskStep = () => (
    <Box>
      <Typography variant="h5" gutterBottom sx={{ fontWeight: 600 }}>
        {t('wizard.plesk_config')}
      </Typography>
      <Typography variant="body2" color="textSecondary" sx={{ mb: 3 }}>
        {t('wizard.plesk_config_desc')}
      </Typography>

      <Grid container spacing={2}>
        <Grid item xs={12} md={8}>
          <TextField
            fullWidth
            label={t('wizard.plesk_host')}
            placeholder="plesk.example.com"
            value={pleskConfig.host}
            onChange={(e) => setPleskConfig({ ...pleskConfig, host: e.target.value })}
            margin="normal"
          />
        </Grid>
        <Grid item xs={12} md={4}>
          <TextField
            fullWidth
            label={t('wizard.port')}
            type="number"
            value={pleskConfig.port}
            onChange={(e) => setPleskConfig({ ...pleskConfig, port: parseInt(e.target.value) || 8443 })}
            margin="normal"
          />
        </Grid>
        <Grid item xs={12} md={6}>
          <TextField
            fullWidth
            label={t('wizard.username')}
            value={pleskConfig.username}
            onChange={(e) => setPleskConfig({ ...pleskConfig, username: e.target.value })}
            margin="normal"
          />
        </Grid>
        <Grid item xs={12} md={6}>
          <TextField
            fullWidth
            label={t('wizard.password')}
            type={showPleskPassword ? 'text' : 'password'}
            value={pleskConfig.password}
            onChange={(e) => setPleskConfig({ ...pleskConfig, password: e.target.value })}
            margin="normal"
            InputProps={{
              endAdornment: (
                <InputAdornment position="end">
                  <IconButton onClick={() => setShowPleskPassword(!showPleskPassword)} edge="end">
                    {showPleskPassword ? <VisibilityOff /> : <Visibility />}
                  </IconButton>
                </InputAdornment>
              ),
            }}
          />
        </Grid>
        <Grid item xs={12}>
          <TextField
            fullWidth
            label={t('wizard.api_key')}
            value={pleskConfig.api_key}
            onChange={(e) => setPleskConfig({ ...pleskConfig, api_key: e.target.value })}
            margin="normal"
            helperText={t('wizard.api_key_helper')}
          />
        </Grid>
        
        {/* 2FA Configuration Section */}
        <Grid item xs={12}>
          <Card variant="outlined" sx={{ mt: 2 }}>
            <CardContent>
              <Box sx={{ display: 'flex', alignItems: 'center', mb: 2 }}>
                <SecurityIcon sx={{ mr: 1, color: 'primary.main' }} />
                <Typography variant="subtitle1" sx={{ fontWeight: 600 }}>
                  {t('wizard.2fa_section')}
                </Typography>
              </Box>
              
              <FormControlLabel
                control={
                  <Switch
                    checked={pleskConfig.two_factor_enabled}
                    onChange={(e) => setPleskConfig({ 
                      ...pleskConfig, 
                      two_factor_enabled: e.target.checked,
                      two_factor_method: e.target.checked ? 'totp' : 'none'
                    })}
                  />
                }
                label={t('wizard.2fa_enabled')}
              />
              
              {pleskConfig.two_factor_enabled && (
                <Box sx={{ mt: 2 }}>
                  <FormControl fullWidth margin="normal">
                    <InputLabel>{t('wizard.2fa_method')}</InputLabel>
                    <Select
                      value={pleskConfig.two_factor_method}
                      onChange={(e) => setPleskConfig({ 
                        ...pleskConfig, 
                        two_factor_method: e.target.value as 'totp' | 'sms' | 'email' | 'none'
                      })}
                      label={t('wizard.2fa_method')}
                    >
                      <MenuItem value="totp">{t('wizard.2fa_totp')}</MenuItem>
                      <MenuItem value="sms">{t('wizard.2fa_sms')}</MenuItem>
                      <MenuItem value="email">{t('wizard.2fa_email')}</MenuItem>
                    </Select>
                  </FormControl>
                  
                  {pleskConfig.two_factor_method === 'totp' && (
                    <Alert severity="info" sx={{ mt: 2 }}>
                      {t('wizard.2fa_totp_info')}
                    </Alert>
                  )}
                  
                  <Typography variant="body2" color="textSecondary" sx={{ mt: 2 }}>
                    {t('wizard.2fa_tunnel_info')}
                  </Typography>
                </Box>
              )}
            </CardContent>
          </Card>
        </Grid>
      </Grid>

      <Box sx={{ mt: 3, display: 'flex', alignItems: 'center', gap: 2 }}>
        <Button
          variant="outlined"
          onClick={testPleskConnection}
          disabled={loading || !pleskConfig.host}
          startIcon={loading ? <CircularProgress size={20} /> : null}
        >
          {t('wizard.test_connection')}
        </Button>
        {testResults.plesk !== null && (
          <Alert severity={testResults.plesk ? 'success' : 'error'} sx={{ flex: 1 }}>
            {testResults.plesk ? t('wizard.connection_ok') : t('wizard.connection_failed')}
          </Alert>
        )}
      </Box>
      
      {/* 2FA Dialog */}
      <Dialog open={twoFactorDialogOpen} onClose={cancelTwoFactor} maxWidth="sm" fullWidth>
        <DialogTitle>
          <Box sx={{ display: 'flex', alignItems: 'center' }}>
            <KeyIcon sx={{ mr: 1 }} />
            {t('wizard.2fa_title')}
          </Box>
        </DialogTitle>
        <DialogContent>
          {twoFactorWaiting && (
            <Box sx={{ mb: 2 }}>
              <Alert severity="info" icon={<SecurityIcon />}>
                {twoFactorPrompt}
              </Alert>
              <Chip 
                label={t('wizard.2fa_channel') + ': ' + twoFactorChannel} 
                size="small" 
                sx={{ mt: 1 }} 
              />
            </Box>
          )}
          
          <TextField
            fullWidth
            autoFocus
            label={t('wizard.2fa_code')}
            value={twoFactorCode}
            onChange={(e) => setTwoFactorCode(e.target.value.replace(/\D/g, '').slice(0, 6))}
            margin="normal"
            placeholder="000000"
            inputProps={{ 
              maxLength: 6, 
              style: { fontSize: '2rem', textAlign: 'center', letterSpacing: '0.5rem' }
            }}
            onKeyPress={(e) => {
              if (e.key === 'Enter') {
                submitTwoFactorCode();
              }
            }}
          />
          
          <Typography variant="body2" color="textSecondary" sx={{ mt: 2 }}>
            {t('wizard.2fa_code_help')}
          </Typography>
        </DialogContent>
        <DialogActions>
          <Button onClick={cancelTwoFactor}>
            {t('wizard.cancel')}
          </Button>
          <Button 
            variant="contained" 
            onClick={submitTwoFactorCode}
            disabled={twoFactorCode.length < 4 || loading}
            startIcon={loading ? <CircularProgress size={20} /> : null}
          >
            {t('wizard.2fa_verify')}
          </Button>
        </DialogActions>
      </Dialog>
    </Box>
  );

  const renderSapStep = () => (
    <Box>
      <Typography variant="h5" gutterBottom sx={{ fontWeight: 600 }}>
        {t('wizard.sap_config')}
      </Typography>
      <Typography variant="body2" color="textSecondary" sx={{ mb: 3 }}>
        {t('wizard.sap_config_desc')}
      </Typography>

      <Grid container spacing={2}>
        <Grid item xs={12} md={8}>
          <TextField
            fullWidth
            label={t('wizard.sap_host')}
            placeholder="sap.example.com"
            value={sapConfig.host}
            onChange={(e) => setSapConfig({ ...sapConfig, host: e.target.value })}
            margin="normal"
          />
        </Grid>
        <Grid item xs={12} md={4}>
          <TextField
            fullWidth
            label={t('wizard.port')}
            type="number"
            value={sapConfig.port}
            onChange={(e) => setSapConfig({ ...sapConfig, port: parseInt(e.target.value) || 50000 })}
            margin="normal"
          />
        </Grid>
        <Grid item xs={12}>
          <TextField
            fullWidth
            label={t('wizard.company_db')}
            placeholder="SBODEMO_DE"
            value={sapConfig.company_db}
            onChange={(e) => setSapConfig({ ...sapConfig, company_db: e.target.value })}
            margin="normal"
            helperText={t('wizard.company_db_helper')}
          />
        </Grid>
        <Grid item xs={12} md={6}>
          <TextField
            fullWidth
            label={t('wizard.username')}
            value={sapConfig.username}
            onChange={(e) => setSapConfig({ ...sapConfig, username: e.target.value })}
            margin="normal"
          />
        </Grid>
        <Grid item xs={12} md={6}>
          <TextField
            fullWidth
            label={t('wizard.password')}
            type={showSapPassword ? 'text' : 'password'}
            value={sapConfig.password}
            onChange={(e) => setSapConfig({ ...sapConfig, password: e.target.value })}
            margin="normal"
            InputProps={{
              endAdornment: (
                <InputAdornment position="end">
                  <IconButton onClick={() => setShowSapPassword(!showSapPassword)} edge="end">
                    {showSapPassword ? <VisibilityOff /> : <Visibility />}
                  </IconButton>
                </InputAdornment>
              ),
            }}
          />
        </Grid>
      </Grid>

      <Box sx={{ mt: 3, display: 'flex', alignItems: 'center', gap: 2 }}>
        <Button
          variant="outlined"
          onClick={testSapConnection}
          disabled={loading || !sapConfig.host || !sapConfig.company_db}
          startIcon={loading ? <CircularProgress size={20} /> : null}
        >
          {t('wizard.test_connection')}
        </Button>
        {testResults.sap !== null && (
          <Alert severity={testResults.sap ? 'success' : 'error'} sx={{ flex: 1 }}>
            {testResults.sap ? t('wizard.connection_ok') : t('wizard.connection_failed')}
          </Alert>
        )}
      </Box>
    </Box>
  );

  const renderSyncStep = () => (
    <Box>
      <Typography variant="h5" gutterBottom sx={{ fontWeight: 600 }}>
        {t('wizard.sync_config')}
      </Typography>
      <Typography variant="body2" color="textSecondary" sx={{ mb: 3 }}>
        {t('wizard.sync_config_desc')}
      </Typography>

      <Grid container spacing={3}>
        <Grid item xs={12} md={6}>
          <FormControl fullWidth margin="normal">
            <InputLabel>{t('wizard.sync_direction')}</InputLabel>
            <Select
              value={syncConfig.sync_direction}
              onChange={(e) => setSyncConfig({ ...syncConfig, sync_direction: e.target.value })}
              label={t('wizard.sync_direction')}
            >
              <MenuItem value="sap_to_plesk">SAP → Plesk</MenuItem>
              <MenuItem value="plesk_to_sap">Plesk → SAP</MenuItem>
              <MenuItem value="bidirectional">{t('wizard.bidirectional')}</MenuItem>
            </Select>
          </FormControl>
        </Grid>
        <Grid item xs={12} md={6}>
          <TextField
            fullWidth
            label={t('wizard.sync_interval')}
            type="number"
            value={syncConfig.sync_interval_minutes}
            onChange={(e) => setSyncConfig({ ...syncConfig, sync_interval_minutes: parseInt(e.target.value) || 60 })}
            margin="normal"
            InputProps={{
              endAdornment: <InputAdornment position="end">{t('wizard.minutes')}</InputAdornment>,
            }}
          />
        </Grid>
        <Grid item xs={12} md={6}>
          <FormControl fullWidth margin="normal">
            <InputLabel>{t('wizard.conflict_resolution')}</InputLabel>
            <Select
              value={syncConfig.conflict_resolution}
              onChange={(e) => setSyncConfig({ ...syncConfig, conflict_resolution: e.target.value })}
              label={t('wizard.conflict_resolution')}
            >
              <MenuItem value="sap_priority">{t('wizard.sap_priority')}</MenuItem>
              <MenuItem value="plesk_priority">{t('wizard.plesk_priority')}</MenuItem>
              <MenuItem value="timestamp_based">{t('wizard.timestamp_based')}</MenuItem>
              <MenuItem value="manual">{t('wizard.manual')}</MenuItem>
            </Select>
          </FormControl>
        </Grid>
      </Grid>
    </Box>
  );

  const renderCompleteStep = () => (
    <Box textAlign="center">
      <Box
        sx={{
          width: 80,
          height: 80,
          borderRadius: '50%',
          background: 'linear-gradient(135deg, #10b981 0%, #059669 100%)',
          display: 'flex',
          alignItems: 'center',
          justifyContent: 'center',
          mx: 'auto',
          mb: 3,
        }}
      >
        <CheckIcon sx={{ fontSize: 48, color: 'white' }} />
      </Box>
      <Typography variant="h4" gutterBottom sx={{ fontWeight: 700 }}>
        {t('wizard.setup_complete')}
      </Typography>
      <Typography variant="body1" color="textSecondary" sx={{ mb: 4, maxWidth: 500, mx: 'auto' }}>
        {t('wizard.setup_complete_desc')}
      </Typography>
      
      <Button variant="contained" size="large" href="/dashboard">
        {t('wizard.go_dashboard')}
      </Button>
    </Box>
  );

  const renderStepContent = () => {
    switch (activeStep) {
      case 0:
        return renderWelcomeStep();
      case 1:
        return renderPleskStep();
      case 2:
        return renderSapStep();
      case 3:
        return renderSyncStep();
      case 4:
        return renderCompleteStep();
      default:
        return null;
    }
  };

  return (
    <Box sx={{ maxWidth: 900, mx: 'auto', p: 3 }}>
      <Card>
        <CardContent sx={{ p: 4 }}>
          <Stepper activeStep={activeStep} sx={{ mb: 4 }}>
            {steps.map((step) => (
              <Step key={step.label}>
                <StepLabel>{step.label}</StepLabel>
              </Step>
            ))}
          </Stepper>

          <Box sx={{ minHeight: 400 }}>
            {renderStepContent()}
          </Box>

          {activeStep < steps.length - 1 && (
            <Box sx={{ display: 'flex', justifyContent: 'space-between', mt: 4 }}>
              <Button
                disabled={activeStep === 0}
                onClick={handleBack}
                variant="outlined"
              >
                {t('wizard.back')}
              </Button>
              <Button
                variant="contained"
                onClick={activeStep === steps.length - 2 ? saveConfiguration : handleNext}
                disabled={loading}
                startIcon={loading ? <CircularProgress size={20} /> : null}
              >
                {activeStep === steps.length - 2 ? t('wizard.complete_setup') : t('wizard.next')}
              </Button>
            </Box>
          )}
        </CardContent>
      </Card>
    </Box>
  );
};

export default SetupWizardPage;
