import React, { useState } from 'react';
import { Box, TextField, Button, Typography, CircularProgress, Alert } from '@mui/material';
import { useNavigate, useLocation } from 'react-router-dom';
import { useRequestLoginCode, useVerifyCode } from '../hooks/apiHooks';

const LoginPage = () => {
  const [email, setEmail] = useState('');
  const [code, setCode] = useState('');
  const [step, setStep] = useState(1); // 1: Enter email, 2: Enter code
  const navigate = useNavigate();
  const location = useLocation();
  
  // Get the return URL from location state or default to home
  const from = location.state?.from?.pathname || '/';
  
  // Get the code from URL params if available (direct link from email)
  const searchParams = new URLSearchParams(location.search);
  const urlCode = searchParams.get('code');
  const urlEmail = searchParams.get('email');
  
  // Use the URL params if available
  React.useEffect(() => {
    if (urlCode && urlEmail) {
      setEmail(urlEmail);
      setCode(urlCode);
      setStep(2);
    }
  }, [urlCode, urlEmail]);
  
  // React Query mutations
  const requestLoginCode = useRequestLoginCode();
  const verifyCode = useVerifyCode();

  const handleRequestCode = async (e) => {
    e.preventDefault();
    
    if (!email) {
      return;
    }
    
    await requestLoginCode.mutateAsync(email);
    setStep(2);
  };
  
  const handleVerifyCode = async (e) => {
    e.preventDefault();
    
    if (!email || !code) {
      return;
    }
    
    await verifyCode.mutateAsync({ email, code });
    navigate(from, { replace: true });
  };
  
  return (
    <Box component="form" noValidate sx={{ mt: 1 }}>
      {step === 1 ? (
        // Step 1: Request login code with email
        <>
          <Typography variant="h5" gutterBottom>
            Login with Email
          </Typography>
          
          {requestLoginCode.isError && (
            <Alert severity="error" sx={{ mb: 2 }}>
              {requestLoginCode.error?.message || 'Failed to send login code. Please try again.'}
            </Alert>
          )}
          
          <TextField
            margin="normal"
            required
            fullWidth
            id="email"
            label="Email Address"
            name="email"
            autoComplete="email"
            autoFocus
            value={email}
            onChange={(e) => setEmail(e.target.value)}
            disabled={requestLoginCode.isLoading}
          />
          
          <Button
            type="submit"
            fullWidth
            variant="contained"
            sx={{ mt: 3, mb: 2 }}
            onClick={handleRequestCode}
            disabled={!email || requestLoginCode.isLoading}
          >
            {requestLoginCode.isLoading ? (
              <CircularProgress size={24} color="inherit" />
            ) : (
              'Request Login Code'
            )}
          </Button>
        </>
      ) : (
        // Step 2: Verify login code
        <>
          <Typography variant="h5" gutterBottom>
            Enter Login Code
          </Typography>
          
          <Typography variant="body2" color="text.secondary" gutterBottom>
            We've sent a verification code to your email.
          </Typography>
          
          {verifyCode.isError && (
            <Alert severity="error" sx={{ mb: 2 }}>
              {verifyCode.error?.message || 'Invalid code. Please try again.'}
            </Alert>
          )}
          
          <TextField
            margin="normal"
            required
            fullWidth
            id="email"
            label="Email Address"
            name="email"
            autoComplete="email"
            value={email}
            onChange={(e) => setEmail(e.target.value)}
            disabled={verifyCode.isLoading}
          />
          
          <TextField
            margin="normal"
            required
            fullWidth
            id="code"
            label="Verification Code"
            name="code"
            autoFocus
            value={code}
            onChange={(e) => setCode(e.target.value)}
            disabled={verifyCode.isLoading}
          />
          
          <Button
            type="submit"
            fullWidth
            variant="contained"
            sx={{ mt: 3, mb: 2 }}
            onClick={handleVerifyCode}
            disabled={!email || !code || verifyCode.isLoading}
          >
            {verifyCode.isLoading ? (
              <CircularProgress size={24} color="inherit" />
            ) : (
              'Verify & Login'
            )}
          </Button>
          
          <Button
            fullWidth
            variant="text"
            onClick={() => setStep(1)}
            disabled={verifyCode.isLoading}
          >
            Request a new code
          </Button>
        </>
      )}
    </Box>
  );
};

export default LoginPage;