import { Circle, Path, Svg, Text, View } from "@react-pdf/renderer";

import { reportStyles } from "@/pdf/styles/report-styles";
import type { HeirShare } from "@/types/inheritance";

const CHART_COLORS = [
  "#047857",
  "#0F766E",
  "#B45309",
  "#14532D",
  "#92400E",
  "#0D9488",
  "#713F12",
  "#166534",
];

function polarToCartesian(
  centerX: number,
  centerY: number,
  radius: number,
  angleInDegrees: number,
) {
  const angleInRadians = ((angleInDegrees - 90) * Math.PI) / 180;
  return {
    x: centerX + radius * Math.cos(angleInRadians),
    y: centerY + radius * Math.sin(angleInRadians),
  };
}

function describePieSlice(
  centerX: number,
  centerY: number,
  radius: number,
  startAngle: number,
  endAngle: number,
) {
  const start = polarToCartesian(centerX, centerY, radius, endAngle);
  const end = polarToCartesian(centerX, centerY, radius, startAngle);
  const largeArcFlag = endAngle - startAngle <= 180 ? "0" : "1";

  return [
    `M ${centerX} ${centerY}`,
    `L ${start.x} ${start.y}`,
    `A ${radius} ${radius} 0 ${largeArcFlag} 0 ${end.x} ${end.y}`,
    "Z",
  ].join(" ");
}

interface InheritancePieChartProps {
  heirs: HeirShare[];
}

export function InheritancePieChartSection({ heirs }: InheritancePieChartProps) {
  const slices = heirs
    .filter((heir) => heir.amount > 0)
    .map((heir, index) => ({
      label: heir.label,
      percentage: heir.percentage,
      color: CHART_COLORS[index % CHART_COLORS.length],
    }));

  const slicesWithAngles = slices.reduce<
    Array<(typeof slices)[number] & { startAngle: number; endAngle: number }>
  >((acc, slice) => {
    const previousEnd = acc[acc.length - 1]?.endAngle ?? 0;
    const sweep = (slice.percentage / 100) * 360;
    acc.push({
      ...slice,
      startAngle: previousEnd,
      endAngle: previousEnd + sweep,
    });
    return acc;
  }, []);

  const centerX = 110;
  const centerY = 110;
  const radius = 78;

  return (
    <View style={reportStyles.section}>
      <Text style={reportStyles.sectionTitle}>Distribution Visual</Text>
      <View style={{ flexDirection: "row", alignItems: "center" }}>
        <Svg width={220} height={220}>
          {slicesWithAngles.map((slice, index) => {
            return (
              <Path
                key={`${slice.label}-${index}`}
                d={describePieSlice(
                  centerX,
                  centerY,
                  radius,
                  slice.startAngle,
                  slice.endAngle,
                )}
                fill={slice.color}
              />
            );
          })}
          <Circle cx={centerX} cy={centerY} r={31} fill="#FFFEFA" />
          <Text
            x={centerX - 17}
            y={centerY + 4}
            style={{ fontSize: 10, fill: "#1F5144", fontWeight: 700 }}
          >
            Heirs
          </Text>
        </Svg>

        <View style={{ flex: 1, marginLeft: 16 }}>
          {slices.map((slice, index) => (
            <View
              key={`${slice.label}-${index}`}
              style={{
                flexDirection: "row",
                alignItems: "center",
                marginBottom: 6,
              }}
            >
              <View
                style={{
                  width: 8,
                  height: 8,
                  marginRight: 6,
                  borderRadius: 999,
                  backgroundColor: slice.color,
                }}
              />
              <Text style={{ fontSize: 9, color: "#1F5144" }}>
                {slice.label} ({slice.percentage.toFixed(2)}%)
              </Text>
            </View>
          ))}
        </View>
      </View>
    </View>
  );
}
