import * as React from 'react';
import { Box, TextField, Button, Typography, IconButton, CircularProgress, Alert, } from '@mui/material';
import ArrowBackRoundedIcon from '@mui/icons-material/ArrowBackRounded';
import { useAuth } from '../providers/Author';

interface RegisterProps {
  onBack: () => void;
}

export default function Register({ onBack }: RegisterProps) {
  const { register, loading, error, currentUser } = useAuth();
  const [username, setUsername] = React.useState('');
  const [password1, setPassword1] = React.useState('');
  const [password2, setPassword2] = React.useState('');
  const [localError, setLocalError] = React.useState<string | null>(null);

   const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setLocalError(null);

    // ✅ Local validation
    if (password1 !== password2) {
      setLocalError("Passwords don't match");
      return;
    }

    if (password1.length < 6) {
      setLocalError('Password must be at least 6 characters long');
      return;
    }

    // ✅ Call backend
    await register(username, password1);
  };

  if (currentUser) {
    // ✅ if logged in, auto-return to the article list
    onBack();
    return null;
  }

  return (
    <Box
      sx={{
        maxWidth: 400,
        mx: 'auto',
        mt: 8,
        p: 4,
        borderRadius: 3,
        boxShadow: 3,
        bgcolor: 'background.paper',
      }}
    >
      <IconButton onClick={onBack} sx={{ mb: 2 }}>
        <ArrowBackRoundedIcon />
      </IconButton>

      <Typography variant="h4" fontWeight="bold" gutterBottom>
        Sign Up
      </Typography>

      <Typography variant="body2" color="text.secondary" gutterBottom>
        Please sign up to continue
      </Typography>

      <form onSubmit={handleSubmit}>
        <TextField
          fullWidth
          label="Username"
          type="username"
          margin="normal"
          value={username}
          onChange={(e) => setUsername(e.target.value)}
          required
        />
        <TextField
          fullWidth
          label="Password"
          type="password"
          margin="normal"
          value={password1}
          onChange={(e) => setPassword1(e.target.value)}
          required
        />
        <TextField
          fullWidth
          label="Password"
          type="password"
          margin="normal"
          value={password2}
          onChange={(e) => setPassword2(e.target.value)}
          required
        />

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

        <Button
          fullWidth
          type="submit"
          variant="contained"
          color="primary"
          sx={{ mt: 3 }}
          disabled={loading}
        >
          {loading ? <CircularProgress size={24} color="inherit" /> : 'Register'}
        </Button>
      </form>
    </Box>
  );
}
