"use client";

import { useEffect, useState, useCallback } from "react";
import { createClient } from "@/lib/supabase/client";
import Card from "@/components/ui/Card";
import Badge from "@/components/ui/Badge";
import Spinner from "@/components/ui/Spinner";
import { formatDate } from "@/lib/format";
import { Gift, Lock, CheckCircle2 } from "lucide-react";

export default function Rewards() {
  const supabase = createClient();
  const [loading, setLoading] = useState(true);
  const [merit, setMerit] = useState(0);
  const [rewards, setRewards] = useState<any[]>([]);
  const [earned, setEarned] = useState<Record<string, string>>({}); // reward_id -> earned_at

  const load = useCallback(async () => {
    const { data: u } = await supabase.auth.getUser();
    if (!u.user) return;
    const [prof, rw, mine] = await Promise.all([
      supabase.from("profiles").select("total_merit").eq("id", u.user.id).single(),
      supabase.from("rewards").select("id, name, description, points_required").order("points_required"),
      supabase.from("volunteer_rewards").select("reward_id, earned_at").eq("volunteer_id", u.user.id),
    ]);
    setMerit(prof.data?.total_merit ?? 0);
    setRewards(rw.data ?? []);
    const map: Record<string, string> = {};
    (mine.data ?? []).forEach((v: any) => (map[v.reward_id] = v.earned_at));
    setEarned(map);
    setLoading(false);
  }, [supabase]);

  useEffect(() => {
    load();
  }, [load]);

  if (loading) return <Spinner label="Loading rewards…" />;

  return (
    <div className="space-y-6">
      <div>
        <h1 className="text-2xl font-extrabold text-ink">Rewards</h1>
        <p className="text-sm text-muted">
          You have <span className="font-bold text-emerald">{merit} merit points</span>. Keep
          volunteering to unlock more.
        </p>
      </div>

      <div className="grid gap-4 md:grid-cols-2 xl:grid-cols-3">
        {rewards.length === 0 && (
          <Card>
            <p className="px-5 py-10 text-center text-sm text-muted">No rewards available yet.</p>
          </Card>
        )}
        {rewards.map((r) => {
          const isEarned = !!earned[r.id];
          const reached = merit >= r.points_required;
          const pct = Math.min(100, Math.round((merit / Math.max(1, r.points_required)) * 100));
          return (
            <Card key={r.id} className="flex flex-col p-5">
              <div className="mb-2 flex items-start justify-between">
                <div
                  className={`flex h-11 w-11 items-center justify-center rounded-card ${
                    isEarned ? "bg-emerald text-white" : reached ? "bg-emerald-light text-emerald" : "bg-sand text-muted"
                  }`}
                >
                  {isEarned ? <CheckCircle2 size={22} /> : reached ? <Gift size={22} /> : <Lock size={20} />}
                </div>
                {isEarned ? (
                  <Badge tone="emerald">Earned</Badge>
                ) : reached ? (
                  <Badge tone="teal">Unlocked</Badge>
                ) : (
                  <Badge tone="neutral">{r.points_required} pts</Badge>
                )}
              </div>
              <h2 className="font-bold text-ink">{r.name}</h2>
              {r.description && <p className="mt-1 text-sm text-muted">{r.description}</p>}

              {isEarned ? (
                <p className="mt-3 text-xs font-medium text-emerald">
                  Awarded on {formatDate(earned[r.id])}
                </p>
              ) : (
                <div className="mt-3">
                  <div className="h-2 w-full overflow-hidden rounded-full bg-sand">
                    <div className="h-full rounded-full bg-emerald" style={{ width: `${pct}%` }} />
                  </div>
                  <p className="mt-1 text-xs text-muted">
                    {merit} / {r.points_required} points
                  </p>
                </div>
              )}
            </Card>
          );
        })}
      </div>
    </div>
  );
}
