import { Avatar, Tag } from '@lobehub/ui';
import { Skeleton, Typography, App } from 'antd';
import { createStyles } from 'antd-style';
import { startCase } from 'lodash-es';
import dynamic from 'next/dynamic';
import { useRouter } from 'next/navigation';
import qs from 'query-string';
import { CSSProperties, memo, useState } from 'react';
import { Center, Flexbox, FlexboxProps } from 'react-layout-kit';
import urlJoin from 'url-join';

import request from "@/app/request"
import { DiscoverAssistantItem } from '@/types/discover';

import CardBanner from '../../../components/CardBanner';
import GitHubAvatar from '../../../components/GitHubAvatar';
import { useCategoryItem } from './useCategory';
import { StarOutlined } from '@ant-design/icons';
import { useUserStore } from '@/store/user';
import { useTranslation } from 'react-i18next';

const Link = dynamic(() => import('next/link'), {
  loading: () => <Skeleton.Button size={'small'} style={{ height: 22 }} />,
  ssr: false,
});

const { Paragraph, Title } = Typography;

const useStyles = createStyles(({ css, token, isDarkMode }) => ({
  banner: css`
    opacity: ${isDarkMode ? 0.9 : 0.4};
  `,
  collectBtn: css`
    font-size: 12px;
    width: 20px;
    height: 20px;
    line-height: 20px;
    border-radius: 50%;
    background: #FFF3D9;
    text-align: center;
  `,
  container: css`
    cursor: pointer;
    position: relative;

    overflow: hidden;

    height: 100%;
    min-height: 162px;
    border-radius: ${token.borderRadiusLG}px;

    background: ${token.colorBgContainer};

    box-shadow: 1px 0px 12px 0px rgba(42, 77, 255, 0.19);

    transition: box-shadow 0.2s ${token.motionEaseInOut};

    &:hover {
      box-shadow: 0 0 1px 1px ${isDarkMode ? token.colorFillSecondary : token.colorFill} inset;
    }
  `,
  desc: css`
    min-height: 44px;
    margin-block-end: 0 !important;
    color: ${token.colorTextDescription};
  `,

  time: css`
    color: ${token.colorTextDescription};
  `,
  title: css`
    margin-block-end: 0 !important;
    font-weight: bold;
  `,
}));

export interface AssistantCardProps
  extends Omit<DiscoverAssistantItem, 'suggestions' | 'socialData' | 'config'> {
  className?: string;
  href: string;
  showCategory?: boolean;
  style?: CSSProperties;
  variant?: 'default' | 'compact';
}

const getUserId = (s: { user?: { id?: any } }) => s.user?.id

const AssistantCard = memo<AssistantCardProps>(
  ({ showCategory, className, meta, createdAt, author, variant, style, href, ...rest}) => {
    const { avatar, title, description, tags = [], category } = meta;
    const { createAt, homepage, identifier, schemaVersion, status, classify } = { ...rest }
    const { cx, styles, theme } = useStyles();
    const { t } = useTranslation('discover')
    const { message } = App.useApp()
    const categoryItem = useCategoryItem(category, 12);
    const isCompact = variant === 'compact';
    const userId = getUserId(useUserStore.getState())
    const [val, setVal] = useState("")
    const router = useRouter();

    const handleCollect = (e) => {
      e.preventDefault()
      e.stopPropagation()
      const params = {
        "author": author,
        "avatar": avatar,
        "category": category,
        "createAt": createAt,
        "createdAt": createdAt,
        "description": description,
        "homepage": homepage,
        "identifier": identifier,
        "schemaVersion": schemaVersion,
        "tags": tags.join(','),
        "title": title,
        "userid": userId,
      }
      request({
        data: params,
        method: "post",
        url: "/flxai/api/robot/appaiassistant",
      }).then(response => {
        if (response.code === 0) {
          message.success(t('collectSuccess'));
          setVal("1")
        }
      }).catch(error => {
        console.error('Error fetching data:', error);
      })
    }

    const user = (
      <Flexbox
        align={'center'}
        gap={6}
        horizontal
        style={{ color: theme.colorTextSecondary, fontSize: 12 }}
      >
        <GitHubAvatar size={18} username={author} />
        <span>{author}</span>
      </Flexbox>
    );

    const renderElement = () => {
      if(classify !== 'collect') {
        if(status === '1' || val === '1') {
          return <div className={styles.collectBtn} onClick={(e) => {e.stopPropagation()}}><StarOutlined style={{color: "#FFAD01"}} /></div>
        } else {
          return <div className={styles.collectBtn} onClick={(e) => handleCollect(e)} style={{background: "#F1F1F1"}}><StarOutlined style={{color: "#D6D6D6"}} /></div>
        }
      } else {
        return;
      }
    }

    return (
      <Flexbox className={cx(styles.container, className)} gap={24} style={style} {...rest}>
        {!isCompact && <CardBanner avatar={avatar} />}
        <Flexbox gap={12} padding={16}>
              <Flexbox
                align={isCompact ? 'flex-start' : 'flex-end'}
                gap={16}
                horizontal
                justify={'space-between'}
                style={{ position: 'relative' }}
                width={'100%'}
              >
                <Flexbox
                  gap={8}
                  style={{
                    overflow: 'hidden',
                    paddingTop: isCompact ? 4 : 0,
                    position: 'relative',
                  }}
                >
                  <Title
                    className={styles.title}
                    ellipsis={{ rows: 1, tooltip: title }}
                    level={3}
                    style={{ fontSize: isCompact ? 16 : 18 }}
                  >
                    {title}
                  </Title>
                  {isCompact && user}
                </Flexbox>

                {isCompact ? (
                  <Avatar avatar={avatar} size={40} style={{ display: 'block' }} title={title} />
                ) : (
                  <Center
                    flex={'none'}
                    height={64}
                    style={{
                      background: theme.colorBgContainer,
                      borderRadius: '50%',
                      marginTop: -6,
                      overflow: 'hidden',
                      zIndex: 2,
                    }}
                    width={64}
                  >
                    <Avatar avatar={avatar} size={56} style={{ display: 'block' }} title={title} />
                  </Center>
                )}
              </Flexbox>

              {!isCompact && (
                <Flexbox gap={8} horizontal style={{ fontSize: 12 }}>
                  {user}
                  <time className={styles.time} dateTime={new Date(createdAt).toISOString()}>
                    {createdAt}
                  </time>
                </Flexbox>
              )}
              <Paragraph className={styles.desc} ellipsis={{ rows: 2 }}>
                {description}
              </Paragraph>

          <Flexbox gap={6} horizontal style={{ flexWrap: 'wrap', justifyContent: "space-between" }}>
            <div onClick={(e) => {e.stopPropagation()}} style={{width: '85%'}}>
              {showCategory && categoryItem ? (
                <Tag icon={categoryItem.icon} style={{ margin: 0 }}>
                  {categoryItem.label}
                </Tag>
              ) : (
                tags
                  .slice(0, 4)
                  .filter(Boolean)
                  .map((tag: string, index) => {
                    // const url = qs.stringifyUrl({
                    //   query: { q: tag, type: 'assistants' },
                    //   url: '/discover/search',
                    // });
                    return (
                      <Tag key={index} style={{ margin: '0 5' }}>{startCase(tag).trim()}</Tag>
                      // <Link href={url} key={index}>
                      //   <Link key={index}>
                      //   <Tag style={{ margin: 0 }}>{startCase(tag).trim()}</Tag>
                      // </Link>
                    );
                  })
              )}
            </div>
          </Flexbox>
        </Flexbox>
      </Flexbox>
    );
  },
);

export default AssistantCard;
