import React, { useState, useEffect } from 'react';
import {
  Box,
  Container,
  Paper,
  Typography,
  Alert,
  Tabs,
  Tab,
  Card,
  CardContent,
  useMediaQuery,
  useTheme,
} 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 'pages/candidate/RegistrationForms';
import { useNavigate, useParams } from 'react-router-dom';
import { useAppState } from 'hooks/GlobalContext';
import * as Types from 'types/types';

const LoginPage: React.FC<BackstoryPageProps> = (props: BackstoryPageProps) => {
  const navigate = useNavigate();
  const { setSnack } = useAppState();
  const [tabValue, setTabValue] = useState<string>('login');
  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 as Types.Candidate).username : user?.email || '';
  const [errorMessage, setErrorMessage] = useState<string | null>(null);
  const theme = useTheme();
  const isMobile = useMediaQuery(theme.breakpoints.down('sm'));
  const showGuest = false;
  const { tab } = useParams();

  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]);

  useEffect(() => {
    if (tab === 'register') {
      setTabValue(tab);
    }
  }, [tab, setTabValue]);

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

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

  return (
    <Paper elevation={3} sx={{ p: isMobile ? 0 : 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: 2 }}>
        <Tabs value={tabValue} onChange={handleTabChange} centered>
          <Tab value="login" icon={<Person />} label="Login" />
          <Tab value="register" 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 === 'login' && <LoginForm />}

      {tabValue === 'register' && <CandidateRegistrationForm />}
    </Paper>
  );
};

export { LoginPage };
