import React, { useEffect, useRef, useState } from 'react';
import styled from 'styled-components';
import { useNavigate, useSearchParams } from 'react-router-dom';
import { useLocale } from '@/app/providers/LocaleProvider';
import { Button, Card } from '@/shared/components/ui';
import { ROUTES } from '@/shared/constants/routes';
import { authService } from '@/features/auth/services/authService';
import { useAuthStore } from '@/features/auth/store/authStore';
import { useBrandingLogos } from '@/shared/hooks/useBrandingLogos';

const Container = styled.div`
  min-height: 100vh;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: ${({ theme }) => theme.spacing[4]};
`;

const LogoBranding = styled.div`
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: ${({ theme }) => theme.spacing[4]};
  margin-bottom: ${({ theme }) => theme.spacing[8]};
`;

const LogoImage = styled.img`
  width: min(200px, 75vw);
  height: auto;
`;

const ContentCard = styled(Card)`
  width: 100%;
  max-width: 400px;
`;

const Message = styled.p`
  text-align: center;
  color: ${({ theme }) => theme.colors.text.secondary};
  margin-bottom: ${({ theme }) => theme.spacing[4]};
`;

const MagicLinkPage: React.FC = () => {
  const { t } = useLocale();
  const { square } = useBrandingLogos();
  const navigate = useNavigate();
  const [searchParams] = useSearchParams();
  const login = useAuthStore((state) => state.login);
  const [error, setError] = useState<string | null>(null);
  const processed = useRef(false);

  useEffect(() => {
    if (processed.current) {
      return;
    }

    processed.current = true;

    const email = searchParams.get('email') ?? '';
    const token = searchParams.get('token') ?? '';

    if (!email || !token) {
      setError(t('auth:messages.invalidOtp'));
      return;
    }

    const verify = async () => {
      try {
        await authService.ensureCsrfCookie();
        const user = await authService.verifyMagicLink(email, token, true);
        login(user);
        
        // Ensure the auth store is updated before navigation
        useAuthStore.setState({ isLoading: false });
        
        // Small delay to ensure session is established
        await new Promise(resolve => setTimeout(resolve, 100));
        
        navigate(ROUTES.DASHBOARD, { replace: true });
      } catch {
        setError(t('auth:messages.invalidOtp'));
      }
    };

    void verify();
  }, [login, navigate, searchParams, t]);

  return (
    <Container>
      <LogoBranding>
        <LogoImage src={square} alt={t('common:app.logoAlt')} />
      </LogoBranding>

      <ContentCard variant="elevated" padding="lg">
        {error ? (
          <>
            <Message>{error}</Message>
            <Button variant="primary" fullWidth onClick={() => navigate(ROUTES.LOGIN)}>
              {t('auth:login.title')}
            </Button>
          </>
        ) : (
          <Message>{t('auth:magicLink.processing')}</Message>
        )}
      </ContentCard>
    </Container>
  );
};

export default MagicLinkPage;
