<template>
  <div v-bind="$attrs" class="chart-wrapper full-width full-height">
    <q-resize-observer @resize="onResize" />
    <div v-if="hasData" class="chart-container">
      <Doughnut
        ref="chart_ref"
        :options="chartPieOptions"
        :data="chartPieData"
        :plugins="[ChartDataLabels]"
      />
    </div>
    <div v-else class="no-data-container">
      <span :class="textColor">{{ $t("http.errors.no_records_found") }}</span>
    </div>
  </div>
</template>

<script setup>
import { ref, computed } from "vue";
import { Chart as ChartJS, ArcElement, Tooltip, Legend } from "chart.js";
import { Doughnut } from "vue-chartjs";
import ChartDataLabels from "chartjs-plugin-datalabels";
import { base64ToJPEG } from "src/helpers/convertBase64Image";
import { useQuasar, colors, getCssVar } from "quasar";

ChartJS.register(ArcElement, Tooltip, Legend);

const $q = useQuasar();
const { lighten } = colors;

const props = defineProps({
  data: {
    type: Object,
    default: () => ({
      chart_data: [],
    }),
  },
  backgroundColors: {
    type: Array,
    default: null,
  },
  title: {
    type: String,
    default: "doughnut-chart",
  },
  dataSetLabel: {
    type: String,
    default: "Dados",
  },
});

const chart_ref = ref(null);

const onResize = () => {
  if (chart_ref.value?.chart) {
    setTimeout(() => {
      chart_ref.value.chart.resize();
    }, 50);
  }
};

const textColor = computed(() => {
  return $q.dark.isActive ? "text-white" : "text-black";
});

const labelColor = computed(() => {
  return $q.dark.isActive ? "#ffffff" : "#000000";
});

const dataLabelColor = computed(() => {
  return $q.dark.isActive ? "#ffffff" : "#000000";
});

const hasData = computed(() => {
  return props.data?.chart_data && props.data.chart_data.length > 0;
});

const chartLabels = computed(() => {
  return props.data?.chart_data?.map((item) => item.label) || [];
});

const chartValues = computed(() => {
  return props.data?.chart_data?.map((item) => item.value) || [];
});

const chartPercentages = computed(() => {
  const total = props.data?.current_total || 0;
  if (total === 0) return [];

  return (
    props.data?.chart_data?.map((item) =>
      Math.round((item.value / total) * 100),
    ) || []
  );
});

const chartThemeColors = computed(() => {
  if (props.backgroundColors) {
    return props.backgroundColors;
  }

  const primaryColor = getCssVar("primary");
  if (!primaryColor) return [];

  const numColors = chartValues.value.length;
  const step = numColors > 0 ? 50 / numColors : 0;
  return Array.from({ length: numColors }, (_, i) =>
    lighten(primaryColor, i * step),
  );
});

const chartPieData = computed(() => ({
  labels: chartLabels.value,
  datasets: [
    {
      label: props.dataSetLabel,
      data: chartPercentages.value,
      backgroundColor: chartThemeColors.value,
    },
  ],
}));

const chartPieOptions = computed(() => ({
  responsive: true,
  maintainAspectRatio: false,
  plugins: {
    legend: {
      position: "bottom",
      labels: {
        color: labelColor.value,
        font: {
          size: 12,
        },
        padding: 20,
      },
    },
    datalabels: {
      color: dataLabelColor.value,
      font: {
        size: 12,
        weight: "bold",
      },
      formatter: (value) => {
        return value > 0 ? value + "%" : "";
      },
    },
    tooltip: {
      backgroundColor: $q.dark.isActive
        ? "rgba(0, 0, 0, 0.8)"
        : "rgba(255, 255, 255, 0.9)",
      titleColor: labelColor.value,
      bodyColor: labelColor.value,
      borderColor: labelColor.value,
      borderWidth: 1,
      callbacks: {
        label: (context) => {
          const label = context.label || "";
          const percentage = context.parsed;
          const actualValue = chartValues.value[context.dataIndex];
          return `${label}: ${actualValue} (${percentage}%)`;
        },
      },
    },
  },
}));

const downloadImage = () => {
  const image = chart_ref.value.chart?.toBase64Image("image/jpeg", 1);
  base64ToJPEG(image, props.title || "pie-chart");
};

defineExpose({
  downloadImage,
  chart_ref,
});
</script>

<style scoped>
.chart-wrapper {
  position: relative;
}

.chart-container {
  position: absolute;
  top: 10px;
  left: 0;
  right: 0;
  bottom: 0;
  width: 100%;
  height: 100%;
}

.no-data-container {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 1.5rem;
}
</style>
