"use client";
import { useEffect, useState } from "react";
import Link from "next/link";
import { Copy, Check, Gift, ShoppingBag, Target } from "lucide-react";

const REASON_LABELS: Record<string, string> = {
  video_play: "Watched a video",
  daily_login: "Logged in today",
  login_streak: "Login streak bonus",
  post_create: "Created a post",
  reaction_given: "Reacted to a post",
  reaction_received: "Someone reacted to your post",
  tip_support: "Supported the creators",
  redemption: "Redeemed points",
};

export default function PointsPageClient({
  points,
  activity,
  plans,
  pointsPerDollar,
  currentTier,
}: {
  points: number;
  activity: { id: string; amount: number; reason: string; createdAt: string }[];
  plans: { id: string; name: string; tier: string; price: number }[];
  pointsPerDollar: number;
  currentTier: string;
}) {
  const [referralLink, setReferralLink] = useState("");
  const [referralCount, setReferralCount] = useState(0);
  const [copied, setCopied] = useState(false);
  const [redeeming, setRedeeming] = useState<string | null>(null);
  const [redeemMsg, setRedeemMsg] = useState("");

  useEffect(() => {
    fetch("/api/referral")
      .then((r) => r.json())
      .then((d) => {
        setReferralLink(d.referralLink || "");
        setReferralCount(d.referralCount || 0);
      });
  }, []);

  function copyLink() {
    navigator.clipboard.writeText(referralLink);
    setCopied(true);
    setTimeout(() => setCopied(false), 2000);
  }

  async function redeem(planId: string) {
    setRedeeming(planId);
    setRedeemMsg("");
    const res = await fetch("/api/points/redeem-membership", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ planId }),
    });
    const data = await res.json();
    setRedeeming(null);
    if (!res.ok) {
      setRedeemMsg(data.error);
      return;
    }
    setRedeemMsg(`✓ Redeemed! You're now on the ${data.newTier} plan.`);
    setTimeout(() => window.location.reload(), 1500);
  }

  return (
    <div className="max-w-3xl mx-auto">
      <h1 className="text-2xl font-bold mb-1">Your points</h1>
      <p className="text-neutral-400 text-sm mb-6">Earn points from activity and missions. Redeem them for memberships and shop items.</p>

      <div className="grid sm:grid-cols-2 gap-4 mb-6">
        <div className="card p-5">
          <p className="text-xs text-neutral-500 mb-1">LIFETIME BALANCE</p>
          <p className="text-3xl font-bold text-amber-400">{points.toLocaleString()}</p>
          <p className="text-xs text-neutral-500 mt-1">Points never expire.</p>
        </div>
        <div className="card p-5">
          <p className="text-xs text-neutral-500 mb-1">REDEEM POINTS</p>
          <p className="text-xs text-neutral-400 mb-3">{pointsPerDollar} points = $1 toward memberships and digital products.</p>
          <div className="flex gap-2">
            <a href="#redeem-membership" className="btn-primary px-3 py-1.5 text-xs">Membership</a>
            <Link href="/shop" className="btn-secondary px-3 py-1.5 text-xs">Shop</Link>
            <Link href="/community" className="btn-secondary px-3 py-1.5 text-xs">Missions</Link>
          </div>
        </div>
      </div>

      <div className="card p-5 mb-6">
        <h3 className="font-bold mb-1 flex items-center gap-2"><Gift size={16} className="text-red-500" /> Invite friends, earn points</h3>
        <p className="text-xs text-neutral-500 mb-4">Share your link. Check your admin-set mission for the reward when friends join.</p>
        <div className="flex items-center justify-between text-xs text-neutral-500 mb-2">
          <span>PROGRESS</span>
          <span>{referralCount} friend{referralCount === 1 ? "" : "s"} joined so far</span>
        </div>
        <p className="text-xs text-neutral-500 mb-1">YOUR INVITATION LINK</p>
        <div className="flex gap-2">
          <input readOnly value={referralLink} className="flex-1 bg-neutral-900 border border-neutral-800 rounded-md px-3 py-2 text-xs outline-none" />
          <button onClick={copyLink} className="btn-primary px-4 py-2 text-xs flex items-center gap-1.5 shrink-0">
            {copied ? <Check size={13} /> : <Copy size={13} />} {copied ? "Copied" : "Copy link"}
          </button>
        </div>
        <p className="text-xs text-neutral-600 mt-2">Friends must register using this link so we can credit your invite.</p>
      </div>

      <div id="redeem-membership" className="card p-5 mb-6">
        <h3 className="font-bold mb-1 flex items-center gap-2"><ShoppingBag size={16} className="text-purple-400" /> Redeem for Membership</h3>
        <p className="text-xs text-neutral-500 mb-4">Instantly switch your tier using points instead of paying — no card needed.</p>
        {redeemMsg && <p className={`text-sm mb-3 ${redeemMsg.startsWith("✓") ? "text-green-500" : "text-red-500"}`}>{redeemMsg}</p>}
        <div className="grid sm:grid-cols-3 gap-3">
          {plans.map((p) => {
            const cost = Math.round(p.price * pointsPerDollar);
            const canAfford = points >= cost;
            const isCurrent = p.tier === currentTier;
            return (
              <div key={p.id} className="border border-neutral-800 rounded-lg p-3">
                <p className="font-semibold text-sm">{p.name}</p>
                <p className="text-amber-400 text-sm font-bold mt-1">{cost.toLocaleString()} pts</p>
                <button
                  onClick={() => redeem(p.id)}
                  disabled={!canAfford || isCurrent || redeeming === p.id}
                  className="btn-secondary w-full mt-2 py-1.5 text-xs disabled:opacity-40"
                >
                  {isCurrent ? "Current Plan" : redeeming === p.id ? "Redeeming..." : canAfford ? "Redeem" : "Not enough points"}
                </button>
              </div>
            );
          })}
        </div>
      </div>

      <div className="card p-5 mb-6">
        <h3 className="font-bold mb-3 flex items-center gap-2"><Target size={16} className="text-blue-400" /> How to use your points</h3>
        <div className="grid sm:grid-cols-3 gap-4 text-xs text-neutral-400">
          <div>
            <p className="font-semibold text-white mb-1">Membership plans</p>
            <p>Redeem points above for a month of access on any tier.</p>
          </div>
          <div>
            <p className="font-semibold text-white mb-1">Shop digital products</p>
            <p>Browse the shop — products with a points price unlock instantly.</p>
          </div>
          <div>
            <p className="font-semibold text-white mb-1">Earn more points</p>
            <p>Complete missions, participate in the community, and invite friends.</p>
          </div>
        </div>
      </div>

      <div className="card p-5">
        <h3 className="font-bold mb-3">Recent activity</h3>
        {activity.length === 0 ? (
          <p className="text-neutral-500 text-sm">No activity yet.</p>
        ) : (
          <div className="space-y-2">
            {activity.map((a) => (
              <div key={a.id} className="flex items-center justify-between text-sm border-b border-neutral-900 pb-2 last:border-0">
                <span className="text-neutral-300">{REASON_LABELS[a.reason] || a.reason}</span>
                <span className={a.amount >= 0 ? "text-green-500" : "text-red-500"}>
                  {a.amount >= 0 ? "+" : ""}{a.amount}
                </span>
              </div>
            ))}
          </div>
        )}
      </div>
    </div>
  );
}
