import { ModelIcon } from '@lobehub/icons';
import { Typography, App } from 'antd';
import { createStyles } from 'antd-style';
import Link from 'next/link';
import { CSSProperties, memo, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { Flexbox } from 'react-layout-kit';
import { useUserStore } from '@/store/user';
import { StarOutlined } from '@ant-design/icons';
import request from '@/app/request';
import { DiscoverModelItem } from '@/types/discover';

import ModelFeatureTags from '../../../features/ModelFeatureTags';

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};
  `,
  id: css`
    margin-block-end: 0 !important;
    font-size: 12px;
    color: ${token.colorTextSecondary};
  `,
  tagBlue: css`
    color: ${token.geekblue};
    background: ${token.geekblue1};
  `,
  tagGreen: css`
    color: ${token.green};
    background: ${token.green1};
  `,
  time: css`
    color: ${token.colorTextDescription};
  `,
  title: css`
    margin-block-end: 0 !important;
    font-size: 18px !important;
    font-weight: bold;
  `,
  token: css`
    font-family: ${token.fontFamilyCode};
  `,
}));

export interface ModelCardProps extends DiscoverModelItem {
  className?: string;
  href: string;
  showCategory?: boolean;
  style?: CSSProperties;
}
const getUserId = (s: { user?: { id?: any } }) => s.user?.id
const ModelCard = memo<ModelCardProps>(({ className,socialData, meta, identifier, style, href,...rest }) => {
  const { title, description, functionCall, vision, contextWindowTokens, category, id, displayName, enabled } = meta;
  const { conversations, likes, tokens: socialDataToken } = socialData;
  // console.log(socialDataToken,"7373736262626----------------------------",meta)
  const { createdAt, providers, suggestions, status, classify } = {...rest}
  const { t } = useTranslation('models');
  const { t:d } = useTranslation('discover');
  const { cx, styles } = useStyles();
  const { message } = App.useApp();
  const userId = getUserId(useUserStore.getState())
  const [val, setVal] = useState(status)
  const handleCollect = (e) => {
    // console.log(e,"8844848")
    e.preventDefault()
    e.stopPropagation()
    const params = {
      "category": category,
      "conversations": conversations,
      "createdAt": createdAt,
      "description": description,
      "displayname": displayName,
      "enabled": enabled,
      "identifier": identifier,
      "likes": likes,
      "metaId": id,
      "metaTokens": contextWindowTokens,
      "providers": providers.join(','),
      "suggestions": suggestions.join(','),
      "title": title,
      "tokens": socialDataToken,
      "userid": userId,
    }
    request({
      data: params,
      method: "post",
      url: "/flxai/api/robot/appaimodel",
    }).then(response => {
      // console.log(response,"222222222")
      if (response.code === 0) {
        message.success(d('collectSuccess'));
        setVal("1")
      }
    }).catch(error => {
      console.error('Error fetching data:', error);
    })
  }
  const renderElement = () => {
    if (classify !== 'collect') {
      if(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;
    }
  };
  const handleClickCard = (item) => {
    console.log(item)
  }
  return (
    <Flexbox className={cx(styles.container, className)} gap={24} key={identifier} {...rest}>
      <Flexbox
        gap={12}
        padding={16}
        style={{ overflow: 'hidden', position: 'relative' }}
        width={'100%'}
      >
        <Flexbox
          align={'center'}
          gap={12}
          horizontal
          style={{ overflow: 'hidden', position: 'relative' }}
          width={'100%'}
        >
          <ModelIcon model={identifier} size={32} type={'avatar'} />
          <Flexbox style={{ overflow: 'hidden', position: 'relative' }}>
            <Title className={styles.title} ellipsis={{ rows: 1, tooltip: title }} level={3}>
              {title}
            </Title>
            <Paragraph className={styles.id} ellipsis={{ rows: 1 }}>
              {identifier}
            </Paragraph>
          </Flexbox>
        </Flexbox>
        {description && (
          <Paragraph className={styles.desc} ellipsis={{ rows: 2 }}>
            {t(`${identifier}.description`)}
          </Paragraph>
        )}
        <Flexbox gap={6} horizontal style={{ flexWrap: 'wrap',justifyContent: 'space-between' }}>
          <ModelFeatureTags functionCall={functionCall} tokens={contextWindowTokens} vision={vision} />
          {renderElement()}
        </Flexbox>
      </Flexbox>
    </Flexbox>
  );
});

export default ModelCard;
