import React, { useState, useEffect } from 'react';
import {
  Box,
  Card,
  CardContent,
  Typography,
  TextField,
  Button,
  Alert,
  CircularProgress,
  Link,
  Divider,
  InputAdornment,
  Dialog,
  DialogTitle,
  DialogContent,
  DialogActions,
  Checkbox,
  FormControlLabel,
  Grid
} from '@mui/material';
import {
  Email as EmailIcon,
  Security as SecurityIcon,
  CheckCircle as CheckCircleIcon,
  ErrorOutline as ErrorIcon,
  Refresh as RefreshIcon,
  DevicesOther as DevicesIcon
} from '@mui/icons-material';
import { useAuth } from 'hooks/AuthContext';
import { BackstoryPageProps } from './BackstoryTab';
import { useNavigate } from 'react-router-dom';

// Email Verification Component
const EmailVerificationPage = (props: BackstoryPageProps) => {
    const { verifyEmail, resendEmailVerification, getPendingVerificationEmail, isLoading, error } = useAuth();
    const navigate = useNavigate();
    const [verificationToken, setVerificationToken] = useState('');
  const [status, setStatus] = useState<'pending' | 'success' | 'error'>('pending');
  const [message, setMessage] = useState('');
  const [userType, setUserType] = useState<string>('');

  useEffect(() => {
    // Get token from URL parameters
    const urlParams = new URLSearchParams(window.location.search);
    const token = urlParams.get('token');
    
    if (token) {
      setVerificationToken(token);
      handleVerifyEmail(token);
    }
  }, []);

  const handleVerifyEmail = async (token: string) => {
    if (!token) {
      setStatus('error');
      setMessage('Invalid verification link');
      return;
    }

    try {
        const result = await verifyEmail({ token });

        if (result) {
        setStatus('success');
            setMessage(result.message);
            setUserType(result.userType);
        
        // Redirect to login after 3 seconds
        setTimeout(() => {
            navigate('/login');
        }, 3000);
      } else {
        setStatus('error');
            setMessage('Email verification failed');
      }
    } catch (error) {
      setStatus('error');
        setMessage('Email verification failed');
    }
  };

  const handleResendVerification = async () => {
      const email = getPendingVerificationEmail();
      if (!email) {
          setMessage('No pending verification email found.');
          return;
      }

    try {
        const success = await resendEmailVerification(email);
        if (success) {
            setMessage('Verification email sent successfully!');
      }
    } catch (error) {
        setMessage('Failed to resend verification email.');
    }
  };

  return (
    <Box
      sx={{
        minHeight: '100vh',
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'center',
        bgcolor: 'grey.50',
        p: 2
      }}
    >
      <Card sx={{ maxWidth: 500, width: '100%' }}>
        <CardContent sx={{ p: 4 }}>
          <Box textAlign="center" mb={3}>
            {status === 'pending' && (
              <>
                <EmailIcon sx={{ fontSize: 64, color: 'primary.main', mb: 2 }} />
                <Typography variant="h4" gutterBottom>
                  Verifying Email
                </Typography>
                <Typography color="text.secondary">
                  Please wait while we verify your email address...
                </Typography>
              </>
            )}

            {status === 'success' && (
              <>
                <CheckCircleIcon sx={{ fontSize: 64, color: 'success.main', mb: 2 }} />
                <Typography variant="h4" gutterBottom color="success.main">
                  Email Verified!
                </Typography>
                <Typography color="text.secondary">
                  Your {userType} account has been successfully activated.
                </Typography>
              </>
            )}

            {status === 'error' && (
              <>
                <ErrorIcon sx={{ fontSize: 64, color: 'error.main', mb: 2 }} />
                <Typography variant="h4" gutterBottom color="error.main">
                  Verification Failed
                </Typography>
                <Typography color="text.secondary">
                  We couldn't verify your email address.
                </Typography>
              </>
            )}
          </Box>

                  {isLoading && (
            <Box display="flex" justifyContent="center" my={3}>
              <CircularProgress />
            </Box>
          )}

                  {(message || error) && (
            <Alert 
              severity={status === 'success' ? 'success' : status === 'error' ? 'error' : 'info'}
              sx={{ mt: 2 }}
            >
                          {message || error}
            </Alert>
          )}

          {status === 'success' && (
            <Box mt={3} textAlign="center">
              <Typography variant="body2" color="text.secondary" mb={2}>
                You will be redirected to the login page in a few seconds...
              </Typography>
              <Button 
                variant="contained" 
                              onClick={() => navigate('/login')}
                fullWidth
              >
                Go to Login
              </Button>
            </Box>
          )}

          {status === 'error' && (
            <Box mt={3}>
              <Button
                variant="outlined"
                onClick={handleResendVerification}
                              disabled={isLoading}
                startIcon={<RefreshIcon />}
                fullWidth
                sx={{ mb: 2 }}
              >
                Resend Verification Email
              </Button>
              <Button
                variant="contained"
                              onClick={() => navigate('/login')}
                fullWidth
              >
                Back to Login
              </Button>
            </Box>
          )}
        </CardContent>
      </Card>
    </Box>
  );
}

// MFA Verification Component
interface MFAVerificationDialogProps {
    open: boolean;
    onClose: () => void;
    onVerificationSuccess: (authData: any) => void;
}
const MFAVerificationDialog = (props: MFAVerificationDialogProps) => {
    const {
        open,
        onClose,
        onVerificationSuccess
    } = props;
    const { verifyMFA, resendMFACode, clearMFA, mfaResponse, isLoading, error } = useAuth();
  const [code, setCode] = useState('');
  const [rememberDevice, setRememberDevice] = useState(false);
    const [localError, setLocalError] = useState('');
  const [timeLeft, setTimeLeft] = useState(600); // 10 minutes in seconds
    const [errorMessage, setErrorMessage] = useState<string | null>(null);

    useEffect(() => {
        if (!error) {
            return;
        }
        /* Remove 'HTTP .*: ' from error string */
        const jsonStr = error.replace(/^[^{]*/, '');
        const data = JSON.parse(jsonStr);
        setErrorMessage(data.error.message);

    }, [error]);

  useEffect(() => {
    if (!open) return;

    const timer = setInterval(() => {
      setTimeLeft((prev) => {
        if (prev <= 1) {
          clearInterval(timer);
            setLocalError('MFA code has expired. Please try logging in again.');
          return 0;
        }
        return prev - 1;
      });
    }, 1000);

    return () => clearInterval(timer);
  }, [open]);

  const formatTime = (seconds: number) => {
    const mins = Math.floor(seconds / 60);
    const secs = seconds % 60;
    return `${mins}:${secs.toString().padStart(2, '0')}`;
  };

  const handleVerifyMFA = async () => {
    if (!code || code.length !== 6) {
        setLocalError('Please enter a valid 6-digit code');
      return;
    }

      if (!mfaResponse || !mfaResponse.mfaData) {
          setLocalError('MFA data not available');
          return;
      }

      setLocalError('');

    try {
        const success = await verifyMFA({
            email: mfaResponse.mfaData.email,
            code,
            deviceId: mfaResponse.mfaData.deviceId,
            rememberDevice,
      });

        if (success) {
            onVerificationSuccess({ success: true });
            onClose();
      }
    } catch (error) {
        setLocalError('Verification failed. Please try again.');
    }
  };

  const handleResendCode = async () => {
      if (!mfaResponse || !mfaResponse.mfaData) {
          setLocalError('MFA data not available');
          return;
      }

    try {
        const success = await resendMFACode(mfaResponse.mfaData.email, mfaResponse.mfaData.deviceId, mfaResponse.mfaData.deviceName);
        if (success) {
        setTimeLeft(600); // Reset timer
            setLocalError('');
        alert('New verification code sent to your email');
      }
    } catch (error) {
        setLocalError('Failed to resend code');
    }
  };

    const handleClose = () => {
        clearMFA();
        onClose();
    };

    if (!mfaResponse || !mfaResponse.mfaData) return null;

  return (
      <Dialog open={open} onClose={handleClose} maxWidth="sm" fullWidth>
      <DialogTitle>
        <Box display="flex" alignItems="center" gap={1}>
          <SecurityIcon color="primary" />
          <Typography variant="h6">
            Verify Your Identity
          </Typography>
        </Box>
      </DialogTitle>
      
      <DialogContent>
        <Alert severity="info" sx={{ mb: 3 }}>
                  We've detected a login from a new device: <strong>{mfaResponse.mfaData.deviceName}</strong>
        </Alert>

        <Typography variant="body1" gutterBottom>
                  We've sent a 6-digit verification code to:
        </Typography>
        <Typography variant="h6" color="primary" gutterBottom>
                  {mfaResponse.mfaData.email}
        </Typography>

        <TextField
          fullWidth
          label="Enter 6-digit code"
          value={code}
          onChange={(e) => {
            const value = e.target.value.replace(/\D/g, '').slice(0, 6);
            setCode(value);
              setLocalError('');
          }}
          placeholder="000000"
          inputProps={{
            maxLength: 6,
            style: { 
              fontSize: 24, 
              textAlign: 'center', 
              letterSpacing: 8 
            }
          }}
          sx={{ mt: 2, mb: 2 }}
                  error={!!(localError || errorMessage)}
                  helperText={localError || errorMessage}
        />

        <Box display="flex" justifyContent="space-between" alignItems="center" mb={2}>
          <Typography variant="body2" color="text.secondary">
            Code expires in: {formatTime(timeLeft)}
          </Typography>
          <Button 
            size="small" 
            onClick={handleResendCode} 
                      disabled={isLoading || timeLeft > 540} // Allow resend after 1 minute
          >
            Resend Code
          </Button>
        </Box>

        <FormControlLabel
          control={
            <Checkbox
              checked={rememberDevice}
              onChange={(e) => setRememberDevice(e.target.checked)}
            />
          }
          label="Remember this device for 90 days"
        />

        <Alert severity="warning" sx={{ mt: 2 }}>
          <Typography variant="body2">
            If you didn't attempt to log in, please change your password immediately.
          </Typography>
        </Alert>
      </DialogContent>

      <DialogActions sx={{ p: 3 }}>
              <Button onClick={handleClose} disabled={isLoading}>
          Cancel
        </Button>
        <Button
          variant="contained"
          onClick={handleVerifyMFA}
                  disabled={isLoading || !code || code.length !== 6 || timeLeft === 0}
        >
                  {isLoading ? <CircularProgress size={20} /> : 'Verify'}
        </Button>
      </DialogActions>
    </Dialog>
  );
}

// Enhanced Registration Success Component
const RegistrationSuccessDialog = ({ 
  open, 
  onClose, 
  email, 
  userType 
}: {
  open: boolean;
  onClose: () => void;
  email: string;
  userType: string;
}) => {
    const { resendEmailVerification, isLoading } = useAuth();
  const [resendMessage, setResendMessage] = useState('');

    const handleResendVerification = async () => {
    try {
        const success = await resendEmailVerification(email);
        if (success) {
            setResendMessage('Verification email sent!');
        }
    } catch (error: any) {
        setResendMessage(error?.message || 'Network error. Please try again.');
    }
  };

  return (
    <Dialog open={open} onClose={onClose} maxWidth="sm" fullWidth>
      <DialogContent sx={{ textAlign: 'center', p: 4 }}>
        <EmailIcon sx={{ fontSize: 64, color: 'primary.main', mb: 2 }} />
        
        <Typography variant="h5" gutterBottom>
          Check Your Email
        </Typography>
        
        <Typography variant="body1" color="text.secondary" paragraph>
          We've sent a verification link to:
        </Typography>
        
        <Typography variant="h6" color="primary" gutterBottom>
          {email}
        </Typography>
        
        <Alert severity="info" sx={{ mt: 2, mb: 3, textAlign: 'left' }}>
          <Typography variant="body2">
            <strong>Next steps:</strong>
            <br />
            1. Check your email inbox (and spam folder)
            <br />
            2. Click the verification link
            <br />
            3. Your {userType} account will be activated
          </Typography>
        </Alert>

        {resendMessage && (
          <Alert 
            severity={resendMessage.includes('sent') ? 'success' : 'error'} 
            sx={{ mb: 2 }}
          >
            {resendMessage}
          </Alert>
        )}
      </DialogContent>

      <DialogActions sx={{ p: 3, justifyContent: 'space-between' }}>
        <Button
          onClick={handleResendVerification}
                  disabled={isLoading}
                  startIcon={isLoading ? <CircularProgress size={16} /> : <RefreshIcon />}
        >
          Resend Email
        </Button>
        <Button variant="contained" onClick={onClose}>
          Got It
        </Button>
      </DialogActions>
    </Dialog>
  );
}

// Enhanced Login Component with MFA Support
const LoginForm = () => {
    const { login, mfaResponse, isLoading, error } = useAuth();
    const [email, setEmail] = useState('');
    const [password, setPassword] = useState('');
    const [errorMessage, setErrorMessage] = useState<string | null>(null);

    useEffect(() => {
        if (!error) {
            return;
        }
        /* Remove 'HTTP .*: ' from error string */
        const jsonStr = error.replace(/^[^{]*/, '');
        const data = JSON.parse(jsonStr);
        setErrorMessage(data.error.message);

    }, [error]);

    const handleLogin = async (e: React.FormEvent) => {
        e.preventDefault();

        const success = await login({
            login: email,
            password
        });

        console.log(`login success: ${success}`);
        if (success) {
            // Redirect based on user type - this could be handled in AuthContext
            // or by a higher-level component that listens to auth state changes
            handleLoginSuccess();
        }
  };

  const handleMFASuccess = (authData: any) => {
      handleLoginSuccess();
  };

    const handleLoginSuccess = () => {
        // This could be handled by a router or parent component
        // For now, just showing the pattern
        console.log('Login successful - redirect to dashboard');
  };

  return (
    <Box component="form" onSubmit={handleLogin} sx={{ mt: 1 }}>
      <TextField
        margin="normal"
        required
        fullWidth
        label="Email or Username"
        value={email}
        onChange={(e) => setEmail(e.target.value)}
        autoComplete="email"
        autoFocus
      />
      <TextField
        margin="normal"
        required
        fullWidth
        label="Password"
        type="password"
        value={password}
        onChange={(e) => setPassword(e.target.value)}
        autoComplete="current-password"
      />

          {errorMessage && (
        <Alert severity="error" sx={{ mt: 2 }}>
                  {errorMessage}
        </Alert>
      )}

      <Button
        type="submit"
        fullWidth
        variant="contained"
              disabled={isLoading}
        sx={{ mt: 3, mb: 2 }}
      >
              {isLoading ? <CircularProgress size={20} /> : 'Sign In'}
      </Button>

          {/* MFA Dialog */}
          <MFAVerificationDialog
              open={mfaResponse?.mfaRequired || false}
              onClose={() => { }} // This will be handled by clearMFA in the dialog
              onVerificationSuccess={handleMFASuccess}
          />
    </Box>
  );
}

// Device Management Component
const TrustedDevicesManager = () => {
  const [devices, setDevices] = useState<any[]>([]);
  const [loading, setLoading] = useState(true);

  // This would need API endpoints to manage trusted devices
  useEffect(() => {
    // Load trusted devices
    setLoading(false);
  }, []);

  return (
    <Card>
      <CardContent>
        <Typography variant="h6" gutterBottom>
          <DevicesIcon sx={{ mr: 1, verticalAlign: 'middle' }} />
          Trusted Devices
        </Typography>
        
        <Typography variant="body2" color="text.secondary" paragraph>
          Manage devices that you've marked as trusted. You won't need to verify 
          your identity when signing in from these devices.
        </Typography>

        {devices.length === 0 ? (
          <Alert severity="info">
            No trusted devices yet. When you log in from a new device and choose 
            to remember it, it will appear here.
          </Alert>
        ) : (
          <Grid container spacing={2}>
            {devices.map((device, index) => (
              <Grid key={index} size={{ xs: 12, md: 6 }}>
                <Card variant="outlined">
                  <CardContent>
                    <Typography variant="subtitle1">
                      {device.deviceName}
                    </Typography>
                    <Typography variant="body2" color="text.secondary">
                      Added: {new Date(device.addedAt).toLocaleDateString()}
                    </Typography>
                    <Typography variant="body2" color="text.secondary">
                      Last used: {new Date(device.lastUsed).toLocaleDateString()}
                    </Typography>
                    <Button 
                      size="small" 
                      color="error" 
                      sx={{ mt: 1 }}
                      onClick={() => {
                        // Remove device
                      }}
                    >
                      Remove
                    </Button>
                  </CardContent>
                </Card>
              </Grid>
            ))}
          </Grid>
        )}
      </CardContent>
    </Card>
  );
}

export { EmailVerificationPage, MFAVerificationDialog, TrustedDevicesManager, RegistrationSuccessDialog, LoginForm };