'use client';

import { MCP } from '@lobehub/icons';
import {
  ActionIcon,
  Avatar,
  Button,
  Flexbox,
  Icon,
  Tag,
  Text,
  Tooltip,
  TooltipGroup,
} from '@lobehub/ui';
import { App } from 'antd';
import { createStaticStyles, cssVar, useResponsive } from 'antd-style';
import {
  BookmarkCheckIcon,
  BookmarkIcon,
  BookTextIcon,
  CoinsIcon,
  DotIcon,
  GitBranchIcon,
} from 'lucide-react';
import qs from 'query-string';
import { memo, useState } from 'react';
import { useTranslation } from 'react-i18next';
import useSWR from 'swr';

import PublishedTime from '@/components/PublishedTime';
import WorkspaceLink from '@/features/Workspace/WorkspaceLink';
import { useMarketAuth } from '@/layout/AuthProvider/MarketAuth';
import { favoriteKeys } from '@/libs/swr/keys';
import { socialService } from '@/services/social';
import { formatIntergerNumber } from '@/utils/format';

import { useCategory } from '../../../(list)/agent/features/Category/useCategory';
import { resolveCommunityProfileLink } from '../../utils/profileLink';
import AgentForkTag from './AgentForkTag';
import { useDetailContext } from './DetailProvider';

const styles = createStaticStyles(({ css, cssVar }) => ({
  time: css`
    font-size: 12px;
    color: ${cssVar.colorTextDescription};
  `,
}));

const Header = memo<{ mobile?: boolean }>(({ mobile: isMobile }) => {
  const { t } = useTranslation('discover');
  const { message } = App.useApp();
  const {
    author,
    identifier,
    createdAt,
    category,
    avatar,
    title,
    tokenUsage,
    pluginCount,
    knowledgeCount,
    userName,
    ownerType,
    forkCount,
  } = useDetailContext();
  const { mobile = isMobile } = useResponsive();
  const { isAuthenticated, signIn, session } = useMarketAuth();
  const [favoriteLoading, setFavoriteLoading] = useState(false);

  // Set access token for social service
  if (session?.accessToken) {
    socialService.setAccessToken(session.accessToken);
  }

  // Fetch favorite status
  const { data: favoriteStatus, mutate: mutateFavorite } = useSWR(
    identifier && isAuthenticated ? favoriteKeys.status('agent', identifier) : null,
    () => socialService.checkFavoriteStatus('agent', identifier!),
    { revalidateOnFocus: false },
  );

  const isFavorited = favoriteStatus?.isFavorited ?? false;

  const handleFavoriteClick = async () => {
    if (!isAuthenticated) {
      await signIn();
      return;
    }

    if (!identifier) return;

    setFavoriteLoading(true);
    try {
      if (isFavorited) {
        await socialService.removeFavorite('agent', identifier);
        message.success(t('assistant.unfavoriteSuccess'));
      } else {
        await socialService.addFavorite('agent', identifier);
        message.success(t('assistant.favoriteSuccess'));
      }
      await mutateFavorite();
    } catch (error) {
      console.error('Favorite action failed:', error);
      message.error(t('assistant.favoriteFailed'));
    } finally {
      setFavoriteLoading(false);
    }
  };

  const categories = useCategory();
  const cate = categories.find((c) => c.key === category);

  const cateButton = (
    <WorkspaceLink
      to={qs.stringifyUrl({
        query: { category: cate?.key },
        url: '/community/agent',
      })}
    >
      <Button icon={cate?.icon} size={'middle'} variant={'outlined'}>
        {cate?.label}
      </Button>
    </WorkspaceLink>
  );

  return (
    <Flexbox gap={12}>
      <Flexbox horizontal align={'flex-start'} gap={16} width={'100%'}>
        <Avatar avatar={avatar} shape={'square'} size={mobile ? 48 : 64} />
        <Flexbox
          flex={1}
          gap={4}
          style={{
            overflow: 'hidden',
          }}
        >
          <Flexbox
            horizontal
            align={'center'}
            gap={8}
            justify={'space-between'}
            style={{
              overflow: 'hidden',
              position: 'relative',
            }}
          >
            <Flexbox
              horizontal
              align={'center'}
              flex={1}
              gap={12}
              style={{
                overflow: 'hidden',
                position: 'relative',
              }}
            >
              <Text
                ellipsis
                as={'h1'}
                style={{ fontSize: mobile ? 18 : 24, margin: 0 }}
                title={identifier}
              >
                {title}
              </Text>
            </Flexbox>
            <Tooltip title={isFavorited ? t('assistant.unfavorite') : t('assistant.favorite')}>
              <ActionIcon
                icon={isFavorited ? BookmarkCheckIcon : BookmarkIcon}
                loading={favoriteLoading}
                variant={isFavorited ? 'outlined' : undefined}
                onClick={handleFavoriteClick}
              />
            </Tooltip>
          </Flexbox>
          <Flexbox horizontal align={'center'} gap={8} wrap={'wrap'}>
            {author && userName ? (
              <WorkspaceLink
                style={{ color: 'inherit' }}
                to={resolveCommunityProfileLink(userName, ownerType)}
              >
                {author}
              </WorkspaceLink>
            ) : (
              author
            )}
            <Icon icon={DotIcon} />
            <PublishedTime className={styles.time} date={createdAt as string} />
            <AgentForkTag />
            {!!forkCount && forkCount > 0 && (
              <Tag bordered={false} color="default" icon={<Icon icon={GitBranchIcon} />}>
                {forkCount} {t('fork.forks')}
              </Tag>
            )}
          </Flexbox>
        </Flexbox>
      </Flexbox>
      <TooltipGroup>
        <Flexbox
          horizontal
          align={'center'}
          gap={mobile ? 12 : 24}
          style={{
            color: cssVar.colorTextSecondary,
          }}
        >
          {!mobile && cateButton}
          {Boolean(tokenUsage) && (
            <Tooltip
              styles={{ root: { pointerEvents: 'none' } }}
              title={t('assistants.tokenUsage')}
            >
              <Flexbox horizontal align={'center'} gap={6}>
                <Icon icon={CoinsIcon} />
                {formatIntergerNumber(tokenUsage)}
              </Flexbox>
            </Tooltip>
          )}
          {Boolean(pluginCount) && (
            <Tooltip
              styles={{ root: { pointerEvents: 'none' } }}
              title={t('assistants.withPlugin')}
            >
              <Flexbox horizontal align={'center'} gap={6}>
                <Icon fill={cssVar.colorTextSecondary} icon={MCP} />
                {pluginCount}
              </Flexbox>
            </Tooltip>
          )}
          {Boolean(knowledgeCount) && (
            <Tooltip
              styles={{ root: { pointerEvents: 'none' } }}
              title={t('assistants.withKnowledge')}
            >
              <Flexbox horizontal align={'center'} gap={6}>
                <Icon icon={BookTextIcon} />
                {knowledgeCount}
              </Flexbox>
            </Tooltip>
          )}
        </Flexbox>
      </TooltipGroup>
    </Flexbox>
  );
});

export default Header;
