import React from 'react';
import type { PieConfig } from '@ant-design/plots';
import { Pie } from '@ant-design/plots';
import styles from './index.less';

type SingleValuePieProps = {
  header: string;
  value?: number;
  conditionKey: string;
  errorText: string;
};

const convertData = (value?: number) => {
  const data: { type: string; value: number }[] = [];
  const m = (value ?? 0) > 1 ? 1 : value ?? 0;
  const leftValue = (1 - m) / 2;
  data.push({
    type: 'r',
    value: leftValue,
  });
  data.push({
    type: 'm',
    value: m,
  });
  data.push({
    type: 'l',
    value: leftValue,
  });
  return data;
};

const SingleValuePie: React.FC<SingleValuePieProps> = ({ header, value, errorText }) => {
  const config: PieConfig & React.RefAttributes<unknown> = {
    data: convertData(value),
    angleField: 'value',
    colorField: 'type',
    radius: 0.7,
    innerRadius: 0.6,
    yAxis: false,
    xAxis: false,
    legend: false,
    label: false,
    color: ['#212d3d', '#208aa3', '#212d3d'],
    pieStyle: {
      lineWidth: 0,
    },
    statistic: {
      title: false,
      content: {
        style: {
          fontSize: '20px',
          color: '#0ff',
        },
        content: typeof value === 'number' ? `${(value * 100).toFixed(1)}%` : errorText,
      },
    },
  };

  return (
    <div className={styles.main}>
      <div className={styles.header}>{header}</div>
      <div className={styles.content}>
        <Pie {...config} />
      </div>
    </div>
  );
};

export default SingleValuePie;
