import React, { useState } from 'react';
import { Box, TextField, Button, Typography, CircularProgress, Alert, Grid } from '@mui/material';
import { Link as RouterLink, useNavigate } from 'react-router-dom';
import { useRegister } from '../hooks/apiHooks';

const RegisterPage = () => {
  const [formData, setFormData] = useState({
    firstName: '',
    lastName: '',
    email: '',
  });
  const navigate = useNavigate();
  
  // React Query mutation
  const register = useRegister();
  
  const handleChange = (e) => {
    const { name, value } = e.target;
    setFormData((prev) => ({
      ...prev,
      [name]: value,
    }));
  };
  
  const handleSubmit = async (e) => {
    e.preventDefault();
    
    // Simple validation
    if (!formData.firstName || !formData.lastName || !formData.email) {
      return;
    }
    
    try {
      await register.mutateAsync(formData);
      
      // Redirect to login page after successful registration
      setTimeout(() => {
        navigate('/auth/login', { state: { email: formData.email } });
      }, 1500);
    } catch (error) {
      // Error handling is done by the hook
    }
  };
  
  return (
    <Box component="form" noValidate onSubmit={handleSubmit} sx={{ mt: 1 }}>
      <Typography variant="h5" gutterBottom>
        Create an Account
      </Typography>
      
      {register.isSuccess && (
        <Alert severity="success" sx={{ mb: 2 }}>
          Registration successful! Redirecting to login...
        </Alert>
      )}
      
      {register.isError && (
        <Alert severity="error" sx={{ mb: 2 }}>
          {register.error?.message || 'Registration failed. Please try again.'}
        </Alert>
      )}
      
      <Grid container spacing={2}>
        <Grid item xs={12} sm={6}>
          <TextField
            margin="normal"
            required
            fullWidth
            id="firstName"
            label="First Name"
            name="firstName"
            autoComplete="given-name"
            autoFocus
            value={formData.firstName}
            onChange={handleChange}
            disabled={register.isLoading || register.isSuccess}
          />
        </Grid>
        <Grid item xs={12} sm={6}>
          <TextField
            margin="normal"
            required
            fullWidth
            id="lastName"
            label="Last Name"
            name="lastName"
            autoComplete="family-name"
            value={formData.lastName}
            onChange={handleChange}
            disabled={register.isLoading || register.isSuccess}
          />
        </Grid>
      </Grid>
      
      <TextField
        margin="normal"
        required
        fullWidth
        id="email"
        label="Email Address"
        name="email"
        autoComplete="email"
        value={formData.email}
        onChange={handleChange}
        disabled={register.isLoading || register.isSuccess}
      />
      
      <Button
        type="submit"
        fullWidth
        variant="contained"
        sx={{ mt: 3, mb: 2 }}
        disabled={register.isLoading || register.isSuccess || 
          !formData.firstName || !formData.lastName || !formData.email}
      >
        {register.isLoading ? (
          <CircularProgress size={24} color="inherit" />
        ) : (
          'Register'
        )}
      </Button>
      
      <Typography variant="body2" align="center">
        Already have an account?{' '}
        <RouterLink to="/auth/login">
          Sign in
        </RouterLink>
      </Typography>
    </Box>
  );
};

export default RegisterPage;