'use client';

import { useQuery } from '@tanstack/react-query';
import {
  Chart as ChartJS,
  CategoryScale,
  LinearScale,
  PointElement,
  LineElement,
  Title,
  Tooltip,
  Legend,
  Filler,
} from 'chart.js';
import { Line } from 'react-chartjs-2';
import { api } from '@/lib/api';

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

interface MetricsChartProps {
  title: string;
  service: string;
  metric: string;
  from: string;
}

interface MetricPoint {
  timestamp: string;
  value: number;
}

export function MetricsChart({ title, service, metric, from }: MetricsChartProps) {
  const { data, isLoading, error } = useQuery({
    queryKey: ['metrics', service, metric, from],
    queryFn: () => api.get('/api/v1/metrics', { service, name: metric, from }),
    refetchInterval: 30000,
  });

  const metrics: MetricPoint[] = data?.metrics ?? [];

  const chartData = {
    labels: metrics.map((m) => {
      const date = new Date(m.timestamp);
      return date.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
    }),
    datasets: [
      {
        label: title,
        data: metrics.map((m) => m.value),
        borderColor: 'rgb(99, 102, 241)',
        backgroundColor: 'rgba(99, 102, 241, 0.1)',
        fill: true,
        tension: 0.3,
        pointRadius: 0,
        pointHoverRadius: 4,
      },
    ],
  };

  const options = {
    responsive: true,
    maintainAspectRatio: false,
    interaction: {
      intersect: false,
      mode: 'index' as const,
    },
    plugins: {
      legend: {
        display: false,
      },
      tooltip: {
        backgroundColor: 'rgba(17, 17, 27, 0.9)',
        titleColor: '#fff',
        bodyColor: '#a1a1aa',
        borderColor: '#3f3f46',
        borderWidth: 1,
        padding: 12,
        displayColors: false,
        callbacks: {
          label: (context: any) => {
            let value = context.parsed.y;
            if (metric.includes('percent')) {
              return `${value.toFixed(1)}%`;
            }
            if (metric.includes('bytes')) {
              if (value > 1e9) return `${(value / 1e9).toFixed(2)} GB`;
              if (value > 1e6) return `${(value / 1e6).toFixed(2)} MB`;
              if (value > 1e3) return `${(value / 1e3).toFixed(2)} KB`;
              return `${value} B`;
            }
            return value.toFixed(2);
          },
        },
      },
    },
    scales: {
      x: {
        grid: {
          color: 'rgba(63, 63, 70, 0.3)',
        },
        ticks: {
          color: '#71717a',
          maxTicksLimit: 6,
        },
      },
      y: {
        grid: {
          color: 'rgba(63, 63, 70, 0.3)',
        },
        ticks: {
          color: '#71717a',
          callback: (value: number) => {
            if (metric.includes('percent')) {
              return `${value}%`;
            }
            if (metric.includes('bytes')) {
              if (value > 1e9) return `${(value / 1e9).toFixed(0)}G`;
              if (value > 1e6) return `${(value / 1e6).toFixed(0)}M`;
              if (value > 1e3) return `${(value / 1e3).toFixed(0)}K`;
              return value;
            }
            return value;
          },
        },
        beginAtZero: true,
        suggestedMax: metric.includes('percent') ? 100 : undefined,
      },
    },
  };

  // Calculate current/avg/max
  const values = metrics.map((m) => m.value);
  const current = values.length > 0 ? values[values.length - 1] : 0;
  const avg = values.length > 0 ? values.reduce((a, b) => a + b, 0) / values.length : 0;
  const max = values.length > 0 ? Math.max(...values) : 0;

  const formatValue = (v: number) => {
    if (metric.includes('percent')) return `${v.toFixed(1)}%`;
    if (metric.includes('bytes')) {
      if (v > 1e9) return `${(v / 1e9).toFixed(2)} GB`;
      if (v > 1e6) return `${(v / 1e6).toFixed(2)} MB`;
      if (v > 1e3) return `${(v / 1e3).toFixed(2)} KB`;
      return `${v.toFixed(0)} B`;
    }
    return v.toFixed(2);
  };

  return (
    <div className="bg-gray-900/50 rounded-lg border border-gray-800 p-4">
      <div className="flex items-center justify-between mb-4">
        <h3 className="text-lg font-semibold text-white">{title}</h3>
        <div className="flex items-center gap-4 text-sm">
          <span className="text-gray-400">
            Current: <span className="text-white">{formatValue(current)}</span>
          </span>
          <span className="text-gray-400">
            Avg: <span className="text-white">{formatValue(avg)}</span>
          </span>
          <span className="text-gray-400">
            Max: <span className="text-white">{formatValue(max)}</span>
          </span>
        </div>
      </div>
      <div className="h-48">
        {isLoading ? (
          <div className="flex items-center justify-center h-full text-gray-500">
            Loading...
          </div>
        ) : error ? (
          <div className="flex items-center justify-center h-full text-red-400">
            Error loading data
          </div>
        ) : metrics.length === 0 ? (
          <div className="flex items-center justify-center h-full text-gray-500">
            No data available
          </div>
        ) : (
          <Line data={chartData} options={options as any} />
        )}
      </div>
    </div>
  );
}
