import prisma from "@/lib/prisma";

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

interface PriceComparisonProps {
  rates: Rate[];
  cityId: number;
}

export default async function PriceComparison({
  rates,
  cityId,
}: PriceComparisonProps) {
  // Get user's primary in_call rate (first available)
  const userRate = rates.find((r) => r.in_call && r.in_call > 0)?.in_call;
  if (!userRate) return null;

  // Query average in_call rate for users in the same city
  const avgResult = await prisma.rateUser.aggregate({
    where: {
      user: { city_id: cityId },
      in_call: { gt: 0 },
    },
    _avg: { in_call: true },
    _count: true,
  });

  const avgRate = avgResult._avg.in_call;
  const count = avgResult._count;

  if (!avgRate || count < 2) return null;

  const diff = ((userRate - avgRate) / avgRate) * 100;

  let indicator: { label: string; color: string; bgColor: string };
  if (diff < -15) {
    indicator = {
      label: "Below average",
      color: "text-blue-400",
      bgColor: "bg-blue-400/10 border-blue-400/20",
    };
  } else if (diff > 15) {
    indicator = {
      label: "Above average",
      color: "text-amber-400",
      bgColor: "bg-amber-400/10 border-amber-400/20",
    };
  } else {
    indicator = {
      label: "Average",
      color: "text-green-400",
      bgColor: "bg-green-400/10 border-green-400/20",
    };
  }

  return (
    <div className="bg-surface rounded-xl border border-surface-light p-5 space-y-3">
      <h3 className="text-sm font-semibold text-text flex items-center gap-2">
        <svg
          className="w-4 h-4 text-gold"
          fill="none"
          stroke="currentColor"
          viewBox="0 0 24 24"
        >
          <path
            strokeLinecap="round"
            strokeLinejoin="round"
            strokeWidth={2}
            d="M9 19v-6a2 2 0 00-2-2H5a2 2 0 00-2 2v6a2 2 0 002 2h2a2 2 0 002-2zm0 0V9a2 2 0 012-2h2a2 2 0 012 2v10m-6 0a2 2 0 002 2h2a2 2 0 002-2m0 0V5a2 2 0 012-2h2a2 2 0 012 2v14a2 2 0 01-2 2h-2a2 2 0 01-2-2z"
          />
        </svg>
        How Your Rates Compare
      </h3>

      <div className="flex items-center justify-between text-sm">
        <div>
          <p className="text-text-muted">Your rate</p>
          <p className="text-text font-semibold">{userRate} credits</p>
        </div>
        <div className="text-right">
          <p className="text-text-muted">City average</p>
          <p className="text-text font-semibold">{Math.round(avgRate)} credits</p>
        </div>
      </div>

      <div
        className={`inline-flex items-center gap-1.5 text-xs font-medium px-2.5 py-1 rounded-full border ${indicator.bgColor} ${indicator.color}`}
      >
        <span className="w-1.5 h-1.5 rounded-full bg-current" />
        {indicator.label}
        <span className="text-text-muted ml-1">
          (based on {count} providers)
        </span>
      </div>
    </div>
  );
}
