import React, { forwardRef } from 'react';
import { useTranslation } from 'react-i18next';
import { useMatch, useNavigate } from 'react-router-dom';
import { Box, Text, Tooltip, TooltipProvider, color, toRem } from 'folds';
import { PageNavHeader } from '../../../components/page';
import { BOTS_PATH, DIRECT_PATH } from '../../paths';
import { isNativePlatform } from '../../../utils/capacitor';

type SegmentProps = {
  active: boolean;
  disabled?: boolean;
  label: string;
  onClick?: () => void;
};
const Segment = forwardRef<HTMLButtonElement, SegmentProps>(
  ({ active, disabled, label, onClick }, ref) => (
    <button
      ref={ref}
      type="button"
      onClick={disabled ? undefined : onClick}
      aria-pressed={active}
      aria-disabled={disabled || undefined}
      style={{
        appearance: 'none',
        border: 'none',
        background: active ? color.Background.ContainerActive : 'transparent',
        color: color.Background.OnContainer,
        opacity: disabled ? 0.45 : 1,
        cursor: disabled ? 'default' : 'pointer',
        padding: `${toRem(6)} ${toRem(10)}`,
        borderRadius: toRem(6),
        font: 'inherit',
        fontWeight: active ? 600 : 500,
        fontSize: toRem(13),
        lineHeight: 1.2,
      }}
    >
      {label}
    </button>
  )
);

export function DirectStreamHeader() {
  const { t } = useTranslation();
  const navigate = useNavigate();
  const comingSoon = t('Direct.segment_coming_soon');

  const directMatch = useMatch({ path: DIRECT_PATH, caseSensitive: true, end: false });
  const botsMatch = useMatch({ path: BOTS_PATH, caseSensitive: true, end: false });

  const navOpts = { replace: isNativePlatform() };

  return (
    <PageNavHeader>
      <Box alignItems="Center" grow="Yes" gap="100">
        <Segment
          active={!!directMatch}
          label={t('Direct.segment_dm')}
          onClick={() => navigate(DIRECT_PATH, navOpts)}
        />
        <TooltipProvider
          delay={400}
          position="Bottom"
          tooltip={
            <Tooltip>
              <Text size="T200">{comingSoon}</Text>
            </Tooltip>
          }
        >
          {(triggerRef) => (
            <Segment
              ref={triggerRef as React.RefCallback<HTMLButtonElement>}
              active={false}
              disabled
              label={t('Direct.segment_channels')}
            />
          )}
        </TooltipProvider>
        <Segment
          active={!!botsMatch}
          label={t('Direct.segment_bots')}
          onClick={() => navigate(BOTS_PATH, navOpts)}
        />
      </Box>
    </PageNavHeader>
  );
}
