<template>
  <div class="chart-container">
    <canvas ref="stackedBarChart"></canvas>
  </div>
</template>

<script>

import {
  Chart as ChartJS,
  CategoryScale,
  LinearScale,
  BarElement,
  BarController,
  ScatterController,
  Title,
  Tooltip,
  Legend,
  PointElement
} from 'chart.js';

// Register the required components
ChartJS.register(
    CategoryScale,
    LinearScale,
    BarElement,
    BarController,
    ScatterController,
    Title,
    Tooltip,
    Legend,
    PointElement
);

export default {
  name: "ReportChart",
  props: {
    title: {
      type: String,
      required: true
    },
    mek_a : {
      type: Number,
      required: true
    },
    logistics_costs : {
      type: Number,
      required: true
    },
    risk_cost : {
      type: Number,
      required: true
    },
    chance_cost : {
      type: Number,
      required: true
    },
    scale : {
      type: Number,
      required: true
    }
  },
  computed: {
    totalCosts() {
      return this.mek_a + this.logistics_costs;
    },
    upperError() {
      return (this.risk_cost - this.totalCosts);
    },
    lowerError() {
      return (this.totalCosts - this.chance_cost);
    }
  },
  mounted() {
    const ctx = this.$refs.stackedBarChart.getContext('2d');

    // Sample data
    const data = {
      labels: [this.title],
      datasets: [
        {
          label: 'MEK A',
          data: [this.mek_a],
          backgroundColor: '#6B869C', // Blue-gray like in your image
          borderColor: '#6B869C',
          borderWidth: 1,
          stack: 'stack1'
        },
        {
          label: 'Logistics costs',
          data: [this.logistics_costs],
          backgroundColor: '#5AF0B4', // Mint green like in your image
          borderColor: '#5AF0B4',
          borderWidth: 1,
          stack: 'stack1'
        },
        {
          label: 'Error Bars',
          type: 'scatter',
          backgroundColor: 'transparent',
          borderColor: 'transparent',
          pointRadius: 0,
          showLine: false,
          stack: 'errorBars',
          errorBars: {
            plus: [this.upperError], // Upper error
            minus: [this.lowerError]  // Lower error
          }
        }
      ]
    };

    const config = {
      type: 'bar',
      data: data,
      options: {
        responsive: true,
        maintainAspectRatio: false,
        scales: {
          x: {
            stacked: true,
            grid: {
              display: false
            },
            ticks: {
              display: false //this will remove only the label
            },
            border: {
              display: false
            }
          },
          y: {
            stacked: true, // Don't stack for error bars
            beginAtZero: true,
            max: this.scale,
            grid: {
              color: '#E3EDFF'
            },
            ticks: {
              display: false //this will remove only the label
            },
            border: {
              display: false
            }
          },

        },
        plugins: {
          legend: {
            display: false,
            labels: {
              filter: function (item, chart) {
                // Hide the error bars dataset from legend
                return item.text !== 'Error Bars';
              }
            }
          },
          tooltip: {
            filter: function (tooltipItem) {
              // Don't show tooltip for error bars dataset
              return tooltipItem.datasetIndex !== 2;
            }
          }
        },
        animation: {
          onComplete: function () {
            // Draw error bars after animation completes
            drawErrorBars(this);
          }
        }
      },
      plugins: [{
        afterDraw: function (chart) {
          drawErrorBars(chart);
        }
      }]
    };

    function drawErrorBars(chart) {
      const ctx = chart.ctx;
      const meta = chart.getDatasetMeta(0); // Get metadata for first dataset
      const errorData = chart.data.datasets[2].errorBars;

      if (!errorData) return;

      ctx.strokeStyle = '#002F54';
      ctx.lineWidth = 1;

      meta.data.forEach((bar, index) => {
        const x = bar.x;

        // Calculate the top of the stacked bar (this is the center point for error bars)
        const topValue = chart.data.datasets[0].data[index] + chart.data.datasets[1].data[index];
        const yCenterPixel = chart.scales.y.getPixelForValue(topValue);

        // Error bar measurements
        const errorUp = errorData.plus[index];
        const errorDown = errorData.minus[index];

        // Convert error values to pixel distances
        const errorUpPixels = chart.scales.y.getPixelForValue(topValue) - chart.scales.y.getPixelForValue(topValue + errorUp);
        const errorDownPixels = chart.scales.y.getPixelForValue(topValue - errorDown) - chart.scales.y.getPixelForValue(topValue);

        const yErrorTop = yCenterPixel - errorUpPixels;
        const yErrorBottom = yCenterPixel + errorDownPixels;

        // Draw vertical line
        ctx.beginPath();
        ctx.moveTo(x, yErrorTop);
        ctx.lineTo(x, yErrorBottom);
        ctx.stroke();

        // Draw top cap
        ctx.beginPath();
        ctx.moveTo(x - 8, yErrorTop);
        ctx.lineTo(x + 8, yErrorTop);
        ctx.stroke();

        // Draw bottom cap
        ctx.beginPath();
        ctx.moveTo(x - 8, yErrorBottom);
        ctx.lineTo(x + 8, yErrorBottom);
        ctx.stroke();
      });
    }

    // Create the chart
    const stackedBarChart = new ChartJS(ctx, config);
  }
}
</script>


<style scoped>


.chart-container {
  position: relative;
  height: 300px;
}

</style>