import React, { useState } from 'react';
import styled from 'styled-components';
import { Link, useNavigate, useSearchParams } from 'react-router-dom';
import { useLocale } from '@/app/providers/LocaleProvider';
import { Button, Card, Input } from '@/shared/components/ui';
import { ROUTES } from '@/shared/constants/routes';
import { authService } from '@/features/auth/services/authService';
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 Title = styled.h2`
  font-family: ${({ theme }) => theme.typography.fontFamily.headline};
  font-size: ${({ theme }) => theme.typography.fontSize['2xl']};
  font-weight: ${({ theme }) => theme.typography.fontWeight.semibold};
  margin-bottom: ${({ theme }) => theme.spacing[2]};
  text-align: center;
`;

const Form = styled.form`
  display: flex;
  flex-direction: column;
  gap: ${({ theme }) => theme.spacing[4]};
  width: 100%;
  max-width: 400px;
`;

const ErrorText = styled.p`
  color: ${({ theme }) => theme.colors.error};
  font-size: ${({ theme }) => theme.typography.fontSize.sm};
  text-align: center;
  margin: 0;
`;

const AcceptInvitePage: React.FC = () => {
  const { t } = useLocale();
  const { square } = useBrandingLogos();
  const navigate = useNavigate();
  const [searchParams] = useSearchParams();
  const [name, setName] = useState('');
  const [isLoading, setIsLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);

  const email = searchParams.get('email') ?? '';
  const token = searchParams.get('token') ?? '';
  const hasInviteParams = Boolean(email.trim() && token.trim());

  const handleSubmit = async (event: React.FormEvent) => {
    event.preventDefault();
    if (!hasInviteParams) {
      return;
    }

    setIsLoading(true);
    setError(null);

    try {
      await authService.acceptInvite(email, token, name);
      navigate(ROUTES.LOGIN, { replace: true });
    } catch {
      setError(t('auth:invite.invalid'));
    } finally {
      setIsLoading(false);
    }
  };

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

      <Card variant="elevated" padding="lg">
        <Title>{t('auth:invite.title')}</Title>
        {!hasInviteParams ? (
          <>
            <ErrorText role="alert">{t('auth:invite.missingParams')}</ErrorText>
            <Link to={ROUTES.LOGIN} style={{ textAlign: 'center', marginTop: 16 }}>
              {t('auth:login.title')}
            </Link>
          </>
        ) : (
          <Form onSubmit={handleSubmit}>
            <Input
              label={t('auth:invite.name')}
              value={name}
              onChange={(event) => setName(event.target.value)}
              required
              fullWidth
            />
            {error && <ErrorText role="alert">{error}</ErrorText>}
            <Button type="submit" variant="primary" fullWidth loading={isLoading} disabled={!name.trim()}>
              {t('auth:invite.accept')}
            </Button>
          </Form>
        )}
      </Card>
    </Container>
  );
};

export default AcceptInvitePage;
