import React from 'react';
import { Box, Title, Tabs, Stack, Text, ActionIcon, Group, Select } from '@mantine/core';
import { 
  IconApps, 
  IconKey, 
  IconTestPipe, 
  IconFileText,
  IconDashboard,
  IconStar,
  IconStarFilled 
} from '@tabler/icons-react';
import Applications from './components/Applications';
import Tokens from './components/Tokens';
import TokenTester from './components/TokenTester';
import Audit from './components/Audit';
import Dashboard from './components/Dashboard';

const App: React.FC = () => {
  // Determine current route based on pathname
  const getCurrentRoute = () => {
    const path = window.location.pathname;
    if (path.includes('/applications')) return 'applications';
    if (path.includes('/tokens')) return 'tokens';
    if (path.includes('/token-tester')) return 'token-tester';
    if (path.includes('/audit')) return 'audit';
    return 'dashboard';
  };

  const [currentRoute, setCurrentRoute] = React.useState(getCurrentRoute());
  const [isFavorited, setIsFavorited] = React.useState(false);
  const [selectedColor, setSelectedColor] = React.useState('');

  // Listen for URL changes (for when the shell navigates)
  React.useEffect(() => {
    const handlePopState = () => {
      setCurrentRoute(getCurrentRoute());
    };
    
    window.addEventListener('popstate', handlePopState);
    return () => window.removeEventListener('popstate', handlePopState);
  }, []);

  const handleTabChange = (value: string | null) => {
    if (value) {
      // Use history.pushState to update URL and notify shell router
      const basePath = '/app/kms';
      const newPath = value === 'dashboard' ? basePath : `${basePath}/${value}`;
      
      // Update the URL and internal state
      window.history.pushState(null, '', newPath);
      setCurrentRoute(value);
      
      // Dispatch a custom event so shell can respond if needed
      window.dispatchEvent(new PopStateEvent('popstate', { state: null }));
    }
  };

  const toggleFavorite = () => {
    setIsFavorited(prev => !prev);
  };

  const colorOptions = [
    { value: 'red', label: 'Red' },
    { value: 'blue', label: 'Blue' },
    { value: 'green', label: 'Green' },
    { value: 'purple', label: 'Purple' },
    { value: 'orange', label: 'Orange' },
    { value: 'pink', label: 'Pink' },
    { value: 'teal', label: 'Teal' },
  ];


  const renderContent = () => {
    switch (currentRoute) {
      case 'applications':
        return <Applications />;
      case 'tokens':
        return <Tokens />;
      case 'token-tester':
        return <TokenTester />;
      case 'audit':
        return <Audit />;
      default:
        return <Dashboard />;
    }
  };

  return (
    <Box w="100%" pos="relative">
      <Stack gap="lg">
        <div>
          <Group justify="space-between" align="flex-start">
            <div>
              <Group align="center" gap="sm" mb="xs">
                <Title order={1} size="h2">
                  Key Management System
                </Title>
                <ActionIcon
                  variant="subtle"
                  size="lg"
                  onClick={toggleFavorite}
                  aria-label={isFavorited ? "Remove from favorites" : "Add to favorites"}
                >
                  {isFavorited ? (
                    <IconStarFilled size={20} color="gold" />
                  ) : (
                    <IconStar size={20} />
                  )}
                </ActionIcon>
              </Group>
            </div>

            {/* Right-side controls */}
            <Group align="flex-start" gap="lg">
              <div>
                <Select
                  placeholder="Choose a color"
                  data={colorOptions}
                  value={selectedColor}
                  onChange={(value) => setSelectedColor(value || '')}
                  size="sm"
                  w={150}
                />
              </div>
            </Group>

          </Group>
        </div>

        <Tabs value={currentRoute} onChange={handleTabChange}>
          <Tabs.List>
            <Tabs.Tab 
              value="dashboard" 
              leftSection={<IconDashboard size={16} />}
            >
              Dashboard
            </Tabs.Tab>
            <Tabs.Tab 
              value="applications" 
              leftSection={<IconApps size={16} />}
            >
              Applications
            </Tabs.Tab>
            <Tabs.Tab 
              value="tokens" 
              leftSection={<IconKey size={16} />}
            >
              Tokens
            </Tabs.Tab>
            <Tabs.Tab 
              value="token-tester" 
              leftSection={<IconTestPipe size={16} />}
            >
              Token Tester
            </Tabs.Tab>
            <Tabs.Tab 
              value="audit" 
              leftSection={<IconFileText size={16} />}
            >
              Audit Log
            </Tabs.Tab>
          </Tabs.List>

          <Box pt="md">
            {renderContent()}
          </Box>
        </Tabs>
      </Stack>
    </Box>
  );
};

export default App;