import React, { useMemo } from 'react';
import styled from 'styled-components';
import { Cell, Pie, PieChart, Tooltip } from 'recharts';
import { useTheme } from '@/app/providers/ThemeProvider';
import { useLocale } from '@/app/providers/LocaleProvider';
import { ChartShell } from '@/features/dashboard/components/charts';
import { createChartTooltipRenderer } from '@/features/dashboard/components/charts/ChartTooltip';
import { ChartResponsiveContainer } from '@/features/dashboard/components/ChartResponsiveContainer';
import { getChartAnimationProps } from '@/features/dashboard/components/charts/chartTheme';
import { getSlaStatusColors } from '@/features/dashboard/utils/chartColors';
import type { ChartDataset } from '@/features/dashboard/types/dashboard.types';

const ChartLayout = styled.div`
  display: flex;
  flex-direction: column;
  align-items: stretch;
  gap: ${({ theme }) => theme.spacing[3]};
  flex: 1;
  min-height: 0;
  height: 100%;
  min-width: 0;
`;

const DonutColumn = styled.div`
  width: 100%;
  flex: 1;
  min-height: 120px;
  min-width: 0;
`;

const LegendList = styled.ul`
  list-style: none;
  margin: 0;
  padding: 0;
  display: flex;
  flex-direction: column;
  gap: ${({ theme }) => theme.spacing[2]};
  width: 100%;
  min-width: 0;
  flex-shrink: 0;
`;

const LegendItem = styled.li`
  display: grid;
  grid-template-columns: minmax(0, 1fr) auto;
  align-items: center;
  gap: ${({ theme }) => theme.spacing[3]};
  font-size: ${({ theme }) => theme.typography.fontSize.sm};
`;

const LegendLabel = styled.span`
  display: flex;
  align-items: center;
  gap: ${({ theme }) => theme.spacing[2]};
  color: ${({ theme }) => theme.colors.text.primary};
  min-width: 0;

  span {
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }
`;

const LegendSwatch = styled.span<{ $color: string }>`
  width: 10px;
  height: 10px;
  border-radius: ${({ theme }) => theme.borderRadius.full};
  background-color: ${({ $color }) => $color};
  flex-shrink: 0;
`;

const LegendValue = styled.span`
  color: ${({ theme }) => theme.colors.text.secondary};
  font-variant-numeric: tabular-nums;
  white-space: nowrap;
  flex-shrink: 0;
`;

interface DistributionDonutChartProps {
  title: string;
  dataset: ChartDataset;
  emptyLabel: string;
  emptyHint?: string;
  labelMap?: Record<string, string>;
  colorMap?: Record<string, string>;
}

export const DistributionDonutChart: React.FC<DistributionDonutChartProps> = ({
  title,
  dataset,
  emptyLabel,
  emptyHint,
  labelMap = {},
  colorMap,
}) => {
  const { theme } = useTheme();
  const { locale } = useLocale();
  const slaColors = getSlaStatusColors(theme);

  const chartData = useMemo(
    () =>
      dataset.labels
        .map((label, index) => ({
          name: labelMap[label] ?? label,
          rawName: label,
          value: dataset.data[index] ?? 0,
        }))
        .filter((item) => item.value > 0),
    [dataset, labelMap],
  );

  const hasData = chartData.length > 0;
  const total = chartData.reduce((sum, item) => sum + item.value, 0);

  const resolveColor = (rawName: string, index: number) => {
    if (colorMap?.[rawName]) {
      return colorMap[rawName];
    }
    if (slaColors[rawName]) {
      return slaColors[rawName];
    }
    const palette = [
      theme.colors.primary,
      theme.colors.secondary,
      theme.colors.success,
      theme.colors.warning,
      theme.colors.error,
    ];
    return palette[index % palette.length];
  };

  const numberFormat = new Intl.NumberFormat(locale);
  const tooltipRenderer = createChartTooltipRenderer(undefined, (name, value) => ({
    name: String(name),
    value: numberFormat.format(value),
  }));

  return (
    <ChartShell
      title={title}
      empty={!hasData}
      emptyLabel={emptyLabel}
      emptyHint={emptyHint}
      fill
    >
      <ChartLayout>
        <DonutColumn>
          <ChartResponsiveContainer fill>
            {({ width, height }) => (
              <PieChart width={width} height={height}>
                <Pie
                  data={chartData}
                  dataKey="value"
                  nameKey="name"
                  cx="50%"
                  cy="50%"
                  innerRadius="58%"
                  outerRadius="88%"
                  paddingAngle={2}
                  stroke="none"
                  {...getChartAnimationProps()}
                >
                  {chartData.map((entry, index) => (
                    <Cell key={entry.rawName} fill={resolveColor(entry.rawName, index)} />
                  ))}
                </Pie>
                <Tooltip content={tooltipRenderer} />
              </PieChart>
            )}
          </ChartResponsiveContainer>
        </DonutColumn>
        <LegendList>
          {chartData.map((entry, index) => {
            const percent = total > 0 ? Math.round((entry.value / total) * 100) : 0;
            return (
              <LegendItem key={entry.rawName}>
                <LegendLabel>
                  <LegendSwatch $color={resolveColor(entry.rawName, index)} />
                  <span>{entry.name}</span>
                </LegendLabel>
                <LegendValue>
                  {numberFormat.format(entry.value)} · {percent}%
                </LegendValue>
              </LegendItem>
            );
          })}
        </LegendList>
      </ChartLayout>
    </ChartShell>
  );
};
