import React, { useState } from 'react';
import { useNavigate, Link } from 'react-router-dom';
import {
  Box,
  Container,
  Paper,
  TextField,
  Button,
  Typography,
  InputAdornment,
  IconButton
} from '@mui/material';
import { Visibility, VisibilityOff, LiveTv } from '@mui/icons-material';
import { useTranslation } from 'react-i18next';
import axios from 'axios';
import { useAuthStore } from '../store/authStore';
import PasswordStrengthMeter from '../components/PasswordStrengthMeter';
import { useErrorNotification } from '../components/ErrorNotificationProvider';

function Register() {
  const { t } = useTranslation();
  const navigate = useNavigate();
  const login = useAuthStore((state) => state.login);
  const { showError, showSuccess } = useErrorNotification();
  const [showPassword, setShowPassword] = useState(false);
  const [formData, setFormData] = useState({
    username: '',
    email: '',
    password: ''
  });

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

    try {
      const response = await axios.post('/api/auth/register', formData);
      login(response.data.user, response.data.token);
      
      showSuccess(t('register.success') || 'Registration successful! Welcome aboard.', {
        duration: 3000
      });
      
      navigate('/');
    } catch (err) {
      // Handle password policy errors with detailed feedback
      if (err.response?.data?.details) {
        showError(
          new Error(err.response.data.details.join('. ')),
          {
            title: t('errors.validation.title'),
            duration: 10000
          }
        );
      } else {
        showError(err, {
          title: t('register.failed') || 'Registration Failed',
          defaultMessage: t('register.error') || 'Registration failed. Please try again.'
        });
      }
    }
  };

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

  return (
    <Box
      sx={{
        minHeight: '100vh',
        display: 'flex',
        alignItems: 'center',
        background: (theme) =>
          theme.palette.mode === 'light'
            ? 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)'
            : 'linear-gradient(135deg, #1e3c72 0%, #2a5298 100%)'
      }}
    >
      <Container maxWidth="sm">
        <Paper
          elevation={24}
          sx={{
            p: 3,
            borderRadius: 2.5,
            maxWidth: 400,
            backgroundColor: (theme) =>
              theme.palette.mode === 'light'
                ? 'rgba(255, 255, 255, 0.95)'
                : 'rgba(26, 32, 44, 0.95)',
            backdropFilter: 'blur(10px)'
          }}
        >
          <Box sx={{ textAlign: 'center', mb: 3 }}>
            <LiveTv sx={{ fontSize: 48, color: 'primary.main', mb: 1 }} />
            <Typography variant="h5" fontWeight="bold" gutterBottom>
              {t('app_name')}
            </Typography>
            <Typography variant="caption" color="text.secondary">
              {t('premium_plan')}
            </Typography>
          </Box>

          <Typography variant="h6" fontWeight="600" gutterBottom sx={{ mb: 2 }}>
            {t('create_account')}
          </Typography>

          <form onSubmit={handleSubmit}>
            <TextField
              fullWidth
              label={t('username')}
              name="username"
              value={formData.username}
              onChange={handleChange}
              margin="normal"
              required
              autoFocus
            />

            <TextField
              fullWidth
              label={t('email')}
              name="email"
              type="email"
              value={formData.email}
              onChange={handleChange}
              margin="normal"
              required
            />

            <TextField
              fullWidth
              label={t('password')}
              name="password"
              type={showPassword ? 'text' : 'password'}
              value={formData.password}
              onChange={handleChange}
              margin="normal"
              required
              InputProps={{
                endAdornment: (
                  <InputAdornment position="end">
                    <IconButton
                      onClick={() => setShowPassword(!showPassword)}
                      edge="end"
                    >
                      {showPassword ? <VisibilityOff /> : <Visibility />}
                    </IconButton>
                  </InputAdornment>
                )
              }}
            />

            <PasswordStrengthMeter
              password={formData.password}
              username={formData.username}
              email={formData.email}
            />

            <Button
              type="submit"
              fullWidth
              variant="contained"
              size="medium"
              sx={{ mt: 2, mb: 1.5 }}
            >
              {t('sign_up')}
            </Button>

            <Box sx={{ textAlign: 'center' }}>
              <Typography variant="caption" color="text.secondary">
                {t('already_have_account')}{' '}
                <Link to="/login" style={{ textDecoration: 'none', color: '#2196F3' }}>
                  {t('sign_in')}
                </Link>
              </Typography>
            </Box>
          </form>
        </Paper>
      </Container>
    </Box>
  );
}

export default Register;
