import React, { useState, useEffect } from 'react';
import { NavLink, Stack, Text } from '@mantine/core';
import { useNavigate, useLocation } from 'react-router-dom';
import {
  IconDashboard,
  IconKey,
  IconFunction,
  IconApps,
  IconUsers,
} from '@tabler/icons-react';
import { microFrontends } from '../microfrontends.js';

// Map microfrontend IDs to display information
const getAppInfo = (id: string) => {
  const appInfo: Record<string, { label: string; icon: React.ComponentType<any>; category: string }> = {
    demo: {
      label: 'Demo App',
      icon: IconDashboard,
      category: 'Development',
    },
    kms: {
      label: 'Key Management',
      icon: IconKey,
      category: 'Security',
    },
    faas: {
      label: 'Functions',
      icon: IconFunction,
      category: 'Development',
    },
    user: {
      label: 'User Management',
      icon: IconUsers,
      category: 'Administration',
    },
  };

  return appInfo[id] || {
    label: id.charAt(0).toUpperCase() + id.slice(1),
    icon: IconApps,
    category: 'Application',
  };
};

const Navigation: React.FC = () => {
  const navigate = useNavigate();
  const location = useLocation();

  // Load favorites from localStorage (same as HomePage)
  const [favoriteApps, setFavoriteApps] = useState<string[]>(() => {
    try {
      const saved = localStorage.getItem('favoriteMicrofrontends');
      return saved ? JSON.parse(saved) : ['demo'];
    } catch {
      return ['demo'];
    }
  });

  // Listen for changes to favorites in localStorage (in case they change in HomePage)
  useEffect(() => {
    const handleStorageChange = () => {
      try {
        const saved = localStorage.getItem('favoriteMicrofrontends');
        if (saved) {
          setFavoriteApps(JSON.parse(saved));
        }
      } catch {
        // If parsing fails, keep current state
      }
    };

    window.addEventListener('storage', handleStorageChange);
    return () => window.removeEventListener('storage', handleStorageChange);
  }, []);

  // Generate all available applications from the microfrontends registry
  const allAvailableApplications = Object.keys(microFrontends).map(id => {
    const info = getAppInfo(id);
    return {
      id,
      label: info.label,
      icon: info.icon,
      path: `/app/${id}`,
    };
  });

  const favoriteApplications = allAvailableApplications.filter(app => 
    favoriteApps.includes(app.id)
  );

  const nonFavoriteApplications = allAvailableApplications.filter(app => 
    !favoriteApps.includes(app.id)
  );

  return (
    <Stack gap="xs" p="md">
      <Text size="sm" fw={600} c="dimmed" tt="uppercase" mb="xs">
        Favorites
      </Text>
      
      {favoriteApplications.map((app) => (
        <NavLink
          key={app.path}
          label={app.label}
          leftSection={<app.icon size={16} />}
          active={location.pathname.startsWith(app.path)}
          onClick={() => navigate(app.path)}
        />
      ))}

      {nonFavoriteApplications.length > 0 && (
        <>
          <Text size="sm" fw={600} c="dimmed" tt="uppercase" mt="lg" mb="xs">
            All Applications
          </Text>
          
          {nonFavoriteApplications.map((app) => (
            <NavLink
              key={`all-${app.path}`}
              label={app.label}
              leftSection={<app.icon size={16} />}
              active={location.pathname.startsWith(app.path)}
              onClick={() => navigate(app.path)}
            />
          ))}
        </>
      )}
    </Stack>
  );
};

export default Navigation;
