<script setup>
import * as am5 from '@amcharts/amcharts5'
import * as am5xy from '@amcharts/amcharts5/xy'
import am5themes_Animated from '@amcharts/amcharts5/themes/Animated'

const props = defineProps({
  chartData: {
    type: Array,
    required: true
  },
  orgNames: {
    type: Array,
    required: true
  }
})

const chartDiv = ref(null)
let root = null
let chart = null

onMounted(() => {
  if (chartDiv.value) {
    // Create root element
    root = am5.Root.new(chartDiv.value)

    // Set themes
    root.setThemes([
      am5themes_Animated.new(root)
    ])

    // Create chart
    chart = root.container.children.push(am5xy.XYChart.new(root, {
      panX: true,
      panY: true,
      wheelX: "panX",
      wheelY: "zoomX",
      pinchZoomX: true
    }))

    // Add cursor with tooltip
    const cursor = chart.set("cursor", am5xy.XYCursor.new(root, {
      behavior: "zoomX"
    }))
    cursor.lineY.set("visible", false)

    // Create a container for the external tooltip
    const tooltipContainer = root.tooltipContainer.children.push(
      am5.Container.new(root, {
        width: am5.percent(100),
        height: am5.percent(100),
        layer: 1000
      })
    )

    // Create tooltip that will show all series values
    const externalTooltip = am5.Tooltip.new(root, {
      getFillFromSprite: false,
      autoTextColor: false,
      pointerOrientation: "left",
      paddingTop: 10,
      paddingBottom: 10,
      paddingLeft: 15,
      paddingRight: 15
    })

    externalTooltip.get("background").setAll({
      fill: am5.color(0xffffff),
      fillOpacity: 0.95,
      stroke: am5.color(0xe5e7eb),
      strokeWidth: 1,
      shadowColor: am5.color(0x000000),
      shadowBlur: 10,
      shadowOpacity: 0.2
    })

    externalTooltip.label.setAll({
      fill: am5.color(0x000000),
      fontSize: 13
    })

    tooltipContainer.children.push(externalTooltip)

    // Create axes
    const xAxis = chart.xAxes.push(am5xy.DateAxis.new(root, {
      baseInterval: { timeUnit: "day", count: 1 },
      renderer: am5xy.AxisRendererX.new(root, {
        minGridDistance: 50
      }),
      tooltip: am5.Tooltip.new(root, {})
    }))

    const yAxis = chart.yAxes.push(am5xy.ValueAxis.new(root, {
      renderer: am5xy.AxisRendererY.new(root, {}),
      numberFormat: "#,###.## €"
    }))

    // Add legend
    const legend = chart.children.push(
      am5.Legend.new(root, {
        centerX: am5.p50,
        x: am5.p50
      })
    )

    // Create series for each organization
    const colors = [
      am5.color(0x3b82f6), // blue
      am5.color(0x10b981), // green
      am5.color(0xf59e0b), // amber
      am5.color(0xef4444), // red
      am5.color(0x8b5cf6), // purple
      am5.color(0xec4899), // pink
      am5.color(0x06b6d4), // cyan
      am5.color(0xf97316), // orange
      am5.color(0x84cc16), // lime
      am5.color(0x6366f1), // indigo
      am5.color(0x14b8a6), // teal
      am5.color(0xeab308)  // yellow
    ]

    const seriesList = []

    props.orgNames.forEach((orgName, index) => {
      const series = chart.series.push(am5xy.LineSeries.new(root, {
        name: orgName,
        xAxis: xAxis,
        yAxis: yAxis,
        valueYField: orgName,
        valueXField: "date",
        stroke: colors[index % colors.length],
        fill: colors[index % colors.length]
      }))

      seriesList.push(series)

      series.strokes.template.setAll({
        strokeWidth: 2
      })

      series.bullets.push(function() {
        return am5.Bullet.new(root, {
          sprite: am5.Circle.new(root, {
            radius: 4,
            fill: series.get("fill")
          })
        })
      })

      series.data.setAll(props.chartData)

      legend.data.push(series)
    })

    // Add cursor event to show all values in external tooltip
    cursor.events.on("cursormoved", function() {
      const dataItem = xAxis.getSeriesItem(seriesList[0], xAxis.toAxisPosition(cursor.getPrivate("positionX")))

      if (dataItem && dataItem.dataContext) {
        let tooltipText = "[bold]" + root.dateFormatter.format(dataItem.dataContext.date, "MMM dd, yyyy") + "[/]\n\n"

        seriesList.forEach((series) => {
          const seriesDataItem = series.dataItems.find(item => item.dataContext.date === dataItem.dataContext.date)
          if (seriesDataItem) {
            const value = seriesDataItem.get("valueY")
            if (value !== undefined && value !== 0) {
              const color = series.get("stroke")
              tooltipText += "[" + color.toString() + "]●[/] " + series.get("name") + ": " +
                           root.numberFormatter.format(value, "#,###.## €") + "\n"
            }
          }
        })

        externalTooltip.label.set("text", tooltipText)
        externalTooltip.set("pointTo", { x: cursor.getPrivate("positionX"), y: 0 })
        externalTooltip.show()
      }
    })

    cursor.events.on("cursorhidden", function() {
      externalTooltip.hide()
    })

    // Make stuff animate on load
    chart.appear(1000, 100)
  }
})

onBeforeUnmount(() => {
  if (root) {
    root.dispose()
  }
})

// Watch for data changes and update chart
watch(() => props.chartData, (newData) => {
  if (chart && chart.series) {
    chart.series.each((series, index) => {
      series.data.setAll(newData)
    })
  }
}, { deep: true })

watch(() => props.orgNames, (newNames) => {
  // Recreate chart when org names change
  if (root) {
    root.dispose()
  }
  nextTick(() => {
    if (chartDiv.value) {
      onMounted()
    }
  })
}, { deep: true })
</script>

<template>
  <div ref="chartDiv" class="chart" style="width: 100%; height: 400px;"></div>
</template>

<style scoped>
.chart {
  min-height: 400px;
}
</style>
