/**
 * Страница автоматического входа по персональному токену
 */

'use client';

import { useEffect, useState, useRef } from 'react';
import { useParams, useRouter } from 'next/navigation';
import { useAuth } from '@/contexts/AuthContext';
import apiClient from '@/lib/api-client';
import { LoadingSpinner } from '@/components/common/LoadingSpinner';
import { getErrorMessage } from '@/lib/error-utils';

export default function LoginByTokenPage() {
  const { token } = useParams();
  const router = useRouter();
  const { login: authLogin } = useAuth();
  const [error, setError] = useState<string | null>(null);
  const loginAttempted = useRef(false);

  useEffect(() => {
    const performLogin = async () => {
      if (loginAttempted.current) return;
      loginAttempted.current = true;
      
      try {
        const response = await apiClient.post<any>('/auth/login-by-token/', { token });
        const data = response.data?.data;
        
        if (data?.tokens?.access) {
          localStorage.setItem('access_token', data.tokens.access);
          if (data.tokens.refresh) {
            localStorage.setItem('refresh_token', data.tokens.refresh);
          }
          
          await authLogin(data.tokens.access, data.user);
          router.push('/dashboard');
        } else {
          setError('Ошибка авторизации: токен недействителен');
        }
      } catch (err: any) {
        setError(getErrorMessage(err, 'Не удалось войти по ссылке'));
      }
    };

    if (token) {
      performLogin();
    }
  }, [token, authLogin, router]);

  if (error) {
    return (
      <div style={{ minHeight: '100vh', display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 20, background: '#f8f9fa' }}>
        <div style={{ maxWidth: 400, width: '100%', padding: 32, textAlign: 'center', borderRadius: 24, boxShadow: '0 4px 12px rgba(0,0,0,0.1)', background: '#fff' }}>
          <div style={{ color: '#c62828', marginBottom: 16 }}>
            <svg style={{ width: 64, height: 64 }} fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 8v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
            </svg>
          </div>
          <h1 style={{ fontSize: 24, fontWeight: 700, marginBottom: 8 }}>Ошибка входа</h1>
          <p style={{ color: '#666', marginBottom: 24 }}>{error}</p>
          <button 
            onClick={() => router.push('/login')}
            style={{ 
              width: '100%', 
              padding: '12px', 
              borderRadius: 12, 
              border: 'none', 
              background: 'var(--md-sys-color-primary, #6750a4)', 
              color: '#fff',
              fontSize: 16,
              fontWeight: 600,
              cursor: 'pointer'
            }}
          >
            На страницу входа
          </button>
        </div>
      </div>
    );
  }

  return (
    <div style={{ minHeight: '100vh', display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', background: '#f8f9fa' }}>
      <LoadingSpinner size="large" />
      <p style={{ marginTop: 16, color: '#666', fontSize: 16 }}>Входим в аккаунт...</p>
    </div>
  );
}
