import { memo, useMemo } from 'react';
import ReactEChartsCore from 'echarts-for-react/lib/core';
import * as echarts from 'echarts/core';
import { BarChart, PieChart } from 'echarts/charts';
import {
	GridComponent,
	TooltipComponent,
	TitleComponent,
	LegendComponent,
	DatasetComponent,
} from 'echarts/components';
import { CanvasRenderer } from 'echarts/renderers';
import { ChartContainer } from '@/components/ui/chart-container';

echarts.use([
	TitleComponent,
	TooltipComponent,
	GridComponent,
	LegendComponent,
	DatasetComponent,
	BarChart,
	PieChart,
	CanvasRenderer
]);

type RoleDistribution = { name: string; users_count: number }[];

const CHART_HEIGHT = 300;
const TEXT_COLOR = '#6b7280';

export const RolePieChart = memo(function RolePieChart({ 
	roleDistribution = [] 
}: { 
	roleDistribution?: RoleDistribution 
}) {
	const option = useMemo(() => ({
		tooltip: { trigger: 'item' },
		legend: { orient: 'vertical', left: 'left', textStyle: { color: TEXT_COLOR } },
		series: [
			{
				name: 'Users',
				type: 'pie',
				radius: '50%',
				data: roleDistribution.map(role => ({ name: role.name, value: role.users_count })),
				emphasis: {
					itemStyle: {
						shadowBlur: 10,
						shadowOffsetX: 0,
						shadowColor: 'rgba(0, 0, 0, 0.5)',
					},
				},
				label: { color: TEXT_COLOR },
			},
		],
	}), [roleDistribution]);

	return (
		<ChartContainer title="User Distribution by Role" height={CHART_HEIGHT}>
			<ReactEChartsCore
				echarts={echarts}
				option={option}
				style={{ height: CHART_HEIGHT, width: '100%' }}
				notMerge={true}
				lazyUpdate={true}
			/>
		</ChartContainer>
	);
});

export const RoleBarChart = memo(function RoleBarChart({ 
	roleDistribution = [] 
}: { 
	roleDistribution?: RoleDistribution 
}) {
	const option = useMemo(() => ({
		tooltip: {},
		xAxis: {
			type: 'category',
			data: roleDistribution.map(role => role.name),
			axisLabel: { rotate: 0, color: TEXT_COLOR },
		},
		yAxis: {
			type: 'value',
			axisLabel: { color: TEXT_COLOR },
		},
		series: [
			{
				data: roleDistribution.map(role => role.users_count),
				type: 'bar',
				animation: true,
				animationDuration: 1000,
				animationEasing: 'cubicOut',
				itemStyle: { color: '#3b82f6' },
				barWidth: '50%',
			},
		],
	}), [roleDistribution]);

	return (
		<ChartContainer title="Users per Role" height={CHART_HEIGHT}>
			<ReactEChartsCore
				echarts={echarts}
				option={option}
				style={{ height: CHART_HEIGHT, width: '100%' }}
				notMerge={true}
				lazyUpdate={true}
			/>
		</ChartContainer>
	);
});
