"use client";

import { useEffect, useState } from "react";

interface ReferralHistory {
  id: number;
  referral_code: string;
  status: string;
  reward_credits: number;
  referred_username: string | null;
  created_at: string;
}

interface ReferralData {
  referral_code: string | null;
  stats: {
    total: number;
    successful: number;
    pending: number;
    credits_earned: number;
    premium_months_earned: number;
  };
  history: ReferralHistory[];
}

export default function ReferralsPage() {
  const [data, setData] = useState<ReferralData | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [generating, setGenerating] = useState(false);
  const [copied, setCopied] = useState(false);

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

  async function fetchData() {
    try {
      const res = await fetch("/api/referrals");
      if (res.ok) {
        setData(await res.json());
      } else {
        setError("Failed to load referral data. Please try again later.");
      }
    } catch {
      setError("Failed to load referral data. Please try again later.");
    } finally {
      setLoading(false);
    }
  }

  async function generateCode() {
    setGenerating(true);
    try {
      const res = await fetch("/api/referrals", { method: "POST" });
      if (res.ok) {
        const result = await res.json();
        setData((prev) =>
          prev
            ? { ...prev, referral_code: result.referral_code }
            : prev
        );
      }
    } catch {
      alert("Failed to generate referral code");
    } finally {
      setGenerating(false);
    }
  }

  function copyLink() {
    if (!data?.referral_code) return;
    const link = `https://adultworld.ai/register?ref=${data.referral_code}`;
    navigator.clipboard.writeText(link);
    setCopied(true);
    setTimeout(() => setCopied(false), 2000);
  }

  if (loading) {
    return (
      <div className="text-center py-16 text-text-muted">Loading...</div>
    );
  }

  if (error) {
    return (
      <div className="text-center py-16 text-red-400">{error}</div>
    );
  }

  const referralLink = data?.referral_code
    ? `https://adultworld.ai/register?ref=${data.referral_code}`
    : null;

  return (
    <div className="max-w-4xl mx-auto py-8">
      <h1 className="text-3xl font-bold text-gold mb-2 font-heading">
        Referral Program
      </h1>
      <p className="text-text-muted mb-8">
        Invite friends and earn credits when they sign up.
      </p>

      {/* Referral Code Section */}
      <div className="bg-surface rounded-xl border border-surface-light p-6 mb-8">
        <h2 className="text-lg font-semibold mb-4">Your Referral Link</h2>
        {data?.referral_code ? (
          <div className="space-y-4">
            <div className="flex items-center gap-3">
              <div className="flex-1 bg-background rounded-lg border border-surface-light px-4 py-3 text-sm font-mono truncate">
                {referralLink}
              </div>
              <button
                onClick={copyLink}
                className="px-4 py-3 rounded-lg bg-primary hover:bg-primary-dark text-white font-medium transition-colors text-sm shrink-0"
              >
                {copied ? "Copied!" : "Copy"}
              </button>
            </div>
            <div className="flex items-center gap-2 text-sm text-text-muted">
              <span>Your code:</span>
              <code className="bg-surface-light px-2 py-1 rounded text-primary font-mono font-semibold">
                {data.referral_code}
              </code>
            </div>
          </div>
        ) : (
          <button
            onClick={generateCode}
            disabled={generating}
            className="px-6 py-3 rounded-lg bg-primary hover:bg-primary-dark text-white font-medium transition-colors disabled:opacity-50"
          >
            {generating ? "Generating..." : "Generate Referral Code"}
          </button>
        )}
      </div>

      {/* Stats */}
      <div className="grid grid-cols-1 sm:grid-cols-3 gap-4 mb-8">
        <div className="bg-surface rounded-xl border border-surface-light p-5 text-center">
          <p className="text-text-muted text-sm mb-1">Total Referrals</p>
          <p className="text-3xl font-bold text-text">
            {data?.stats.total ?? 0}
          </p>
        </div>
        <div className="bg-surface rounded-xl border border-surface-light p-5 text-center">
          <p className="text-text-muted text-sm mb-1">Successful</p>
          <p className="text-3xl font-bold text-green-400">
            {data?.stats.successful ?? 0}
          </p>
        </div>
        <div className="bg-surface rounded-xl border border-surface-light p-5 text-center">
          <p className="text-text-muted text-sm mb-1">Credits Earned</p>
          <p className="text-3xl font-bold text-primary">
            {data?.stats.credits_earned ?? 0}
          </p>
        </div>
      </div>

      {/* Referral History */}
      <div className="bg-surface rounded-xl border border-surface-light p-6">
        <h2 className="text-lg font-semibold mb-4">Referral History</h2>
        {data?.history && data.history.length > 0 ? (
          <div className="overflow-x-auto">
            <table className="w-full text-left">
              <thead>
                <tr className="border-b border-surface-light text-text-muted text-sm">
                  <th className="pb-3 font-medium">User</th>
                  <th className="pb-3 font-medium">Status</th>
                  <th className="pb-3 font-medium">Credits</th>
                  <th className="pb-3 font-medium">Date</th>
                </tr>
              </thead>
              <tbody>
                {data.history.map((item) => (
                  <tr
                    key={item.id}
                    className="border-b border-surface-light last:border-0"
                  >
                    <td className="py-3 text-sm">
                      {item.referred_username ?? (
                        <span className="text-text-muted italic">Pending</span>
                      )}
                    </td>
                    <td className="py-3">
                      <span
                        className={`inline-block px-2 py-0.5 rounded text-xs font-medium ${
                          item.status === "completed"
                            ? "bg-green-500/20 text-green-400"
                            : item.status === "pending"
                            ? "bg-yellow-500/20 text-yellow-400"
                            : "bg-gray-500/20 text-gray-400"
                        }`}
                      >
                        {item.status}
                      </span>
                    </td>
                    <td className="py-3 text-primary text-sm font-medium">
                      {item.status === "completed"
                        ? `+${item.reward_credits}`
                        : "-"}
                    </td>
                    <td className="py-3 text-text-muted text-sm">
                      {new Date(item.created_at).toLocaleDateString()}
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        ) : (
          <p className="text-text-muted text-sm text-center py-8">
            No referrals yet. Share your link to get started!
          </p>
        )}
      </div>
    </div>
  );
}
