import React from 'react';
import PropTypes from 'prop-types';
import { Cell, Pie, PieChart, ResponsiveContainer } from 'recharts';
import { alpha } from '@mui/material';
import { useTheme } from '@mui/material/styles';
import { InfoOutlined } from '@mui/icons-material';

import { DEVICES } from '../../constants';
import { ALPHA_500 } from '@/mui/constants/opacity';

import { Tooltip, Typography } from '@/mui/components';

import styles from './Device.module.scss';

const RADIAN = Math.PI / 180;
const renderCustomizedLabel = ({ cx, cy, midAngle, innerRadius, outerRadius, percent }) => {
  const radius = innerRadius + (outerRadius - innerRadius) * 0.5;
  const x = cx + radius * Math.cos(-midAngle * RADIAN);
  const y = cy + radius * Math.sin(-midAngle * RADIAN);
  const text = `${(percent * 100).toFixed(0)}%`;
  let rectWidth = 15;
  if (text?.length > 2) {
    rectWidth = 20;
  }
  if (text?.length > 3) {
    rectWidth = 30;
  }

  return (
    <g>
      <rect fill="white" x={x > cx ? x : x - rectWidth} y={y - 7} width={rectWidth} height={15} />
      <text
        className={styles.Label}
        x={x}
        y={y}
        fill="black"
        textAnchor={x > cx ? 'start' : 'end'}
        dominantBaseline="central"
      >
        {text}
      </text>
    </g>
  );
};

function Device(props) {
  const theme = useTheme();

  const COLORS = {
    DESKTOP: theme.palette.primary.main,
    MOBILE: theme.palette['-graph'][12],
    OTHER: alpha(theme.palette.primary.main, ALPHA_500),
  };

  return (
    <div className={styles.Device}>
      <Typography
        variant="caption"
        color="text.primary"
        component="div"
        fontWeight={400}
        className={styles.DeviceTitle}
      >
        Devices
      </Typography>
      <Typography variant="captionSmall" color="text.secondary" component="div" className={styles.DeviceDescr}>
        by revenue
      </Typography>

      {!!props.devices?.length && (
        <>
          <div className={styles.ChartContainer}>
            <ResponsiveContainer width="100%" height="100%">
              <PieChart width={95} height={95}>
                <Pie
                  data={props.devices}
                  cx="50%"
                  cy="50%"
                  labelLine={false}
                  label={renderCustomizedLabel}
                  outerRadius={45}
                  fill="#8884d8"
                  dataKey="value"
                >
                  {props.devices.map((item, index) => (
                    <Cell key={`cell-${index + 1}`} fill={COLORS[item.device]} />
                  ))}
                </Pie>
              </PieChart>
            </ResponsiveContainer>
          </div>

          <div className={styles.Legend}>
            {DEVICES.map((device) => (
              <div className={styles.LegendItem} key={device.value}>
                <div
                  className={styles.LegendColor}
                  style={{
                    backgroundColor: COLORS[device.value],
                  }}
                />
                <Typography variant="captionSmall" color="text.primary" fontWeight={400}>
                  {device.label}
                </Typography>
              </div>
            ))}
          </div>
        </>
      )}

      <Tooltip title="Share of revenue generated with views on these types of devices" placement="top">
        <span className={styles.InfoIconWrap}>
          <InfoOutlined fontSize="xSmall" htmlColor="info.main" />
        </span>
      </Tooltip>

      {!props.devices?.length && (
        <div className={styles.NoData}>
          <Typography variant="subtitle1" color="text.disabled" className={styles.NoDataTitle}>
            {props.isTotalsLoading ? 'Loading...' : 'No Data...'}
          </Typography>
        </div>
      )}
    </div>
  );
}

Device.propTypes = {
  devices: PropTypes.arrayOf(
    PropTypes.shape({
      device: PropTypes.string.isRequired,
      value: PropTypes.number.isRequired,
      valuePct: PropTypes.number.isRequired,
    }),
  ).isRequired,
  isTotalsLoading: PropTypes.bool.isRequired,
};

export default Device;
