<template>
  <div class="w-full h-[400px] relative">
    <Line
      v-if="chartData"
      :data="chartData as any"
      :options="chartOptions as any"
    />
    <div v-else class="flex items-center justify-center h-full">
      <span class="loading loading-spinner loading-lg"></span>
    </div>
  </div>
</template>

<script setup lang="ts">
import { computed } from 'vue';
import {
  Chart as ChartJS,
  CategoryScale,
  LinearScale,
  PointElement,
  LineElement,
  Title,
  Tooltip,
  Legend,
  Filler,
  TimeScale
} from 'chart.js';
import { Line } from 'vue-chartjs';
import 'chartjs-adapter-dayjs-4';
import zoomPlugin from 'chartjs-plugin-zoom';

// Register Chart.js components
ChartJS.register(
  CategoryScale,
  LinearScale,
  PointElement,
  LineElement,
  Title,
  Tooltip,
  Legend,
  Filler,
  TimeScale,
  zoomPlugin
);

interface DataPoint {
  x: string | Date;
  y: number;
}

interface Dataset {
  label: string;
  data: DataPoint[];
  borderColor: string;
  backgroundColor: string;
}

interface Props {
  datasets: Dataset[];
  title?: string;
  xAxisLabel?: string;
  yAxisLabel?: string;
  useTimeScale?: boolean;
}

const props = withDefaults(defineProps<Props>(), {
  title: '',
  xAxisLabel: 'Date',
  yAxisLabel: 'Gallons',
  useTimeScale: true
});

// Color palette for different years
const colors = [
  { border: 'rgb(59, 130, 246)', background: 'rgba(59, 130, 246, 0.1)' },   // Blue
  { border: 'rgb(16, 185, 129)', background: 'rgba(16, 185, 129, 0.1)' },   // Green
  { border: 'rgb(249, 115, 22)', background: 'rgba(249, 115, 22, 0.1)' },   // Orange
  { border: 'rgb(139, 92, 246)', background: 'rgba(139, 92, 246, 0.1)' },   // Purple
];

const chartData = computed(() => {
  if (!props.datasets || props.datasets.length === 0) {
    return null;
  }

  return {
    datasets: props.datasets.map((ds, index) => ({
      label: ds.label,
      data: ds.data,
      borderColor: ds.borderColor || colors[index % colors.length].border,
      backgroundColor: ds.backgroundColor || colors[index % colors.length].background,
      tension: 0.3,
      fill: false,
      pointRadius: 3,
      pointHoverRadius: 6,
      spanGaps: true
    }))
  };
});

const chartOptions = computed(() => ({
  responsive: true,
  maintainAspectRatio: false,
  interaction: {
    mode: 'index',
    intersect: false,
  },
  plugins: {
    title: {
      display: !!props.title,
      text: props.title,
      font: { size: 16 }
    },
    legend: {
      position: 'top',
    },
    tooltip: {
      callbacks: {
        label: (context: { parsed: { y: number | null }; dataset: { label?: string } }) => {
          const value = context.parsed?.y ?? 0;
          return `${context.dataset.label || ''}: ${value.toLocaleString()} gallons`;
        }
      }
    },
    zoom: {
      pan: {
        enabled: true,
        mode: 'x',
      },
      zoom: {
        wheel: {
          enabled: true,
        },
        pinch: {
          enabled: true,
        },
        mode: 'x',
      }
    }
  },
  scales: {
    x: props.useTimeScale ? {
      type: 'time',
      time: {
        unit: 'day',
        displayFormats: {
          day: 'MMM D',
          week: 'MMM D',
          month: 'MMM YYYY'
        }
      },
      title: {
        display: true,
        text: props.xAxisLabel
      }
    } : {
      title: {
        display: true,
        text: props.xAxisLabel
      }
    },
    y: {
      beginAtZero: true,
      title: {
        display: true,
        text: props.yAxisLabel
      },
      ticks: {
        callback: (value: string | number) => {
          if (typeof value === 'number') {
            return value.toLocaleString();
          }
          return value;
        }
      }
    }
  }
}));
</script>
