import React, { useEffect, useState } from 'react';
import styles from './style/compDetails.module.less';
import { Space, Divider, Button, Typography, Card, Image, Rate, Grid } from '@arco-design/web-react';
import dayjs from 'dayjs';
import { getComponentMarket } from '@/api/componentMarket';
import ReactMarkdown from 'react-markdown';
import remarkGfm from 'remark-gfm';
import CopyComponentModal from './copyComponentModal';

const { Row, Col } = Grid;

const CompDetails = ({ compInfo }) => {
  const [componentList, setComponentList] = useState([]);
  const [currentCompInfo, setCurrentCompInfo] = useState<any>(compInfo);
  const [copyModalVisible, setCopyModalVisible] = useState(false);

  // 获取组件市场数据
  const fetchComponentData = async () => {
    try {
      const params = {
        componentClassify: compInfo.componentClassify,
        keyword: '',
        current: 1,
        size: 4
      };

      const res: any = await getComponentMarket(params);

      if (res?.code === 200 && res?.data) {
        setComponentList(res.data.list || []);
      }
      else {
        setComponentList([]);
      }
    } catch (error) {
      console.error('获取组件市场数据失败:', error);
      setComponentList([]);
    } finally {
    }
  };
  useEffect(() => {
    fetchComponentData();
  }, []);

  // 处理复制组件
  const handleCopyComponent = () => {
    setCopyModalVisible(true);
  };


  // 渲染组件外壳
  const renderCompHousing = () => {
    return (
      <div className={styles['comp-housing']}>
        <div className={styles['comp-housing-header']}>
          <div className={styles['comp-housing-title']}>{currentCompInfo.name}</div>
        </div>
        <div className={styles['comp-housing-content']}>
          {currentCompInfo.def ? (
            <>
              <div className={styles['comp-housing-content-api']}>
                <div className={styles['comp-housing-content-api-in']}>
                  {currentCompInfo.def?.apis?.map((item: any, index) => <div key={index}>{item.id}</div>)}
                </div>
                <div className={styles['comp-housing-content-api-out']}>
                  <div>{currentCompInfo.def?.apiOut?.id}</div>
                </div>
              </div>
              <Divider style={{ marginTop: 10, marginBottom: 10 }} />
              <div className={styles['comp-housing-content-data']}>
                <div className={styles['comp-housing-content-data-in']}>
                  {currentCompInfo.def?.dataIns?.map((item: any, index) => <div key={index}>{item.id}</div>)}
                </div>
                <div className={styles['comp-housing-content-data-out']}>
                  {currentCompInfo.def?.dataOuts?.map((item: any, index) => <div key={index}>{item.id}</div>)}
                </div>
              </div>
            </>
          ) : (
            <>
              <div className={styles['comp-housing-content-api']}>
                <div className={styles['comp-housing-content-api-in']}>
                  <div>contour</div>
                </div>
                <div className={styles['comp-housing-content-api-out']}>
                  <div>done</div>
                </div>
              </div>
              <Divider style={{ marginTop: 10, marginBottom: 10 }} />
              <div className={styles['comp-housing-content-data']}>
                <div className={styles['comp-housing-content-data-in']}>
                  {currentCompInfo.flowHousVO?.dataIns?.map((item: any, index) => <div key={index}>{item.id}</div>)}
                </div>
                <div className={styles['comp-housing-content-data-out']}>
                  {currentCompInfo.flowHousVO?.dataOuts?.map((item: any, index) => <div key={index}>{item.id}</div>)}
                </div>
              </div>
            </>
          )}
        </div>
      </div>
    );
  };

  return (
    <>
      <div className={styles['comp-container']}>
        <div className={styles['comp-preview']}>
          <h3>组件预览</h3>
          {renderCompHousing()}
        </div>
        <div className={styles['comp-info']}>
          <div className={styles['header']}>
            <Space size={40}>
              <div className={styles['title']}>{currentCompInfo.name}</div>
              <div
                className={styles['update-time']}>更新时间: {dayjs(currentCompInfo.updateTime).format('YYYY-MM-DD HH:mm:ss')}</div>
              <div className={styles['update-time']}>组件大小: {currentCompInfo.size}</div>
              <div className={styles['update-time']}>组件版本: V_{currentCompInfo.status}</div>
              <div className={styles['update-time']}>组件评分: {currentCompInfo.star}分</div>
            </Space>
          </div>
          <div className={styles['extra']}>
            <Divider style={{ borderColor: '#5484ff', marginTop: 0, marginBottom: 30 }} />
            <Space size={30}>
              <div className={styles['extra-font']}>{currentCompInfo.identifier}</div>
              <div className={styles['extra-font']}>分类：{currentCompInfo.componentClassify}</div>
              <div className={styles['extra-font']}>语言：{currentCompInfo.codeLanguage}</div>
            </Space>
          </div>
          <Divider style={{ marginTop: 15, borderBottomStyle: 'dashed' }} />
          <div className={styles['description']}>
            {currentCompInfo.description ? currentCompInfo.description : ' - '}
          </div>
          <Divider style={{ borderBottomStyle: 'dashed' }} />
          <div className={styles['markdown-content']}>
            <ReactMarkdown
              remarkPlugins={[remarkGfm]}
              components={{
                // 自定义组件样式
                h1: ({ node, ...props }) => <h1
                  style={{ fontSize: '24px', fontWeight: 'bold', marginBottom: '16px' }} {...props} />,
                h2: ({ node, ...props }) => <h2
                  style={{ fontSize: '20px', fontWeight: 'bold', marginBottom: '14px' }} {...props} />,
                h3: ({ node, ...props }) => <h3
                  style={{ fontSize: '18px', fontWeight: 'bold', marginBottom: '12px' }} {...props} />,
                p: ({ node, ...props }) => <p style={{ marginBottom: '12px', lineHeight: '1.6' }} {...props} />,
                code: ({ node, inline, ...props }: any) =>
                  inline
                    ? <code style={{
                      backgroundColor: '#f6f6f6',
                      padding: '2px 6px',
                      borderRadius: '3px',
                      fontSize: '0.9em'
                    }} {...props} />
                    : <code style={{
                      display: 'block',
                      backgroundColor: '#f6f6f6',
                      padding: '12px',
                      borderRadius: '4px',
                      overflow: 'auto',
                      fontSize: '0.9em'
                    }} {...props} />,
                pre: ({ node, ...props }) => <pre style={{
                  backgroundColor: '#f6f6f6',
                  padding: '12px',
                  borderRadius: '4px',
                  overflow: 'auto'
                }} {...props} />,
                ul: ({ node, ...props }) => <ul style={{ marginLeft: '20px', marginBottom: '12px' }} {...props} />,
                ol: ({ node, ...props }) => <ol style={{ marginLeft: '20px', marginBottom: '12px' }} {...props} />,
                li: ({ node, ...props }) => <li style={{ marginBottom: '6px', lineHeight: '1.6' }} {...props} />,
                blockquote: ({ node, ...props }) => <blockquote style={{
                  borderLeft: '4px solid #ddd',
                  paddingLeft: '16px',
                  color: '#666',
                  margin: '12px 0'
                }} {...props} />,
                a: ({ node, ...props }) => <a style={{ color: '#165DFF', textDecoration: 'none' }} {...props} />,
                table: ({ node, ...props }) => <table
                  style={{ borderCollapse: 'collapse', width: '100%', marginBottom: '12px' }} {...props} />,
                th: ({ node, ...props }) => <th style={{
                  border: '1px solid #ddd',
                  padding: '8px',
                  backgroundColor: '#f6f6f6',
                  fontWeight: 'bold'
                }} {...props} />,
                td: ({ node, ...props }) => <td style={{ border: '1px solid #ddd', padding: '8px' }} {...props} />
              }}
            >
              {currentCompInfo.readme || currentCompInfo.desc || '暂无详细说明'}
            </ReactMarkdown>
          </div>
          <Divider style={{ borderBottomStyle: 'dashed' }} />
          <div className={styles['handel-box']}>
            <Button type="text">更新时间: {dayjs(currentCompInfo.updateTime).format('YYYY-MM-DD HH:mm:ss')}</Button>
            <Button type="text"  onClick={handleCopyComponent}>复制到我的组件</Button>
          </div>
          <Divider style={{ borderBottomStyle: 'dashed' }} />
        </div>
      </div>
      <div className={styles['recommend']}>
        <Typography.Title heading={5}>相关推荐</Typography.Title>

        <Row style={{ marginBottom: 16 }}>
          {componentList.map((item) => (
            <Col
              xs={12}
              sm={12}
              md={12}
              lg={6}
              xl={6}
              xxl={6}
              key={item.id}
              style={{ marginBottom: 16 }}
            >
              <Card
                style={{ cursor: 'pointer', border: '1px solid #d9d9d9' }}
                onClick={() => setCurrentCompInfo(item)}
                hoverable
              >
                {/*左侧图片*/}
                <div className={styles['img-box']}>
                  <Image width={'100%'} height={'100%'} src={item.logoUrl} alt="暂无图片"></Image>
                </div>
                {/*右侧数据*/}
                <div className={styles['info-box']}>
                  <div className={styles['info-title']}>{item.name || '未命名组件'}</div>
                  <div className={styles['info-author']}>{item.identifier || '-'}</div>
                  <div className={styles['info-score']}>
                    <div>组件评分：</div>
                    <div className={styles['info-rate']}>
                      <Rate readonly allowHalf value={item.star || 5} />
                      <Typography.Text style={{ margin: '0 5px', fontSize: 16 }}>
                        {item.star || 5}分
                      </Typography.Text>
                    </div>
                  </div>
                </div>
              </Card>
              <div className={styles['comp-card-footer']}>
                <div className={styles['comp-type']}>{item.componentClassify || '-'}</div>
                <div className={styles['comp-language']}>{item.codeLanguage || '-'}</div>
              </div>
            </Col>
          ))}
        </Row>
      </div>

      {/* 复制组件弹窗 */}
      <CopyComponentModal
        visible={copyModalVisible}
        componentInfo={currentCompInfo}
        onCancel={() => setCopyModalVisible(false)}
        onSuccess={() => {
          setCopyModalVisible(false);
        }}
      />
    </>
  );
};

export default CompDetails;