"use client";

import { useState } from "react";
import type { CarPriceHistory, PriceHistoryEntry } from "@/lib/types";

// ── helpers ───────────────────────────────────────────────────────────────────

function fmtINR(n: number): string {
  if (n >= 10_000_000) return `₹${(n / 10_000_000).toFixed(2)} Cr`;
  if (n >= 100_000)    return `₹${(n / 100_000).toFixed(1)} L`;
  return `₹${n.toLocaleString("en-IN")}`;
}

function fmtDate(iso: string): string {
  return new Date(iso).toLocaleDateString("en-IN", { day: "numeric", month: "short", year: "2-digit" });
}

function fmtDateShort(iso: string): string {
  return new Date(iso).toLocaleDateString("en-IN", { day: "numeric", month: "short" });
}

// ── SVG chart ─────────────────────────────────────────────────────────────────

const W  = 600;
const H  = 180;
const PL = 10;   // left pad (labels are outside)
const PR = 10;
const PT = 16;
const PB = 28;   // for x-axis labels
const IW = W - PL - PR;
const IH = H - PT - PB;

interface ChartProps {
  history: PriceHistoryEntry[];
  color: string;
  fillColor: string;
}

function PriceSVG({ history, color, fillColor }: ChartProps) {
  const [hovered, setHovered] = useState<number | null>(null);
  const n = history.length;

  const prices = history.map((h) => h.price);
  const rawMin  = Math.min(...prices);
  const rawMax  = Math.max(...prices);
  const pad     = (rawMax - rawMin) * 0.15 || rawMax * 0.05;
  const minP    = rawMin - pad;
  const maxP    = rawMax + pad;
  const range   = maxP - minP || 1;

  const toX = (i: number) => PL + (i / Math.max(n - 1, 1)) * IW;
  const toY = (p: number) => PT + IH - ((p - minP) / range) * IH;

  // Line and area paths
  const pts = history.map((h, i) => `${toX(i).toFixed(1)},${toY(h.price).toFixed(1)}`);
  const linePath = pts.map((p, i) => `${i === 0 ? "M" : "L"}${p}`).join(" ");
  const areaPath =
    `${linePath} ` +
    `L${toX(n - 1).toFixed(1)},${(PT + IH).toFixed(1)} ` +
    `L${toX(0).toFixed(1)},${(PT + IH).toFixed(1)} Z`;

  // X-axis tick indices (show at most 6 labels)
  const step = Math.max(1, Math.floor(n / 6));
  const xTicks = Array.from({ length: n }, (_, i) => i).filter(
    (i) => i === 0 || i === n - 1 || i % step === 0
  );

  const hoveredEntry = hovered !== null ? history[hovered] : null;

  return (
    <div className="relative w-full">
      <svg
        viewBox={`0 0 ${W} ${H}`}
        className="w-full"
        style={{ height: "auto" }}
        onMouseLeave={() => setHovered(null)}
      >
        <defs>
          <linearGradient id="priceGradFill" x1="0" y1="0" x2="0" y2="1">
            <stop offset="0%"   stopColor={fillColor} stopOpacity="0.5" />
            <stop offset="100%" stopColor={fillColor} stopOpacity="0.02" />
          </linearGradient>
        </defs>

        {/* Area fill */}
        <path d={areaPath} fill="url(#priceGradFill)" />

        {/* Line */}
        <path
          d={linePath}
          fill="none"
          stroke={color}
          strokeWidth="2.5"
          strokeLinecap="round"
          strokeLinejoin="round"
        />

        {/* X-axis labels */}
        {xTicks.map((i) => (
          <text
            key={i}
            x={toX(i)}
            y={H - 4}
            textAnchor="middle"
            fontSize="10"
            fill="#9ca3af"
            fontFamily="sans-serif"
          >
            {fmtDateShort(history[i].recordedAt)}
          </text>
        ))}

        {/* Dots — only render on last, first, and hovered */}
        {history.map((h, i) => {
          const isEndpoint = i === 0 || i === n - 1;
          const isHov      = hovered === i;
          if (!isEndpoint && !isHov) return null;
          return (
            <circle
              key={i}
              cx={toX(i)}
              cy={toY(h.price)}
              r={isHov ? 6 : 4}
              fill={isHov ? color : "#fff"}
              stroke={color}
              strokeWidth="2"
              style={{ cursor: "pointer" }}
              onMouseEnter={() => setHovered(i)}
            />
          );
        })}

        {/* Invisible hover targets across the full width */}
        {history.map((_, i) => (
          <rect
            key={`hit-${i}`}
            x={toX(i) - IW / (2 * Math.max(n - 1, 1))}
            y={PT}
            width={IW / Math.max(n - 1, 1)}
            height={IH}
            fill="transparent"
            onMouseEnter={() => setHovered(i)}
          />
        ))}
      </svg>

      {/* Tooltip */}
      {hoveredEntry && hovered !== null && (
        <div
          className="absolute pointer-events-none bg-gray-900 text-white rounded-xl px-3 py-2 text-xs shadow-xl z-10"
          style={{
            left: `${(toX(hovered) / W) * 100}%`,
            top:  `${((toY(hoveredEntry.price) - PT) / H) * 100}%`,
            transform: "translate(-50%, -120%)",
            whiteSpace: "nowrap",
          }}
        >
          <p className="font-black">{fmtINR(hoveredEntry.price)}</p>
          <p className="opacity-70">{fmtDate(hoveredEntry.recordedAt)}</p>
          {hoveredEntry.changeType !== "initial" && (
            <p className={hoveredEntry.changeType === "decrease" ? "text-green-400" : "text-red-400"}>
              {hoveredEntry.changeType === "decrease" ? "↓" : "↑"}{" "}
              {fmtINR(Math.abs(hoveredEntry.changeAmount))} ({Math.abs(hoveredEntry.changePct).toFixed(1)}%)
            </p>
          )}
        </div>
      )}
    </div>
  );
}

// ── Main export ───────────────────────────────────────────────────────────────

export default function PriceHistoryChart({
  data,
}: {
  data: CarPriceHistory;
}) {
  const { history, currentPrice, previousPrice, changeAmount, changePct, changeType,
          lowestPrice, highestPrice } = data;

  const isDown    = changeType === "decrease";
  const isUp      = changeType === "increase";
  const color     = isDown ? "#16a34a" : isUp ? "#dc2626" : "#2563eb";
  const fillColor = isDown ? "#bbf7d0" : isUp ? "#fecaca" : "#bfdbfe";
  const bgClass   = isDown ? "bg-green-50 border-green-200" : isUp ? "bg-red-50 border-red-200" : "bg-blue-50 border-blue-200";
  const textClass = isDown ? "text-green-700" : isUp ? "text-red-700" : "text-blue-700";
  const arrow     = isDown ? "↓" : isUp ? "↑" : "—";

  const hasChart = history.length >= 2;

  return (
    <div className="rounded-[32px] bg-white border border-gray-200/60 p-6 shadow-[0_10px_40px_rgba(0,0,0,0.05)] mb-6 mt-4">
      {/* Header */}
      <div className="flex items-start justify-between mb-5">
        <div>
          <p className="text-[10px] uppercase tracking-[0.2em] text-blue-600 font-black mb-1">
            Price Intelligence
          </p>
          <h2 className="text-xl font-black text-gray-900">Price History</h2>
        </div>

        {/* Change badge */}
        {changeType && changeType !== "initial" && (
          <div className={`flex items-center gap-1.5 px-3 py-1.5 rounded-2xl border text-sm font-black ${bgClass} ${textClass}`}>
            <span>{arrow}</span>
            <span>{fmtINR(Math.abs(changeAmount))}</span>
            <span className="opacity-70 font-semibold text-xs">
              ({Math.abs(changePct).toFixed(1)}%)
            </span>
          </div>
        )}
      </div>

      {/* Chart or empty state */}
      {hasChart ? (
        <div className="mb-5">
          <PriceSVG history={history} color={color} fillColor={fillColor} />
        </div>
      ) : (
        <div className="flex items-center justify-center h-24 rounded-2xl bg-gray-50 border border-gray-100 mb-5 text-sm text-gray-400 font-semibold">
          Tracking price from today — chart will appear after the next update
        </div>
      )}

      {/* Stats row */}
      <div className="grid grid-cols-2 sm:grid-cols-4 gap-3">
        {[
          {
            label: "Current Price",
            value: fmtINR(currentPrice),
            color: "text-gray-900",
          },
          {
            label: "Previous Price",
            value: previousPrice ? fmtINR(previousPrice) : "—",
            color: "text-gray-500",
          },
          {
            label: "All-time Low",
            value: fmtINR(lowestPrice),
            color: "text-green-600",
          },
          {
            label: "All-time High",
            value: fmtINR(highestPrice),
            color: "text-red-500",
          },
        ].map(({ label, value, color: c }) => (
          <div key={label} className="rounded-2xl bg-gray-50 border border-gray-100 p-4">
            <p className={`text-base font-black ${c}`}>{value}</p>
            <p className="text-[11px] text-gray-400 font-semibold mt-0.5">{label}</p>
          </div>
        ))}
      </div>

      {/* Tracking note */}
      {data.firstRecordedAt && (
        <p className="text-[11px] text-gray-400 mt-4 text-center">
          Tracking since {fmtDate(data.firstRecordedAt)}
          {data.totalChanges ? ` · ${data.totalChanges} price change${data.totalChanges !== 1 ? "s" : ""} recorded` : ""}
        </p>
      )}
    </div>
  );
}
