import React, { useState, useEffect } from 'react';
import { useNavigate, Link } from 'react-router-dom';
import {
  Box,
  TextField,
  Button,
  Typography,
  InputAdornment,
  IconButton,
  Checkbox,
  FormControlLabel,
  Grid
} from '@mui/material';
import { Visibility, VisibilityOff, PersonOutline, LockOutlined, ArrowForward } from '@mui/icons-material';
import { useTranslation } from 'react-i18next';
import axios from 'axios';
import { useAuthStore } from '../store/authStore';
import ChangePasswordDialog from '../components/ChangePasswordDialog';
import { useErrorNotification } from '../components/ErrorNotificationProvider';

function Login() {
  const { t } = useTranslation();
  const navigate = useNavigate();
  const login = useAuthStore((state) => state.login);
  const mustChangePassword = useAuthStore((state) => state.mustChangePassword);
  const { showError, showWarning, showSuccess } = useErrorNotification();
  const [showPassword, setShowPassword] = useState(false);
  const [rememberMe, setRememberMe] = useState(false);
  const [require2FA, setRequire2FA] = useState(false);
  const [tempToken, setTempToken] = useState('');
  const [twoFACode, setTwoFACode] = useState('');
  const [useBackupCode, setUseBackupCode] = useState(false);
  const [formData, setFormData] = useState({
    username: '',
    password: ''
  });

  const handleSubmit = async (e) => {
    e.preventDefault();

    try {
      const response = await axios.post('/api/auth/login', formData);
      
      // Check if account is locked
      if (response.data.locked) {
        showError(
          new Error(t('security.accountLockedMsg') + ' ' + t('security.remainingTime', { minutes: response.data.remainingMinutes })),
          { title: t('errors.auth.title'), duration: 8000 }
        );
        return;
      }

      // Check if password has expired
      if (response.data.passwordExpired) {
        showError(
          new Error(t('security.passwordExpiredMsg')),
          { title: t('errors.auth.title'), duration: 8000 }
        );
        return;
      }
      
      // Check if 2FA is required
      if (response.data.require2FA) {
        setRequire2FA(true);
        setTempToken(response.data.tempToken);
        // Show password warning if present
        if (response.data.passwordWarning) {
          showWarning(response.data.passwordWarning, {
            title: t('errors.auth.title'),
            duration: 10000
          });
        }
        return;
      }
      
      login(response.data.user, response.data.token);
      
      // Show password expiry warning if present
      if (response.data.passwordWarning) {
        showWarning(response.data.passwordWarning, {
          title: t('errors.auth.title'),
          duration: 10000
        });
      } else {
        // Show success message only if no warnings
        showSuccess(t('login.success') || 'Login successful', {
          duration: 3000
        });
      }
      
      // If password change is not required, navigate to home
      if (!response.data.user.must_change_password) {
        navigate('/');
      }
      // Otherwise, ChangePasswordDialog will show automatically
    } catch (err) {
      // Handle account lockout
      if (err.response?.status === 423) {
        showError(err, {
          title: t('errors.auth.title'),
          defaultMessage: err.response.data.error + ' ' + t('security.remainingTime', { minutes: err.response.data.remainingMinutes }),
          duration: 8000
        });
      }
      // Handle password expiry
      else if (err.response?.status === 403 && err.response.data.passwordExpired) {
        showError(err, {
          title: t('errors.auth.title'),
          defaultMessage: t('security.passwordExpiredMsg'),
          duration: 8000
        });
      }
      // Handle other errors
      else {
        showError(err, {
          title: t('errors.auth.title'),
          defaultMessage: t('error') || 'Login failed'
        });
      }
    }
  };

  const handleVerify2FA = async (e) => {
    if (e) e.preventDefault();

    try {
      const response = await axios.post('/api/auth/verify-2fa', {
        tempToken,
        code: twoFACode
      });
      
      login(response.data.user, response.data.token);
      
      showSuccess(t('twoFactor.verifySuccess') || '2FA verification successful', {
        duration: 3000
      });
      
      // If password change is not required, navigate to home
      if (!response.data.user.must_change_password) {
        navigate('/');
      }
    } catch (err) {
      showError(err, {
        title: t('twoFactor.verifyFailed') || '2FA Verification Failed',
        defaultMessage: t('twoFactor.invalidCode') || 'Invalid verification code'
      });
      setTwoFACode('');
    }
  };

  // Auto-submit when code is complete
  useEffect(() => {
    if (require2FA && twoFACode.length === (useBackupCode ? 8 : 6)) {
      handleVerify2FA();
    }
  }, [twoFACode, require2FA, useBackupCode]);

  const handlePasswordChanged = () => {
    navigate('/');
  };

  const handleChange = (e) => {
    setFormData({ ...formData, [e.target.name]: e.target.value });
  };

  return (
    <Box
      sx={{
        minHeight: '100vh',
        display: 'flex',
        background: '#000000'
      }}
    >
      {/* Left Side - Black with Logo */}
      <Grid container sx={{ height: '100vh' }}>
        <Grid 
          item 
          xs={12} 
          md={6} 
          sx={{
            display: 'flex',
            flexDirection: 'column',
            alignItems: 'center',
            justifyContent: 'center',
            background: '#000000',
            p: 4
          }}
        >
          {/* Logo */}
          <Box
            sx={{
              mb: 4,
              display: 'flex',
              flexDirection: 'column',
              alignItems: 'center'
            }}
          >
            <svg 
              width="200" 
              height="200" 
              viewBox="0 0 192 192" 
              style={{ marginBottom: '20px' }}
            >
              <defs>
                <linearGradient id="loginGrad" 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(#loginGrad)" 
                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(#loginGrad)" 
                strokeWidth="4" 
                opacity="0.6" 
                strokeLinecap="round"
              />
            </svg>
            <Typography 
              variant="h3" 
              sx={{ 
                color: '#ffffff',
                fontWeight: 700,
                letterSpacing: '0.5px'
              }}
            >
              StreamFlow
            </Typography>
          </Box>
        </Grid>

        {/* Right Side - Light Grey with Login Form */}
        <Grid 
          item 
          xs={12} 
          md={6}
          sx={{
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'center',
            background: 'linear-gradient(135deg, #f5f7fa 0%, #e8ecf1 100%)',
            p: 4
          }}
        >
          <Box
            sx={{
              maxWidth: 450,
              width: '100%',
              px: 4
            }}
          >
            <Typography 
              variant="h4" 
              sx={{ 
                color: '#2d3748',
                fontWeight: 700,
                mb: 4
              }}
            >
              {t('login.loginHere')}
            </Typography>

            {!require2FA ? (
              <form onSubmit={handleSubmit}>
                {/* Username Field */}
                <TextField
                  fullWidth
                  placeholder={t('username')}
                  name="username"
                  value={formData.username}
                  onChange={handleChange}
                  required
                  autoFocus
                  sx={{
                    mb: 2,
                    '& .MuiOutlinedInput-root': {
                      borderRadius: '12px',
                      backgroundColor: '#f7fafc',
                      '& fieldset': {
                        borderColor: '#e2e8f0'
                      },
                      '&:hover fieldset': {
                        borderColor: '#cbd5e0'
                      },
                      '&.Mui-focused fieldset': {
                        borderColor: '#a855f7'
                      }
                    },
                    '& .MuiOutlinedInput-input': {
                      color: '#2d3748',
                      '&::placeholder': {
                        color: '#a0aec0',
                        opacity: 1
                      }
                    }
                  }}
                  InputProps={{
                    startAdornment: (
                      <InputAdornment position="start">
                        <PersonOutline sx={{ color: '#718096' }} />
                      </InputAdornment>
                    )
                  }}
                />

                {/* Password Field */}
                <TextField
                  fullWidth
                  placeholder={t('password')}
                  name="password"
                  type={showPassword ? 'text' : 'password'}
                  value={formData.password}
                  onChange={handleChange}
                  required
                  sx={{
                    mb: 2,
                    '& .MuiOutlinedInput-root': {
                      borderRadius: '12px',
                      backgroundColor: '#f7fafc',
                      '& fieldset': {
                        borderColor: '#e2e8f0'
                      },
                      '&:hover fieldset': {
                        borderColor: '#cbd5e0'
                      },
                      '&.Mui-focused fieldset': {
                        borderColor: '#a855f7'
                      }
                    },
                    '& .MuiOutlinedInput-input': {
                      color: '#2d3748',
                      '&::placeholder': {
                        color: '#a0aec0',
                        opacity: 1
                      }
                    }
                  }}
                  InputProps={{
                    startAdornment: (
                      <InputAdornment position="start">
                        <LockOutlined sx={{ color: '#718096' }} />
                      </InputAdornment>
                    ),
                    endAdornment: (
                      <InputAdornment position="end">
                        <IconButton
                          onClick={() => setShowPassword(!showPassword)}
                          edge="end"
                          sx={{ color: '#718096' }}
                        >
                          {showPassword ? <VisibilityOff /> : <Visibility />}
                        </IconButton>
                      </InputAdornment>
                    )
                  }}
                />

                {/* Remember Password */}
                <FormControlLabel
                  control={
                    <Checkbox 
                      checked={rememberMe}
                      onChange={(e) => setRememberMe(e.target.checked)}
                      size="small"
                      sx={{
                        color: '#cbd5e0',
                        '&.Mui-checked': {
                          color: '#a855f7'
                        }
                      }}
                    />
                  }
                  label={
                    <Typography variant="body2" sx={{ color: '#718096', fontSize: '0.875rem' }}>
                      {t('remember_me')}
                    </Typography>
                  }
                  sx={{ mb: 3 }}
                />

                {/* Login Button */}
                <Button
                  type="submit"
                  fullWidth
                  variant="contained"
                  endIcon={<ArrowForward />}
                  sx={{
                    py: 1.5,
                    borderRadius: '12px',
                    textTransform: 'uppercase',
                    fontWeight: 600,
                    fontSize: '0.875rem',
                    background: 'linear-gradient(135deg, #2d3748 0%, #1a202c 100%)',
                    color: '#ffffff',
                    boxShadow: '0 4px 6px rgba(0, 0, 0, 0.1)',
                    '&:hover': {
                      background: 'linear-gradient(135deg, #1a202c 0%, #000000 100%)',
                      boxShadow: '0 6px 12px rgba(0, 0, 0, 0.15)'
                    }
                  }}
                >
                  {t('login.login')}
                </Button>
              </form>
            ) : (
              <form onSubmit={handleVerify2FA}>
                <Alert severity="info" sx={{ mb: 3, borderRadius: 2 }}>
                  {useBackupCode ? t('twoFactor.enterBackupCode') : t('twoFactor.enterCode')}
                </Alert>

                <TextField
                  fullWidth
                  placeholder={useBackupCode ? t('twoFactor.backupCodePlaceholder') : t('twoFactor.codePlaceholder')}
                  value={twoFACode}
                  onChange={(e) => setTwoFACode(useBackupCode ? e.target.value.toUpperCase() : e.target.value.replace(/\D/g, '').slice(0, 6))}
                  required
                  autoFocus
                  inputProps={{
                    maxLength: useBackupCode ? 8 : 6,
                    style: { 
                      textAlign: 'center',
                      fontSize: useBackupCode ? '18px' : '24px',
                      letterSpacing: useBackupCode ? '4px' : '8px',
                      fontFamily: 'monospace',
                      color: '#2d3748'
                    }
                  }}
                  sx={{
                    mb: 2,
                    '& .MuiOutlinedInput-root': {
                      borderRadius: '12px',
                      backgroundColor: '#f7fafc',
                      '& fieldset': {
                        borderColor: '#e2e8f0'
                      },
                      '&:hover fieldset': {
                        borderColor: '#cbd5e0'
                      },
                      '&.Mui-focused fieldset': {
                        borderColor: '#a855f7'
                      }
                    },
                    '& .MuiOutlinedInput-input': {
                      color: '#2d3748'
                    }
                  }}
                />

                <Button
                  size="small"
                  onClick={() => { setUseBackupCode(!useBackupCode); setTwoFACode(''); }}
                  sx={{ mb: 3, color: '#718096', textTransform: 'none' }}
                >
                  {useBackupCode ? t('twoFactor.useAuthenticatorCode') : t('twoFactor.useBackupCode')}
                </Button>

                <Button
                  type="submit"
                  fullWidth
                  variant="contained"
                  disabled={useBackupCode ? twoFACode.length !== 8 : twoFACode.length !== 6}
                  sx={{
                    py: 1.5,
                    borderRadius: '12px',
                    textTransform: 'uppercase',
                    fontWeight: 600,
                    fontSize: '0.875rem',
                    background: 'linear-gradient(135deg, #2d3748 0%, #1a202c 100%)',
                    color: '#ffffff',
                    boxShadow: '0 4px 6px rgba(0, 0, 0, 0.1)',
                    '&:hover': {
                      background: 'linear-gradient(135deg, #1a202c 0%, #000000 100%)',
                      boxShadow: '0 6px 12px rgba(0, 0, 0, 0.15)'
                    }
                  }}
                >
                  {t('twoFactor.verify')}
                </Button>

                <Button
                  fullWidth
                  onClick={() => { setRequire2FA(false); setTwoFACode(''); setUseBackupCode(false); }}
                  sx={{
                    mt: 2,
                    color: '#718096',
                    textTransform: 'none'
                  }}
                >
                  {t('twoFactor.backToLogin')}
                </Button>
              </form>
            )}

          </Box>
        </Grid>
      </Grid>

      {/* Show password change dialog if required */}
      {mustChangePassword && (
        <ChangePasswordDialog onPasswordChanged={handlePasswordChanged} />
      )}
    </Box>
  );
}

export default Login;
