import prisma from "@/lib/prisma";

interface AvailabilityHeatmapProps {
  userId: number;
}

const DAYS = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];
const HOURS = Array.from({ length: 24 }, (_, i) => i);

// Convert hour to display label
function hourLabel(h: number): string {
  if (h === 0) return "12a";
  if (h < 12) return `${h}a`;
  if (h === 12) return "12p";
  return `${h - 12}p`;
}

export default async function AvailabilityHeatmap({
  userId,
}: AvailabilityHeatmapProps) {
  // Query the user's historical lastonline_at patterns
  // We look at the last 90 days of login activity from recently_viewed or session data
  let heatmapData: { day_of_week: number; hour_of_day: number; frequency: bigint }[] = [];

  try {
    // recently_viewed.viewed_at is the activity proxy. Earlier code used
    // `created_at`, which doesn't exist on this table — every call hit the
    // catch and fell through to a messages JOIN that doesn't reflect the
    // escort's online time anyway. Drop the fallback; rely on the new
    // (viewed_user_id, viewed_at) index for a fast GROUP BY.
    heatmapData = await prisma.$queryRawUnsafe<
      { day_of_week: number; hour_of_day: number; frequency: bigint }[]
    >(
      `SELECT EXTRACT(DOW FROM viewed_at)::int AS day_of_week,
              EXTRACT(HOUR FROM viewed_at)::int AS hour_of_day,
              COUNT(*) AS frequency
       FROM recently_viewed
       WHERE viewed_user_id = $1
         AND viewed_at >= NOW() - INTERVAL '90 days'
       GROUP BY day_of_week, hour_of_day
       ORDER BY day_of_week, hour_of_day`,
      userId
    );
  } catch (err) {
    console.error("AvailabilityHeatmap query failed:", err);
  }

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

  // Build the grid: days x hours
  const grid: Record<string, number> = {};
  let maxFreq = 0;

  for (const row of heatmapData) {
    const key = `${row.day_of_week}-${row.hour_of_day}`;
    const freq = Number(row.frequency);
    grid[key] = freq;
    if (freq > maxFreq) maxFreq = freq;
  }

  // Show only hours 6-23 (6am to 11pm) for cleaner display
  const displayHours = HOURS.filter((h) => h >= 6 && h <= 23);

  function getCellColor(freq: number): string {
    if (freq === 0) return "bg-surface-light";
    const intensity = freq / maxFreq;
    if (intensity > 0.7) return "bg-green-500";
    if (intensity > 0.4) return "bg-green-600/60";
    if (intensity > 0.2) return "bg-green-700/40";
    return "bg-green-800/20";
  }

  return (
    <div className="bg-surface rounded-lg p-6">
      <h2 className="text-lg font-semibold mb-1">Usually Available</h2>
      <p className="text-text-muted text-xs mb-4">Based on historical activity patterns</p>

      <div className="overflow-x-auto">
        <div className="min-w-[500px]">
          {/* Hour labels */}
          <div className="flex mb-1 ml-10">
            {displayHours.map((h) => (
              <div
                key={h}
                className="flex-1 text-center text-[9px] text-text-muted"
              >
                {h % 3 === 0 ? hourLabel(h) : ""}
              </div>
            ))}
          </div>

          {/* Rows: one per day */}
          <div className="space-y-1">
            {DAYS.map((dayLabel, dayIndex) => (
              <div key={dayIndex} className="flex items-center gap-1">
                <span className="text-xs text-text-muted w-9 text-right shrink-0">
                  {dayLabel}
                </span>
                <div className="flex flex-1 gap-px">
                  {displayHours.map((hour) => {
                    const freq = grid[`${dayIndex}-${hour}`] || 0;
                    return (
                      <div
                        key={hour}
                        className={`flex-1 h-4 rounded-sm ${getCellColor(freq)} transition-colors`}
                        title={`${dayLabel} ${hourLabel(hour)}: ${freq} visits`}
                      />
                    );
                  })}
                </div>
              </div>
            ))}
          </div>

          {/* Legend */}
          <div className="flex items-center gap-2 mt-3 ml-10">
            <span className="text-[10px] text-text-muted">Less</span>
            <div className="flex gap-px">
              <div className="w-3 h-3 rounded-sm bg-surface-light" />
              <div className="w-3 h-3 rounded-sm bg-green-800/20" />
              <div className="w-3 h-3 rounded-sm bg-green-700/40" />
              <div className="w-3 h-3 rounded-sm bg-green-600/60" />
              <div className="w-3 h-3 rounded-sm bg-green-500" />
            </div>
            <span className="text-[10px] text-text-muted">More</span>
          </div>
        </div>
      </div>
    </div>
  );
}
