"use client";

interface Rate {
  name: string;
  in_call: string | number | null;
  out_call: string | number | null;
}

interface PricingChartProps {
  rates: Rate[];
  currency?: string;
}

function parseDurationMinutes(name: string): number | null {
  const lower = name.toLowerCase().trim();
  // Match patterns like "1 hour", "30 minutes", "2 hours", "15 min", "overnight"
  const hourMatch = lower.match(/(\d+)\s*h/);
  const minMatch = lower.match(/(\d+)\s*min/);
  if (hourMatch) return parseInt(hourMatch[1]) * 60;
  if (minMatch) return parseInt(minMatch[1]);
  if (lower.includes("overnight") || lower.includes("night")) return 720;
  if (lower.includes("dinner")) return 180;
  // Try bare numbers — assume minutes if < 10 assume hours, else minutes
  const numMatch = lower.match(/^(\d+)$/);
  if (numMatch) {
    const n = parseInt(numMatch[1]);
    return n <= 10 ? n * 60 : n;
  }
  return null;
}

function parsePrice(value: string | number | null): number | null {
  if (value === null || value === undefined || value === "" || value === "-")
    return null;
  const num = typeof value === "number" ? value : parseFloat(String(value).replace(/[^0-9.]/g, ""));
  return isNaN(num) || num <= 0 ? null : num;
}

interface RateData {
  name: string;
  price: number;
  minutes: number;
  perHour: number;
  type: "incall" | "outcall";
}

export default function PricingChart({ rates, currency = "GBP" }: PricingChartProps) {
  // Build rate data from both incall and outcall
  const rateData: RateData[] = [];

  for (const rate of rates) {
    const minutes = parseDurationMinutes(rate.name);
    if (!minutes) continue;

    const incallPrice = parsePrice(rate.in_call);
    if (incallPrice) {
      rateData.push({
        name: rate.name,
        price: incallPrice,
        minutes,
        perHour: (incallPrice / minutes) * 60,
        type: "incall",
      });
    }

    const outcallPrice = parsePrice(rate.out_call);
    if (outcallPrice) {
      rateData.push({
        name: rate.name,
        price: outcallPrice,
        minutes,
        perHour: (outcallPrice / minutes) * 60,
        type: "outcall",
      });
    }
  }

  if (rateData.length === 0) return null;

  // Use incall rates for the chart (primary), fall back to outcall
  const incallRates = rateData.filter((r) => r.type === "incall");
  const chartRates = incallRates.length > 0 ? incallRates : rateData.filter((r) => r.type === "outcall");

  if (chartRates.length < 2) return null;

  // Sort by duration
  chartRates.sort((a, b) => a.minutes - b.minutes);

  const maxPerHour = Math.max(...chartRates.map((r) => r.perHour));
  const bestValue = chartRates.reduce((best, r) =>
    r.perHour < best.perHour ? r : best
  );

  const currencySymbol =
    currency === "GBP" ? "\u00A3" : currency === "EUR" ? "\u20AC" : currency === "USD" ? "$" : "";

  return (
    <div className="bg-surface rounded-lg p-6">
      <h2 className="text-lg font-semibold mb-1">Price Per Hour by Duration</h2>
      <p className="text-text-muted text-sm mb-4">
        {chartRates[0].type === "incall" ? "Incall" : "Outcall"} rates
      </p>
      <div className="space-y-3">
        {chartRates.map((rate) => {
          const widthPct = Math.max((rate.perHour / maxPerHour) * 100, 8);
          const isBest = rate === bestValue;
          return (
            <div key={`${rate.name}-${rate.type}`} className="flex items-center gap-3">
              <div className="w-24 text-sm text-text-muted shrink-0 text-right">
                {rate.name}
              </div>
              <div className="flex-1 relative">
                <div className="h-8 bg-surface-light rounded-full overflow-hidden">
                  <div
                    className={`h-full rounded-full flex items-center px-3 transition-all duration-500 ${
                      isBest
                        ? "bg-gradient-to-r from-yellow-500 to-amber-400"
                        : "bg-gradient-to-r from-primary/80 to-primary/40"
                    }`}
                    style={{ width: `${widthPct}%` }}
                  >
                    <span
                      className={`text-xs font-semibold whitespace-nowrap ${
                        isBest ? "text-black" : "text-white"
                      }`}
                    >
                      {currencySymbol}{Math.round(rate.perHour)}/hr
                    </span>
                  </div>
                </div>
                {isBest && (
                  <span className="absolute -top-1 -right-1 bg-yellow-500 text-black text-[10px] font-bold px-1.5 py-0.5 rounded-full shadow-lg">
                    BEST VALUE
                  </span>
                )}
              </div>
              <div className="w-20 text-sm text-text-muted shrink-0">
                {currencySymbol}{rate.price} total
              </div>
            </div>
          );
        })}
      </div>
      <p className="text-xs text-text-muted mt-4 flex items-center gap-1.5">
        <span className="inline-block w-3 h-3 rounded-full bg-gradient-to-r from-yellow-500 to-amber-400" />
        Best value: <strong className="text-yellow-400">{bestValue.name}</strong> at {currencySymbol}{Math.round(bestValue.perHour)}/hour
      </p>
    </div>
  );
}
