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

interface LoginProps {
  onBack: () => void;
  onRegister: () => void;
}

export default function Login({ onBack, onRegister }: LoginProps) {
  const { login, loading, error, currentUser } = useAuth();
  const [username, setUsername] = React.useState('');
  const [password, setPassword] = React.useState('');

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    await login(username, password);
  };

  // ✅ Auto-return if already logged in
  React.useEffect(() => {
    if (currentUser) onBack();
  }, [currentUser]);

  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 In
      </Typography>

      <Typography variant="body2" color="text.secondary" gutterBottom>
        Please log in 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={password}
          onChange={(e) => setPassword(e.target.value)}
          required
        />

        {error && (
          <Typography color="error" variant="body2" sx={{ mt: 1 }}>
            {error}
          </Typography>
        )}

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

      <Typography
        variant="body2"
        color="text.secondary"
        align="center"
        sx={{ mt: 3 }}
      >
        Don’t have an account?{' '}
        <Link
          component="button"
          underline="hover"
          color="primary"
          onClick={onRegister}
          sx={{ fontWeight: 500 }}
        >
          Register
        </Link>
      </Typography>
    </Box>
  );
}
