import React, { useState, useEffect } from 'react';
import {
  SimpleGrid,
  Card,
  Text,
  ActionIcon,
  Group,
  Stack,
  Title,
} from '@mantine/core';
import { Badge } from '@skybridge/web-components';
import { useNavigate } from 'react-router-dom';
import {
  IconStar,
  IconStarFilled,
  IconDashboard,
  IconKey,
  IconFunction,
  IconApps,
} from '@tabler/icons-react';
import Breadcrumbs from '../components/Breadcrumbs';
import { microFrontends } from '../microfrontends.js';

interface App {
  id: string;
  name: string;
  description: string;
  icon: React.ComponentType<any>;
  path: string;
  category: string;
}

// Map microfrontend IDs to display information
const getAppInfo = (id: string) => {
  const appInfo: Record<string, { name: string; description: string; icon: React.ComponentType<any>; category: string }> = {
    demo: {
      name: 'Demo App',
      description: 'Sample microfrontend application for testing module federation',
      icon: IconDashboard,
      category: 'Development',
    },
    kms: {
      name: 'Key Management System',
      description: 'Manage API keys, tokens, and access permissions for applications',
      icon: IconKey,
      category: 'Security',
    },
    faas: {
      name: 'Function-as-a-Service',
      description: 'Deploy and manage serverless functions',
      icon: IconFunction,
      category: 'Development',
    },
  };

  return appInfo[id] || {
    name: id.charAt(0).toUpperCase() + id.slice(1),
    description: `Microfrontend application: ${id}`,
    icon: IconApps,
    category: 'Application',
  };
};

const HomePage: React.FC = () => {
  const navigate = useNavigate();
  
  // Load favorites from localStorage or default to demo app
  const [favoriteApps, setFavoriteApps] = useState<string[]>(() => {
    try {
      const saved = localStorage.getItem('favoriteMicrofrontends');
      return saved ? JSON.parse(saved) : ['demo'];
    } catch {
      return ['demo'];
    }
  });

  // Save favorites to localStorage whenever they change
  useEffect(() => {
    try {
      localStorage.setItem('favoriteMicrofrontends', JSON.stringify(favoriteApps));
    } catch (e) {
      console.warn('Failed to save favorites to localStorage', e);
    }
  }, [favoriteApps]);

  // Generate available apps from the microfrontends registry
  const availableApps: App[] = Object.keys(microFrontends).map(id => {
    const info = getAppInfo(id);
    return {
      id,
      name: info.name,
      description: info.description,
      icon: info.icon,
      path: `/app/${id}`,
      category: info.category,
    };
  });

  const toggleFavorite = (appId: string) => {
    setFavoriteApps(prev =>
      prev.includes(appId)
        ? prev.filter(id => id !== appId)
        : [...prev, appId]
    );
  };

  const favoriteAppsList = availableApps.filter(app => favoriteApps.includes(app.id));
  const otherApps = availableApps.filter(app => !favoriteApps.includes(app.id));

  const AppTile: React.FC<{ app: App }> = ({ app }) => {
    const IconComponent = app.icon;
    
    return (
      <Card
        shadow="sm"
        padding="lg"
        radius="md"
        withBorder
        style={{ cursor: 'pointer', height: '100%' }}
        onClick={() => navigate(app.path)}
      >
        <Group justify="space-between" align="flex-start" mb="xs">
          <IconComponent size={32} color="var(--mantine-color-blue-6)" />
          <ActionIcon
            variant="subtle"
            onClick={(e) => {
              e.stopPropagation();
              toggleFavorite(app.id);
            }}
          >
            {favoriteApps.includes(app.id) ? (
              <IconStarFilled size={16} color="gold" />
            ) : (
              <IconStar size={16} />
            )}
          </ActionIcon>
        </Group>

        <Stack gap="xs">
          <Text fw={500} size="lg">
            {app.name}
          </Text>
          <Text size="sm" c="dimmed">
            {app.description}
          </Text>
          <Badge variant="light" size="sm">
            {app.category}
          </Badge>
        </Stack>
      </Card>
    );
  };

  return (
    <Stack gap="xl">
      <Breadcrumbs />
      
      {favoriteAppsList.length > 0 && (
        <div>
          <Group mb="md">
            <IconStarFilled size={20} color="gold" />
            <Title order={2}>Favorite Applications</Title>
          </Group>
          <SimpleGrid cols={{ base: 1, sm: 2, md: 3, lg: 4 }} spacing="md">
            {favoriteAppsList.map(app => (
              <AppTile key={app.id} app={app} />
            ))}
          </SimpleGrid>
        </div>
      )}

      <div>
        <Title order={2} mb="md">
          All Applications
        </Title>
        <SimpleGrid cols={{ base: 1, sm: 2, md: 3, lg: 4 }} spacing="md">
          {otherApps.map(app => (
            <AppTile key={app.id} app={app} />
          ))}
        </SimpleGrid>
      </div>
    </Stack>
  );
};

export default HomePage;
