import React, { useState, useEffect } from 'react';
import {
  Box,
  Container,
  Paper,
  Typography,
  Alert,
  Tabs,
  Tab,
  Card,
  CardContent,
} from '@mui/material';
import {
  Person,
  PersonAdd,
} from '@mui/icons-material';
import 'react-phone-number-input/style.css';
import './LoginPage.css';

import { useAuth } from 'hooks/AuthContext';
import { BackstoryLogo } from 'components/ui/BackstoryLogo';

import { BackstoryPageProps } from 'components/BackstoryTab';

import { LoginForm } from "components/EmailVerificationComponents";
import { CandidateRegistrationForm } from "components/RegistrationForms";
import { useNavigate } from 'react-router-dom';
import { useAppState } from 'hooks/GlobalContext';

const LoginPage: React.FC<BackstoryPageProps> = (props: BackstoryPageProps) => {
  const navigate = useNavigate();
  const { setSnack } = useAppState();
  const [tabValue, setTabValue] = useState(0);
  const [loading, setLoading] = useState(false);
  const [success, setSuccess] = useState<string | null>(null);
  const { guest, user, login, isLoading, error } = useAuth();
  const name = (user?.userType === 'candidate') ? user.username : user?.email || '';
  const [errorMessage, setErrorMessage] = useState<string | null>(null);

  const showGuest: boolean = false;

  useEffect(() => {
    if (!loading || !error) {
      return;
    }
    if (loading && error) {
      /* Remove 'HTTP .*: ' from error string */
      const jsonStr = error.replace(/^[^{]*/, '');
      const data = JSON.parse(jsonStr);
      setErrorMessage(data.error.message);
      setSnack(data.error.message, "error");
      setTimeout(() => {
        setErrorMessage(null);
        setLoading(false);
      }, 3000);
    }
  }, [error, loading]);

  const handleTabChange = (event: React.SyntheticEvent, newValue: number) => {
    setTabValue(newValue);
    setSuccess(null);
  };

  // If user is logged in, navigate to the profile page
  if (user) {
    navigate('/candidate/profile');
    return (<></>);
  }

  return (
    <Container maxWidth="sm" sx={{ mt: 4 }}>
      <Paper elevation={3} sx={{ p: 4 }}>
        <BackstoryLogo />
        
        {showGuest && guest && (
          <Card sx={{ mb: 3, bgcolor: 'grey.50' }} elevation={1}>
            <CardContent>
              <Typography variant="h6" gutterBottom color="primary">
                Guest Session Active
              </Typography>
              <Typography variant="body2" color="text.secondary" sx={{ mb: 0.5 }}>
                Session ID: {guest.sessionId}
              </Typography>
              <Typography variant="body2" color="text.secondary">
                Created: {guest.createdAt.toLocaleString()}
              </Typography>
            </CardContent>
          </Card>
        )}

        <Box sx={{ borderBottom: 1, borderColor: 'divider', mb: 3 }}>
          <Tabs value={tabValue} onChange={handleTabChange} centered>
            <Tab icon={<Person />} label="Login" />
            <Tab icon={<PersonAdd />} label="Register" />
          </Tabs>
        </Box>

        {errorMessage && (
          <Alert severity="error" sx={{ mb: 2 }}>
            {errorMessage}
          </Alert>
        )}

        {success && (
          <Alert severity="success" sx={{ mb: 2 }}>
            {success}
          </Alert>
        )}

        {tabValue === 0 && (
          <LoginForm />
        )}

        {tabValue === 1 && (
          <CandidateRegistrationForm />
        )}
      </Paper>
    </Container>
  );
};

export { LoginPage };