import { createClient, getBrowserUserId } from "@/lib/supabase/client";
import type { ChartPoint } from "@/components/notes/blocks/chart-block-view";

export type ChartDataSourceType = "task_completion_rate" | "journal_mood_trend";

export interface ChartDataSource {
  type: ChartDataSourceType;
  days?: number;
}

const MOOD_SCORE: Record<string, number> = {
  terrible: 1,
  bad: 2,
  neutral: 3,
  good: 4,
  great: 5,
};

function weeklyBuckets(days: number) {
  return Math.min(6, Math.max(2, Math.round(days / 7)));
}

function bucketIndex(iso: string, days: number, buckets: number, bucketMs: number) {
  const age = Date.now() - new Date(iso).getTime();
  if (age < 0 || age > days * 24 * 60 * 60 * 1000) return -1;
  return buckets - 1 - Math.min(buckets - 1, Math.floor(age / bucketMs));
}

async function fetchTaskCompletionRate(days: number): Promise<ChartPoint[]> {
  const supabase = createClient();
  const userId = await getBrowserUserId();
  const buckets = weeklyBuckets(days);
  const counts = new Array(buckets).fill(0);
  if (!userId) return counts.map((value, i) => ({ label: `W${i + 1}`, value }));

  const since = new Date(Date.now() - days * 24 * 60 * 60 * 1000).toISOString();
  const { data } = await supabase
    .from("tasks")
    .select("completed_at")
    .eq("user_id", userId)
    .eq("status", "done")
    .gte("completed_at", since);

  const bucketMs = (days * 24 * 60 * 60 * 1000) / buckets;
  for (const row of data || []) {
    if (!row.completed_at) continue;
    const idx = bucketIndex(row.completed_at, days, buckets, bucketMs);
    if (idx >= 0) counts[idx] += 1;
  }
  return counts.map((value, i) => ({ label: `W${i + 1}`, value }));
}

async function fetchJournalMoodTrend(days: number): Promise<ChartPoint[]> {
  const supabase = createClient();
  const userId = await getBrowserUserId();
  const buckets = weeklyBuckets(days);
  const sums = new Array(buckets).fill(0);
  const counts = new Array(buckets).fill(0);
  if (!userId) return sums.map((value, i) => ({ label: `W${i + 1}`, value }));

  const since = new Date(Date.now() - days * 24 * 60 * 60 * 1000).toISOString().slice(0, 10);
  const { data } = await supabase
    .from("journal_entries")
    .select("entry_date, mood")
    .eq("user_id", userId)
    .gte("entry_date", since);

  const bucketMs = (days * 24 * 60 * 60 * 1000) / buckets;
  for (const row of data || []) {
    if (!row.mood) continue;
    const score = MOOD_SCORE[row.mood];
    if (!score) continue;
    const idx = bucketIndex(row.entry_date, days, buckets, bucketMs);
    if (idx < 0) continue;
    sums[idx] += score;
    counts[idx] += 1;
  }
  return sums.map((sum, i) => ({ label: `W${i + 1}`, value: counts[i] ? Math.round((sum / counts[i]) * 10) / 10 : 0 }));
}

export async function fetchLiveChartData(source: ChartDataSource): Promise<ChartPoint[]> {
  const days = source.days || 30;
  if (source.type === "task_completion_rate") return fetchTaskCompletionRate(days);
  if (source.type === "journal_mood_trend") return fetchJournalMoodTrend(days);
  return [];
}
