import { IconLabel } from '@/components/common/IconLabel';
import { useMessages, useNavigation, useShare } from '@/components/hooks';
import { AlignEndHorizontal, Clock, Eye, PanelLeft, Sheet, Tag, User } from '@/components/icons';
import { LanguageButton } from '@/components/input/LanguageButton';
import { PreferencesButton } from '@/components/input/PreferencesButton';
import { Funnel, Gauge, Lightning, Magnet, Money, Network, Path, Target } from '@/components/svg';
import { buildPath } from '@/lib/url';
import {
  Button,
  Column,
  Focusable,
  Icon,
  Row,
  Text,
  ThemeButton,
  Tooltip,
  TooltipTrigger,
} from '@umami/react-zen';
import Link from '@/components/common/Link';
import { ShareBranding } from './ShareBranding';

export function ShareNav({
  collapsed,
  onCollapse,
  onItemClick,
}: {
  collapsed?: boolean;
  onCollapse?: (collapsed: boolean) => void;
  onItemClick?: () => void;
}) {
  const share = useShare();
  const { t, labels } = useMessages();
  const { pathname, query } = useNavigation();
  const { slug, parameters } = share;

  const renderPath = (path: string) =>
    buildPath(`/share/${slug}${path}`, {
      ...query,
      event: undefined,
      compare: undefined,
      view: undefined,
      unit: undefined,
      excludeBounce: undefined,
    });

  const allItems = [
    {
      section: 'traffic',
      label: t(labels.traffic),
      items: [
        { id: 'overview', label: t(labels.overview), icon: <Eye />, path: renderPath('') },
        { id: 'events', label: t(labels.events), icon: <Lightning />, path: renderPath('/events') },
        {
          id: 'sessions',
          label: t(labels.sessions),
          icon: <User />,
          path: renderPath('/sessions'),
        },
        {
          id: 'realtime',
          label: t(labels.realtime),
          icon: <Clock />,
          path: renderPath('/realtime'),
        },
        {
          id: 'performance',
          label: t(labels.performance),
          icon: <Gauge />,
          path: renderPath('/performance'),
        },
        {
          id: 'compare',
          label: t(labels.compare),
          icon: <AlignEndHorizontal />,
          path: renderPath('/compare'),
        },
        {
          id: 'breakdown',
          label: t(labels.breakdown),
          icon: <Sheet />,
          path: renderPath('/breakdown'),
        },
      ],
    },
    {
      section: 'behavior',
      label: t(labels.behavior),
      items: [
        { id: 'goals', label: t(labels.goals), icon: <Target />, path: renderPath('/goals') },
        { id: 'funnels', label: t(labels.funnels), icon: <Funnel />, path: renderPath('/funnels') },
        {
          id: 'journeys',
          label: t(labels.journeys),
          icon: <Path />,
          path: renderPath('/journeys'),
        },
        {
          id: 'retention',
          label: t(labels.retention),
          icon: <Magnet />,
          path: renderPath('/retention'),
        },
      ],
    },
    {
      section: 'growth',
      label: t(labels.growth),
      items: [
        { id: 'utm', label: t(labels.utm), icon: <Tag />, path: renderPath('/utm') },
        { id: 'revenue', label: t(labels.revenue), icon: <Money />, path: renderPath('/revenue') },
        {
          id: 'attribution',
          label: t(labels.attribution),
          icon: <Network />,
          path: renderPath('/attribution'),
        },
      ],
    },
  ];

  // Filter items based on parameters
  const items = allItems
    .map(section => ({
      label: section.label,
      items: section.items.filter(item => parameters[item.id] === true),
    }))
    .filter(section => section.items.length > 0);

  const selectedKey = items
    .flatMap(e => e.items)
    .find(({ path }) => path && pathname.endsWith(path.split('?')[0]))?.id;

  const isMobile = !!onItemClick;

  return (
    <Column
      position={isMobile ? undefined : 'fixed'}
      paddingX={collapsed ? '1' : '3'}
      paddingY="3"
      width={isMobile ? '100%' : collapsed ? '60px' : '240px'}
      maxHeight="100dvh"
      height="100dvh"
      border={isMobile ? undefined : 'right'}
    >
      <Row
        as="header"
        gap
        alignItems="center"
        justifyContent={collapsed ? 'center' : 'space-between'}
      >
        {!collapsed && <ShareBranding size="md" />}
        {!onItemClick && (
          <Button variant="quiet" onPress={() => onCollapse?.(!collapsed)}>
            <Icon color="muted">
              <PanelLeft />
            </Icon>
          </Button>
        )}
      </Row>
      <Column flexGrow={1} marginTop="2" overflowY="auto" gap="2">
        {items.map(({ label: sectionLabel, items: sectionItems }, index) => (
          <Column key={`${sectionLabel}${index}`} gap="1" marginBottom="1">
            {!collapsed && (
              <Row padding>
                <Text weight="bold">{sectionLabel}</Text>
              </Row>
            )}
            {sectionItems.map(({ id, path, label, icon }) => {
              const isSelected = selectedKey === id;
              return (
                <Link key={id} href={path} role="button" onClick={onItemClick}>
                  <TooltipTrigger isDisabled={!collapsed} delay={0}>
                    <Focusable>
                      <Row
                        alignItems="center"
                        justifyContent={collapsed ? 'center' : undefined}
                        hover={{ backgroundColor: 'surface-sunken' }}
                        backgroundColor={isSelected ? 'surface-sunken' : undefined}
                        borderRadius
                        minHeight="40px"
                      >
                        <IconLabel
                          icon={icon}
                          label={collapsed ? '' : label}
                          weight={isSelected ? 'bold' : undefined}
                          {...(!collapsed && { padding: true })}
                        />
                      </Row>
                    </Focusable>
                    <Tooltip placement="right">{label}</Tooltip>
                  </TooltipTrigger>
                </Link>
              );
            })}
          </Column>
        ))}
      </Column>
      <Column
        flexGrow={collapsed ? 1 : undefined}
        justifyContent="flex-end"
        alignItems={collapsed ? 'center' : undefined}
      >
        {collapsed ? (
          <Column gap="2" alignItems="center">
            <ThemeButton />
            <LanguageButton />
            <PreferencesButton />
          </Column>
        ) : (
          <Row>
            <ThemeButton />
            <LanguageButton />
            <PreferencesButton />
          </Row>
        )}
      </Column>
    </Column>
  );
}
