"use client";

import type { PriceHistoryPoint } from "@/app/gunbuilder/[categoryId]/[partId]/data";

interface PricingHistoryGraphProps {
  data: PriceHistoryPoint[];
  currentPrice: number;
}

export function PricingHistoryGraph({
  data,
  currentPrice,
}: PricingHistoryGraphProps) {
  if (data.length === 0) return null;

  // Calculate chart dimensions
  const width = 100;
  const height = 60;
  const padding = 4;

  // Find min and max prices for scaling
  const prices = data.map((d) => d.price);
  const minPrice = Math.min(...prices);
  const maxPrice = Math.max(...prices);
  const priceRange = maxPrice - minPrice || 1; // Avoid division by zero

  // Generate path points
  const points = data.map((point, index) => {
    const x = padding + ((index / (data.length - 1)) * (width - padding * 2));
    const normalizedPrice = (point.price - minPrice) / priceRange;
    const y = padding + (height - padding * 2) * (1 - normalizedPrice);
    return { x, y, price: point.price };
  });

  // Create SVG path
  const pathData = points
    .map((point, index) => `${index === 0 ? "M" : "L"} ${point.x} ${point.y}`)
    .join(" ");

  // Create area path (for gradient fill)
  const areaPath = `${pathData} L ${width - padding} ${height - padding} L ${padding} ${height - padding} Z`;

  // Format date for display
  const formatDate = (dateStr: string) => {
    const date = new Date(dateStr);
    return date.toLocaleDateString("en-US", { month: "short", day: "numeric" });
  };

  return (
    <div className="w-full">
      <div className="mb-4 flex items-center justify-between">
        <div>
          <div className="text-xs font-semibold tracking-[0.16em] uppercase text-zinc-400">
            Price History (30 Days)
          </div>
          <div className="mt-1 text-xs text-zinc-500">
            Current: <span className="text-amber-300 font-semibold">${currentPrice.toFixed(2)}</span>
          </div>
        </div>
        <div className="text-xs text-zinc-500">
          {formatDate(data[0].date)} - {formatDate(data[data.length - 1].date)}
        </div>
      </div>

      <div className="relative w-full h-32 rounded-md border border-zinc-800 bg-zinc-900/30 p-3">
        <svg
          viewBox={`0 0 ${width} ${height}`}
          className="w-full h-full"
          preserveAspectRatio="none"
        >
          <defs>
            <linearGradient id="priceGradient" x1="0%" y1="0%" x2="0%" y2="100%">
              <stop offset="0%" stopColor="#fbbf24" stopOpacity="0.3" />
              <stop offset="100%" stopColor="#fbbf24" stopOpacity="0.05" />
            </linearGradient>
          </defs>
          {/* Area fill */}
          <path
            d={areaPath}
            fill="url(#priceGradient)"
          />
          {/* Line */}
          <path
            d={pathData}
            fill="none"
            stroke="#fbbf24"
            strokeWidth="1.5"
            strokeLinecap="round"
            strokeLinejoin="round"
          />
          {/* Current price indicator */}
          <circle
            cx={points[points.length - 1].x}
            cy={points[points.length - 1].y}
            r="2"
            fill="#fbbf24"
          />
        </svg>
      </div>

      <div className="mt-2 flex items-center justify-between text-xs text-zinc-500">
        <span>Low: ${minPrice.toFixed(2)}</span>
        <span>High: ${maxPrice.toFixed(2)}</span>
      </div>
    </div>
  );
}

