<template>
  <div v-bind="$attrs" class="chart-wrapper full-width full-height">
    <q-resize-observer @resize="onResize" />
    <div v-if="hasData" class="chart-container">
      <Line
        ref="chart_ref"
        :options="chartLineOptions"
        :data="chartLineData"
        :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 { Line } from "vue-chartjs";
import {
  Chart as ChartJS,
  Title,
  Tooltip,
  Legend,
  LineElement,
  PointElement,
  CategoryScale,
  LinearScale,
} from "chart.js";
import ChartDataLabels from "chartjs-plugin-datalabels";
import { base64ToJPEG } from "src/helpers/convertBase64Image";
import { useQuasar, getCssVar, colors } from "quasar";

ChartJS.register(
  Title,
  Tooltip,
  Legend,
  LineElement,
  PointElement,
  CategoryScale,
  LinearScale,
);

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

const props = defineProps({
  data: {
    type: Object,
    default: () => ({
      chart_data: [],
    }),
  },
  title: {
    type: String,
    default: "",
  },
  dataSetLabel: {
    type: String,
    default: "Valores",
  },
  labelX: {
    type: String,
    default: "Categorias",
  },
  labelY: {
    type: String,
    default: "Valores",
  },
  backgroundColors: {
    type: Array,
    default: 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 gridColor = computed(() => {
  return $q.dark.isActive ? "rgba(255, 255, 255, 0.1)" : "rgba(0, 0, 0, 0.1)";
});

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 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 chartLineData = computed(() => ({
  labels: chartLabels.value,
  datasets: [
    {
      label: props.dataSetLabel,
      data: chartValues.value,
      borderColor: chartThemeColors.value[0],
      backgroundColor: chartThemeColors.value,
      fill: false,
      cubicInterpolationMode: "monotone",
      tension: 0.4,
    },
  ],
}));

const chartLineOptions = computed(() => ({
  responsive: true,
  maintainAspectRatio: false,
  plugins: {
    legend: {
      display: false,
    },
    title: {
      display: !!props.title,
      text: props.title,
      color: labelColor.value,
      font: {
        size: 16,
      },
    },
    datalabels: {
      color: dataLabelColor.value,
      anchor: "end",
      align: "top",
      offset: 4,
      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,
    },
  },
  interaction: {
    intersect: false,
  },
  scales: {
    x: {
      display: true,
      title: {
        display: !!props.labelX,
        text: props.labelX,
        color: labelColor.value,
        font: {
          size: 14,
        },
      },
      grid: {
        color: gridColor.value,
        tickColor: gridColor.value,
      },
      ticks: {
        color: labelColor.value,
      },
    },
    y: {
      display: true,
      title: {
        display: !!props.labelY,
        text: props.labelY,
        color: labelColor.value,
        font: {
          size: 14,
        },
      },
      suggestedMin: 0,
      grid: {
        color: gridColor.value,
        tickColor: gridColor.value,
      },
      ticks: {
        color: labelColor.value,
        stepSize: 1,
      },
    },
  },
}));

const downloadImage = () => {
  if (!chart_ref.value?.chart) return;
  const image = chart_ref.value.chart.toBase64Image("image/jpeg", 1);
  base64ToJPEG(image, props.title || "line-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>
