<template>
  <div class="card bg-base-100 shadow-xl">
    <div class="card-body">
      <div class="flex justify-between items-center mb-4">
        <h2 class="card-title">Market Price Trends</h2>
        <div class="join">
          <button 
            class="join-item btn btn-sm" 
            :class="{ 'btn-active': days === 7 }"
            @click="days = 7"
          >7 Days</button>
          <button 
            class="join-item btn btn-sm" 
            :class="{ 'btn-active': days === 30 }"
            @click="days = 30"
          >30 Days</button>
          <button 
            class="join-item btn btn-sm" 
            :class="{ 'btn-active': days === 90 }"
            @click="days = 90"
          >90 Days</button>
        </div>
      </div>
      
      <div v-if="loading" class="flex justify-center items-center h-64">
        <span class="loading loading-spinner loading-lg"></span>
      </div>
      <div v-else class="h-80 w-full relative">
        <Line :data="chartData" :options="chartOptions" />
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, watch, onMounted } from 'vue';
import axios from 'axios';
import authHeader from '../services/auth.header';
import {
  Chart as ChartJS,
  CategoryScale,
  LinearScale,
  PointElement,
  LineElement,
  Title,
  Tooltip,
  Legend
} from 'chart.js';
import { Line } from 'vue-chartjs';

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

const props = defineProps<{
  initialDays?: number;
}>();

const days = ref(props.initialDays || 30);
const loading = ref(true);
const historyData = ref<any[]>([]);

const chartData = ref({
  labels: [] as string[],
  datasets: [] as any[]
});

const chartOptions = {
  responsive: true,
  maintainAspectRatio: false,
  interaction: {
    mode: 'index' as const,
    intersect: false,
  },
  plugins: {
    legend: {
      position: 'top' as const,
    },
    tooltip: {
      callbacks: {
        label: function(context: any) {
          let label = context.dataset.label || '';
          if (label) {
            label += ': ';
          }
          if (context.parsed.y !== null) {
            label += new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD', minimumFractionDigits: 3 }).format(context.parsed.y);
          }
          return label;
        }
      }
    }
  },
  scales: {
    y: {
      ticks: {
        callback: function(value: any) {
            return '$' + value.toFixed(2);
        }
      }
    }
  }
};

const fetchData = async () => {
  loading.value = true;
  try {
    const path = import.meta.env.VITE_BASE_URL + '/info/price/ticker/history';
    const response = await axios.get(path, {
      params: { days: days.value },
      headers: authHeader(),
      withCredentials: true
    });
    
    if (response.data.ok && response.data.history) {
      historyData.value = response.data.history;
      updateChart();
    }
  } catch (error) {
    console.error('Failed to fetch ticker history:', error);
  } finally {
    loading.value = false;
  }
};

const updateChart = () => {
  chartData.value = {
    labels: historyData.value.map(d => formatDate(d.date)),
    datasets: [
      {
        label: 'Heating Oil (HO)',
        borderColor: '#ef4444', // Red
        backgroundColor: '#ef4444',
        data: historyData.value.map(d => d.prices['HO=F'] || null),
        tension: 0.1
      },
      {
        label: 'Crude Oil (CL)',
        borderColor: '#3b82f6', // Blue
        backgroundColor: '#3b82f6',
        data: historyData.value.map(d => d.prices['CL=F'] || null),
        tension: 0.1
      },
      {
        label: 'Gasoline (RB)',
        borderColor: '#22c55e', // Green
        backgroundColor: '#22c55e',
        data: historyData.value.map(d => d.prices['RB=F'] || null),
        tension: 0.1
      }
    ]
  };
};

const formatDate = (dateStr: string) => {
  const date = new Date(dateStr);
  return date.toLocaleDateString(undefined, { month: 'short', day: 'numeric' });
};

// watch(days, () => {
//   fetchData();
// });

// onMounted(() => {
//   fetchData();
// });
</script>
