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 qs from 'query-string';
import { CSSProperties, memo, useState } from 'react';
import { Center, Flexbox } from 'react-layout-kit';
import urlJoin from 'url-join';
import { useTranslation } from 'react-i18next';
import { DiscoverPlugintem } from '@/types/discover';
import { useUserStore } from '@/store/user';
import CardBanner from '../../../components/CardBanner';
import { useCategoryItem } from './useCategory';
import { StarOutlined } from '@ant-design/icons';
import request from '@/app/request';
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;

    background: ${token.colorBgContainer};
    border-radius: ${token.borderRadiusLG}px;

    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};
  `,
  inner: css`
    padding: 16px;
  `,
  time: css`
    color: ${token.colorTextDescription};
  `,
  title: css`
    margin-block-end: 0 !important;
    font-size: 18px !important;
    font-weight: bold;
  `,
}));

interface PluginCardProps
  extends Omit<DiscoverPlugintem, 'manifest' | 'suggestions' | 'socialData'> {
  className?: string;
  href: string;
  showCategory?: boolean;
  style?: CSSProperties;
  variant?: 'default' | 'compact';
}
const getUserId = (s: { user?: { id?: any } }) => s.user?.id
const PluginCard = memo<PluginCardProps>(
  ({ className, showCategory, meta, createdAt, author, variant, style, href,...rest }) => {
    const { avatar, title, description, tags = [], category } = meta;
    const { homepage, identifier, schemaVersion, status, classify, manifest,locale } = {...rest}
    const categoryItem = useCategoryItem(category, 12);
    const { cx, styles, theme } = useStyles();
    const { t } = useTranslation('discover');
    const { message } = App.useApp();
    const isCompact = variant === 'compact';
    const userId = getUserId(useUserStore.getState())
    const [val, setVal] = useState('')
    const handleCollect = (e) => {
      // console.log(e,"8844848")
      e.preventDefault()
      e.stopPropagation()
      const params = {
        "author": author,
        "avatar": avatar,
        "category": category,
        "createdAt": createdAt,
        "description": description,
        "homepage": homepage,
        "identifier": identifier,
        "locale": locale,
        "manifest": manifest,
        "schemaVersion": schemaVersion,
        "tags": tags.join(','),
        "title": title,
        "userid": userId,
      }
      request({
        data: params,
        method: "post",
        url: "/flxai/api/robot/appaiplugin",
      }).then(response => {
        // console.log(response,"222222222")
        if (response.code === 0) {
          message.success(t('collectSuccess'));
          setVal("1")
        }
      }).catch(error => {
        console.error('Error fetching data:', error);
      })
    }
    const renderElement = () => {
      // console.log(classify,'66666----------------------')
      if (classify !== 'collect') {
        // console.log(status,"222222222--------------------------")
        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}>
        {!isCompact && <CardBanner avatar={avatar} />}
        <Flexbox className={styles.inner} gap={12}>
          <Flexbox align={'flex-end'} gap={16} horizontal justify={'space-between'} width={'100%'}>
            <Title className={styles.title} ellipsis={{ rows: 1, tooltip: title }} level={3}>
              {title}
            </Title>
            {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
                  alt={title}
                  avatar={avatar}
                  size={56}
                  style={{ display: 'block' }}
                  title={title}
                />
              </Center>
            )}
          </Flexbox>
          <Flexbox gap={8} horizontal style={{ fontSize: 12 }}>
            <div style={{ color: theme.colorTextSecondary }}>@{author}</div>
            {!isCompact && (
              <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 5' }}>
                  {categoryItem.label}
                </Tag>
              ) : (
                tags
                  .slice(0, 4)
                  .filter(Boolean)
                  .map((tag: string, index) => {
                    // const url = qs.stringifyUrl({
                    //   query: { q: tag, type: 'plugins' },
                    //   url: '/discover/search',
                    // });
                    return (
                      <Tag key={index} style={{ margin: '0 5' }}>{startCase(tag).trim()}</Tag>
                    );
                  })
              )}
            </div>
            {renderElement()}
          </Flexbox>
        </Flexbox>
      </Flexbox>
    );
  },
);

export default PluginCard;
