import React, { useState, useEffect } from 'react';
import { useParams, useNavigate } from 'react-router-dom';
import { Spin, Result, Button } from 'antd';
import { LoadingOutlined, LockOutlined } from '@ant-design/icons';
import ProjectDetail from '../pages/ProjectDetail';
import urlResolutionService from '../services/urlResolutionService';
import debugLogger from '../utils/debugLogger';

// Smart Route Component für Admin URL Resolution
export default function SmartProjectRoute({ user, darkMode, onLogout, onToggleDarkMode }) {
  const { project, tab } = useParams();
  const navigate = useNavigate();
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);
  const [resolvedClient, setResolvedClient] = useState(null);

  useEffect(() => {
    const resolveUrl = async () => {
      debugLogger.routing('SmartProjectRoute - Resolving URL for:', { project, tab });
      
      // Nur für Admins, die Client-URLs verwenden
      if (user.role !== 'admin') {
        debugLogger.routing('User ist kein Admin, keine URL Resolution');
        setLoading(false);
        return;
      }

      try {
        debugLogger.routing('Resolving client for project:', project);
        const clientName = await urlResolutionService.resolveClientForProject(project);
        
        if (clientName) {
          debugLogger.success('Client resolved:', { project, clientName, tab });
          setResolvedClient(clientName);
        } else {
          debugLogger.warn('No client found for project:', project);
          setError(`Projekt "${project}" wurde keinem Client zugeordnet.`);
        }
      } catch (err) {
        debugLogger.error('Error during URL resolution:', err);
        setError(`Fehler bei der URL-Resolution: ${err.message}`);
      } finally {
        setLoading(false);
      }
    };

    resolveUrl();
  }, [project, tab, user.role]);

  if (loading) {
    return (
      <Spin 
        indicator={<LoadingOutlined spin />} 
        size="large" 
        tip="Löse URL auf..." 
        style={{ 
          display: 'flex', 
          justifyContent: 'center', 
          alignItems: 'center', 
          height: '100vh' 
        }} 
      />
    );
  }

  if (error) {
    return (
      <Result
        icon={<LockOutlined />}
        status="403"
        title="Keine Zugriffsberechtigung"
        subTitle={error}
        extra={
          <Button type="primary" onClick={() => navigate('/')}>
            Zurück zum Dashboard
          </Button>
        }
      />
    );
  }

  // Für Clients oder wenn keine Resolution nötig: Normale ProjectDetail
  if (user.role !== 'admin' || !resolvedClient) {
    return (
      <ProjectDetail 
        user={user} 
        darkMode={darkMode} 
        onLogout={onLogout} 
        onToggleDarkMode={onToggleDarkMode}
      />
    );
  }

  // Für Admins mit aufgelöster URL: ProjectDetail mit injiziertem Client-Parameter
  debugLogger.routing('Passing parameters to ProjectDetail:', { client: resolvedClient, project, tab });
  return (
    <ProjectDetail 
      user={user} 
      darkMode={darkMode} 
      onLogout={onLogout} 
      onToggleDarkMode={onToggleDarkMode}
      // Inject resolved client parameter
      overrideParams={{ client: resolvedClient, project, tab }}
    />
  );
}
