import { useState, useEffect } from 'react';
import {
  Box,
  Card,
  CardContent,
  Typography,
  Button,
  TextField,
  Dialog,
  DialogTitle,
  DialogContent,
  DialogActions,
  Alert,
  AlertTitle,
  Chip,
  Grid,
  Divider,
  List,
  ListItem,
  ListItemText,
  IconButton,
  InputAdornment,
  CircularProgress
} from '@mui/material';
import {
  Security,
  QrCode2,
  Download,
  Visibility,
  VisibilityOff,
  Check,
  Close,
  Refresh
} from '@mui/icons-material';
import axios from 'axios';
import { useAuthStore } from '../store/authStore';

const TwoFactorSettings = () => {
  const token = useAuthStore((state) => state.token);
  const [status, setStatus] = useState(null);
  const [loading, setLoading] = useState(true);
  const [setupDialogOpen, setSetupDialogOpen] = useState(false);
  const [disableDialogOpen, setDisableDialogOpen] = useState(false);
  const [backupCodesDialogOpen, setBackupCodesDialogOpen] = useState(false);
  
  // Setup flow state
  const [qrCode, setQrCode] = useState('');
  const [secret, setSecret] = useState('');
  const [verificationCode, setVerificationCode] = useState('');
  const [backupCodes, setBackupCodes] = useState([]);
  const [setupStep, setSetupStep] = useState(1); // 1: QR, 2: Verify, 3: Backup Codes
  
  // Disable flow state
  const [disablePassword, setDisablePassword] = useState('');
  const [disableCode, setDisableCode] = useState('');
  const [showPassword, setShowPassword] = useState(false);
  
  // Backup codes regeneration
  const [regenPassword, setRegenPassword] = useState('');
  const [regenCode, setRegenCode] = useState('');
  const [existingBackupCodes, setExistingBackupCodes] = useState([]);
  
  const [error, setError] = useState('');
  const [success, setSuccess] = useState('');

  const fetchStatus = async () => {
    try {
      setLoading(true);
      const response = await axios.get('/api/two-factor/status', {
        headers: { Authorization: `Bearer ${token}` }
      });
      setStatus(response.data);
    } catch (err) {
      console.error('Failed to fetch 2FA status:', err);
    } finally {
      setLoading(false);
    }
  };

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

  const handleStartSetup = async () => {
    try {
      setError('');
      const response = await axios.post(
        '/api/two-factor/setup',
        {},
        { headers: { Authorization: `Bearer ${token}` } }
      );
      
      setQrCode(response.data.qrCode);
      setSecret(response.data.secret);
      setSetupStep(1);
      setSetupDialogOpen(true);
    } catch (err) {
      setError(err.response?.data?.error || 'Failed to start 2FA setup');
    }
  };

  const handleVerifyAndEnable = async () => {
    try {
      setError('');
      const response = await axios.post(
        '/api/two-factor/enable',
        { token: verificationCode },
        { headers: { Authorization: `Bearer ${token}` } }
      );
      
      setBackupCodes(response.data.backupCodes);
      setSetupStep(3);
      setSuccess('2FA enabled successfully!');
      await fetchStatus();
    } catch (err) {
      setError(err.response?.data?.error || 'Invalid verification code');
    }
  };

  const handleDisable2FA = async () => {
    try {
      setError('');
      await axios.post(
        '/api/two-factor/disable',
        { password: disablePassword, token: disableCode },
        { headers: { Authorization: `Bearer ${token}` } }
      );
      
      setSuccess('2FA disabled successfully');
      setDisableDialogOpen(false);
      setDisablePassword('');
      setDisableCode('');
      await fetchStatus();
    } catch (err) {
      setError(err.response?.data?.error || 'Failed to disable 2FA');
    }
  };

  const handleRegenerateBackupCodes = async () => {
    try {
      setError('');
      const response = await axios.post(
        '/api/two-factor/backup-codes/regenerate',
        { password: regenPassword, token: regenCode },
        { headers: { Authorization: `Bearer ${token}` } }
      );
      
      setExistingBackupCodes(response.data.backupCodes);
      setSuccess('Backup codes regenerated successfully');
      setRegenPassword('');
      setRegenCode('');
      await fetchStatus();
    } catch (err) {
      setError(err.response?.data?.error || 'Failed to regenerate backup codes');
    }
  };

  const handleDownloadBackupCodes = () => {
    const codes = backupCodes.length > 0 ? backupCodes : existingBackupCodes;
    const text = `StreamFlow - Two-Factor Authentication Backup Codes\n\n` +
      `Generated: ${new Date().toLocaleString()}\n\n` +
      `These are your backup codes. Keep them safe!\n` +
      `Each code can be used only once.\n\n` +
      codes.map((code, i) => `${i + 1}. ${code}`).join('\n');
    
    const blob = new Blob([text], { type: 'text/plain' });
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = 'Streamflow-backup-codes.txt';
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
    URL.revokeObjectURL(url);
  };

  const handleCloseSetup = () => {
    setSetupDialogOpen(false);
    setVerificationCode('');
    setSetupStep(1);
    setBackupCodes([]);
    setError('');
  };

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

  return (
    <Box>
      {(error || success) && (
        <Alert 
          severity={error ? 'error' : 'success'} 
          onClose={() => { setError(''); setSuccess(''); }}
          sx={{ mb: 2 }}
        >
          {error || success}
        </Alert>
      )}

      <Card>
        <CardContent>
          <Box sx={{ display: 'flex', alignItems: 'center', mb: 2 }}>
            <Security sx={{ fontSize: 40, mr: 2, color: 'primary.main' }} />
            <Box>
              <Typography variant="h5" gutterBottom>
                Two-Factor Authentication
              </Typography>
              <Chip 
                label={status?.enabled ? 'Enabled' : 'Disabled'} 
                color={status?.enabled ? 'success' : 'default'}
                icon={status?.enabled ? <Check /> : <Close />}
              />
            </Box>
          </Box>

          <Divider sx={{ my: 2 }} />

          <Typography variant="body2" color="text.secondary" paragraph>
            Two-factor authentication adds an extra layer of security to your account.
            You'll need to enter a 6-digit code from your authenticator app when logging in.
          </Typography>

          {!status?.enabled ? (
            <Box>
              <Alert severity="info" sx={{ mb: 2 }}>
                <AlertTitle>Enable 2FA</AlertTitle>
                Scan the QR code with an authenticator app like Google Authenticator,
                Microsoft Authenticator, or Authy.
              </Alert>
              <Button
                variant="contained"
                startIcon={<QrCode2 />}
                onClick={handleStartSetup}
                size="large"
              >
                Enable Two-Factor Authentication
              </Button>
            </Box>
          ) : (
            <Box>
              <Grid container spacing={2} sx={{ mb: 3 }}>
                <Grid item xs={6}>
                  <Card variant="outlined">
                    <CardContent>
                      <Typography variant="subtitle2" color="text.secondary">
                        Backup Codes
                      </Typography>
                      <Typography variant="h4">
                        {status.backupCodesUnused} / {status.backupCodesTotal}
                      </Typography>
                      <Typography variant="caption" color="text.secondary">
                        Unused codes remaining
                      </Typography>
                    </CardContent>
                  </Card>
                </Grid>
              </Grid>

              <Box sx={{ display: 'flex', gap: 2, flexWrap: 'wrap' }}>
                <Button
                  variant="outlined"
                  color="error"
                  onClick={() => setDisableDialogOpen(true)}
                >
                  Disable 2FA
                </Button>
                <Button
                  variant="outlined"
                  startIcon={<Refresh />}
                  onClick={() => setBackupCodesDialogOpen(true)}
                >
                  Regenerate Backup Codes
                </Button>
              </Box>
            </Box>
          )}
        </CardContent>
      </Card>

      {/* Setup Dialog */}
      <Dialog 
        open={setupDialogOpen} 
        onClose={handleCloseSetup}
        maxWidth="sm"
        fullWidth
      >
        <DialogTitle>
          Enable Two-Factor Authentication - Step {setupStep} of 3
        </DialogTitle>
        <DialogContent>
          {setupStep === 1 && (
            <Box>
              <Box sx={{ textAlign: 'center', mb: 2 }}>
                <svg width="80" height="80" viewBox="0 0 192 192" style={{ marginBottom: '10px' }}>
                  <defs>
                    <linearGradient id="qrGrad" x1="0%" y1="0%" x2="100%" y2="100%">
                      <stop offset="0%" style={{ stopColor: '#a855f7', stopOpacity: 1 }} />
                      <stop offset="100%" style={{ stopColor: '#3b82f6', stopOpacity: 1 }} />
                    </linearGradient>
                  </defs>
                  <path d="M 72 53 L 72 139 L 139 96 Z" fill="url(#qrGrad)" opacity="0.95" />
                  <path 
                    d="M 96 96 C 96 96, 80 83, 72 74 C 64 65, 56 55, 56 53 L 144 96 C 144 96, 141 101, 132 110 C 123 119, 111 131, 98 139" 
                    fill="none" 
                    stroke="url(#qrGrad)" 
                    strokeWidth="4" 
                    opacity="0.6" 
                    strokeLinecap="round"
                  />
                </svg>
                <Typography variant="h6" sx={{ fontWeight: 700, color: 'primary.main', mb: 1 }}>
                  StreamFlow IPTV
                </Typography>
              </Box>
              <Typography variant="body2" paragraph align="center" color="text.secondary">
                Scan this QR code with your authenticator app (Google Authenticator, Authy, Microsoft Authenticator, etc.):
              </Typography>
              <Box sx={{ 
                textAlign: 'center', 
                my: 2, 
                p: 2, 
                bgcolor: 'background.paper',
                borderRadius: 2,
                border: '2px solid',
                borderColor: 'divider'
              }}>
                <img src={qrCode} alt="StreamFlow 2FA QR Code" style={{ maxWidth: '280px', width: '100%' }} />
              </Box>
              <Alert severity="info" sx={{ mt: 2 }}>
                <AlertTitle>Can't scan the code?</AlertTitle>
                Enter this secret key manually in your authenticator app:<br />
                <Box component="span" sx={{ fontFamily: 'monospace', fontSize: '0.9rem', fontWeight: 600, userSelect: 'all' }}>
                  {secret}
                </Box>
              </Alert>
            </Box>
          )}

          {setupStep === 2 && (
            <Box>
              <Typography variant="body2" paragraph>
                Enter the 6-digit code from your authenticator app to verify:
              </Typography>
              <TextField
                fullWidth
                label="Verification Code"
                value={verificationCode}
                onChange={(e) => setVerificationCode(e.target.value.replace(/\D/g, '').slice(0, 6))}
                placeholder="000000"
                inputProps={{ maxLength: 6, style: { textAlign: 'center', fontSize: '24px', letterSpacing: '8px' } }}
                sx={{ my: 2 }}
              />
              {error && <Alert severity="error" sx={{ mt: 2 }}>{error}</Alert>}
            </Box>
          )}

          {setupStep === 3 && (
            <Box>
              <Alert severity="success" sx={{ mb: 2 }}>
                <AlertTitle>2FA Enabled Successfully!</AlertTitle>
                Save these backup codes in a safe place.
              </Alert>
              <Typography variant="body2" paragraph>
                Each code can be used only once to log in if you don't have access to your authenticator app.
              </Typography>
              <List sx={{ bgcolor: 'background.paper', border: 1, borderColor: 'divider', borderRadius: 1 }}>
                {backupCodes.map((code, index) => (
                  <ListItem key={index}>
                    <ListItemText 
                      primary={code}
                      primaryTypographyProps={{ fontFamily: 'monospace', fontSize: '18px' }}
                    />
                  </ListItem>
                ))}
              </List>
              <Button
                fullWidth
                variant="outlined"
                startIcon={<Download />}
                onClick={handleDownloadBackupCodes}
                sx={{ mt: 2 }}
              >
                Download Backup Codes
              </Button>
            </Box>
          )}
        </DialogContent>
        <DialogActions>
          {setupStep === 3 ? (
            <Button onClick={handleCloseSetup} variant="contained">
              Done
            </Button>
          ) : (
            <>
              <Button onClick={handleCloseSetup}>Cancel</Button>
              {setupStep === 1 && (
                <Button onClick={() => setSetupStep(2)} variant="contained">
                  Next
                </Button>
              )}
              {setupStep === 2 && (
                <Button 
                  onClick={handleVerifyAndEnable} 
                  variant="contained"
                  disabled={verificationCode.length !== 6}
                >
                  Verify & Enable
                </Button>
              )}
            </>
          )}
        </DialogActions>
      </Dialog>

      {/* Disable Dialog */}
      <Dialog open={disableDialogOpen} onClose={() => setDisableDialogOpen(false)}>
        <DialogTitle>Disable Two-Factor Authentication</DialogTitle>
        <DialogContent>
          <Alert severity="warning" sx={{ mb: 2 }}>
            Disabling 2FA will make your account less secure.
          </Alert>
          <TextField
            fullWidth
            type={showPassword ? 'text' : 'password'}
            label="Password"
            value={disablePassword}
            onChange={(e) => setDisablePassword(e.target.value)}
            sx={{ mb: 2 }}
            InputProps={{
              endAdornment: (
                <InputAdornment position="end">
                  <IconButton onClick={() => setShowPassword(!showPassword)} edge="end">
                    {showPassword ? <VisibilityOff /> : <Visibility />}
                  </IconButton>
                </InputAdornment>
              )
            }}
          />
          <TextField
            fullWidth
            label="2FA Code"
            value={disableCode}
            onChange={(e) => setDisableCode(e.target.value.replace(/\D/g, '').slice(0, 6))}
            placeholder="000000"
            inputProps={{ maxLength: 6 }}
          />
          {error && <Alert severity="error" sx={{ mt: 2 }}>{error}</Alert>}
        </DialogContent>
        <DialogActions>
          <Button onClick={() => setDisableDialogOpen(false)}>Cancel</Button>
          <Button 
            onClick={handleDisable2FA} 
            color="error" 
            variant="contained"
            disabled={!disablePassword || disableCode.length !== 6}
          >
            Disable 2FA
          </Button>
        </DialogActions>
      </Dialog>

      {/* Regenerate Backup Codes Dialog */}
      <Dialog open={backupCodesDialogOpen} onClose={() => setBackupCodesDialogOpen(false)}>
        <DialogTitle>Regenerate Backup Codes</DialogTitle>
        <DialogContent>
          <Alert severity="warning" sx={{ mb: 2 }}>
            This will invalidate all existing backup codes and generate new ones.
          </Alert>
          <TextField
            fullWidth
            type="password"
            label="Password"
            value={regenPassword}
            onChange={(e) => setRegenPassword(e.target.value)}
            sx={{ mb: 2 }}
          />
          <TextField
            fullWidth
            label="2FA Code"
            value={regenCode}
            onChange={(e) => setRegenCode(e.target.value.replace(/\D/g, '').slice(0, 6))}
            placeholder="000000"
            inputProps={{ maxLength: 6 }}
          />
          {existingBackupCodes.length > 0 && (
            <Box sx={{ mt: 2 }}>
              <Typography variant="subtitle2" gutterBottom>
                New Backup Codes:
              </Typography>
              <List sx={{ bgcolor: 'background.paper', border: 1, borderColor: 'divider', borderRadius: 1 }}>
                {existingBackupCodes.map((code, index) => (
                  <ListItem key={index}>
                    <ListItemText 
                      primary={code}
                      primaryTypographyProps={{ fontFamily: 'monospace' }}
                    />
                  </ListItem>
                ))}
              </List>
              <Button
                fullWidth
                variant="outlined"
                startIcon={<Download />}
                onClick={handleDownloadBackupCodes}
                sx={{ mt: 1 }}
              >
                Download Backup Codes
              </Button>
            </Box>
          )}
        </DialogContent>
        <DialogActions>
          <Button onClick={() => { setBackupCodesDialogOpen(false); setExistingBackupCodes([]); }}>
            Close
          </Button>
          {existingBackupCodes.length === 0 && (
            <Button 
              onClick={handleRegenerateBackupCodes} 
              color="primary" 
              variant="contained"
              disabled={!regenPassword || regenCode.length !== 6}
            >
              Regenerate
            </Button>
          )}
        </DialogActions>
      </Dialog>
    </Box>
  );
};

export default TwoFactorSettings;
