import { type CodeConfigData } from '@/pages/CodeConfig/List';
import { getGitUrl } from '@/utils';
import { Checkbox, Flex, Typography } from 'antd';
import { type CheckboxChangeEvent } from 'antd/es/checkbox';
import classNames from 'classnames';
import { useState } from 'react';
import styles from './index.less';

type CodeConfigItemProps = {
  item: CodeConfigData;
  checked: boolean;
  onChange?: (item: CodeConfigData, checked: boolean) => void;
};

function CodeConfigItem({ item, checked, onChange }: CodeConfigItemProps) {
  const [isEllipsis, setIsEllipsis] = useState(false);

  const openProject = (e: React.MouseEvent<HTMLElement, MouseEvent>) => {
    e.stopPropagation();
    const { git_url, git_branch } = item;
    const url = getGitUrl(git_url, git_branch);
    window.open(url, '_blank');
  };

  const handleChange = (e: CheckboxChangeEvent) => {
    onChange?.(item, e.target.checked);
  };

  return (
    <div
      id={`code-config-item-${item.id}`}
      className={classNames(styles['code-config-item'], {
        [styles['code-config-item--active']]: checked,
      })}
    >
      <Flex justify="space-between" align="center" style={{ marginBottom: '15px' }}>
        <Checkbox
          className={styles['code-config-item__checkbox']}
          checked={checked}
          onChange={handleChange}
        >
          <Typography.Paragraph
            className={styles['code-config-item__name']}
            ellipsis={{ tooltip: item.code_repo_name }}
          >
            {item.code_repo_name}
          </Typography.Paragraph>
        </Checkbox>
        <div
          className={classNames(
            styles['code-config-item__tag'],
            item.is_public
              ? styles['code-config-item__tag--public']
              : styles['code-config-item__tag--private'],
          )}
        >
          {item.is_public ? '公开' : '私有'}
        </div>
      </Flex>
      <Typography.Paragraph
        className={styles['code-config-item__url']}
        ellipsis={{
          rows: 2,
          tooltip: isEllipsis ? item.git_url : false,
          onEllipsis: (ellipsis) => setIsEllipsis(ellipsis), // 必须这样，不然不能省略
        }}
        onClick={openProject}
      >
        {item.git_url}
      </Typography.Paragraph>
      <Typography.Paragraph
        className={styles['code-config-item__branch']}
        ellipsis={{ tooltip: item.git_branch }}
      >
        {item.git_branch}
      </Typography.Paragraph>
    </div>
  );
}

export default CodeConfigItem;
