/**
 * @file Login.tsx - Login page component that renders a branded card layout with language switcher, authentication form, and version/copyright footer.
 * Listens for cross-tab login events so that authenticating in one browser tab automatically navigates all other open tabs past the login screen.
 */

// @ts-expect-error vite-imagetools OutputMetadata
import { src as logoSrc } from '../assets/brand/logo.png';
import { useEffect, useState } from 'react';
import { useLocation, useNavigate } from 'react-router-dom';
import { Button, Card, Col, Container, Row, Spinner } from 'react-bootstrap';
import { useTranslation } from 'react-i18next';
import { LanguageSwitcher } from '../components/LanguageSwitcher.tsx';
import { useMediaQuery } from 'react-responsive';
import { breakpoints } from '../utils/bootstrapBreakpoints.ts';
import { AuthForm } from '../components/AuthForm.tsx';
import i18next from 'i18next';
import {
  AUTH_SESSION_SYNC_RECEIVED_EVENT_NAME,
  AUTH_SESSION_SYNC_UPDATED_EVENT_NAME,
} from '../constants.ts';
import { useAuth } from '../contexts/AuthContext.tsx';

/**
 * Login page that validates user credentials.
 */
export const Login = () => {
  const navigate = useNavigate();
  const location = useLocation();
  const { isInitializing } = useAuth();

  const [showLoadingSpinner, setShowLoadingSpinner] = useState(false);

  // Handler fires after successful login
  const handleAfterLogin = () => {
    // Retrieve redirect path from state
    const redirectPath = (location.state as any)?.from?.pathname || '/';
    navigate(redirectPath);
  };

  // Listen for cross-tab login events
  useEffect(() => {
    window.addEventListener(
      AUTH_SESSION_SYNC_RECEIVED_EVENT_NAME,
      handleAfterLogin
    );
    window.addEventListener(
      AUTH_SESSION_SYNC_UPDATED_EVENT_NAME,
      handleAfterLogin
    );

    return () => {
      window.removeEventListener(
        AUTH_SESSION_SYNC_RECEIVED_EVENT_NAME,
        handleAfterLogin
      );
      window.removeEventListener(
        AUTH_SESSION_SYNC_UPDATED_EVENT_NAME,
        handleAfterLogin
      );
    };
  }, [navigate, location.state]);

  const isMobileMd = useMediaQuery({ maxWidth: breakpoints.md - 1 });

  const { t } = useTranslation(undefined, {
    keyPrefix: 'pages.login',
  });

  if (isInitializing) {
    return null;
  }

  return (
    <>
      <section className={'d-flex flex-grow-1 align-items-center'}>
        <Container>
          <Row className={'justify-content-center'}>
            <Col xs={12} lg={6} className={'my-3'}>
              <Card className={'text-center'}>
                <Card.Header className={'pb-0 ratio ratio-3x1'}>
                  <Card.Img
                    variant={'top'}
                    className={'object-fit-scale'}
                    src={logoSrc}
                    loading={'lazy'}
                  />
                </Card.Header>
                <Card.Body className={`container ${isMobileMd ? '' : 'w-75'}`}>
                  <LanguageSwitcher />
                  <hr />
                  <Card.Title className={'fs-2'}>
                    {t('card.body.title', {
                      app_title: import.meta.env.VITE_APP_TITLE,
                    })}
                  </Card.Title>
                  <Card.Text className={'text-muted'}>
                    {t('card.body.subtitle', {
                      app_title: import.meta.env.VITE_APP_TITLE,
                    })}
                  </Card.Text>
                  <AuthForm
                    loginThen={handleAfterLogin}
                    buttons={{
                      login: {
                        element: (
                          <Button
                            type={'submit'}
                            variant={'primary'}
                            className={'w-100 my-2'}
                            disabled={showLoadingSpinner}
                          >
                            {showLoadingSpinner ? (
                              <>
                                <Spinner
                                  as={'span'}
                                  animation={'border'}
                                  size={'sm'}
                                  role={'status'}
                                  aria-hidden={'true'}
                                  className={'me-2'}
                                />
                                {i18next.t(
                                  'components.auth_form.buttons.log_in.logging_in_text'
                                )}
                                ...
                              </>
                            ) : (
                              <>
                                {i18next.t(
                                  'components.auth_form.buttons.log_in.default'
                                )}
                              </>
                            )}
                          </Button>
                        ),
                        setShowLoadingSpinner: setShowLoadingSpinner,
                      },
                    }}
                  />
                </Card.Body>
                <Card.Footer>
                  <small>
                    {import.meta.env.VITE_APP_TITLE} ({__APP_VERSION__})
                  </small>
                  <br />
                  <small className={'text-muted'}>
                    {t('card.footer.copyright', {
                      current_year: new Date(Date.now()).getFullYear(),
                      company_name: window.__APP_CONFIG__?.COMPANY_NAME,
                    })}
                  </small>
                </Card.Footer>
              </Card>
            </Col>
          </Row>
        </Container>
      </section>
    </>
  );
};
