"use client";

import { useEffect, useState } from "react";
import { useSession } from "next-auth/react";
import { useRouter } from "next/navigation";

interface ReferralHistory {
  id: number;
  referral_code: string;
  status: string;
  reward_credits: number;
  referred_username: string | null;
  referred_user_type: 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[];
}

const statusConfig: Record<string, { label: string; className: string }> = {
  completed: { label: "Rewarded", className: "bg-green-500/20 text-green-400" },
  pending: { label: "Pending", className: "bg-yellow-500/20 text-yellow-400" },
  pending_purchase: { label: "Awaiting Purchase", className: "bg-blue-500/20 text-blue-400" },
  expired: { label: "Expired", className: "bg-gray-500/20 text-gray-400" },
};

export default function ProviderReferralsPage() {
  const { data: session, status: authStatus } = useSession();
  const router = useRouter();
  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(() => {
    if (authStatus === "unauthenticated") {
      router.push("/login");
      return;
    }
    if (authStatus === "authenticated") {
      fetchData();
    }
  }, [authStatus, router]);

  async function fetchData() {
    try {
      const res = await fetch("/api/referrals");
      if (res.ok) {
        setData(await res.json());
      } else {
        setError("Failed to load referral data.");
      }
    } catch {
      setError("Failed to load referral data.");
    } 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 {
      // silent
    } finally {
      setGenerating(false);
    }
  }

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

  function copyLink() {
    if (!referralLink) return;
    navigator.clipboard.writeText(referralLink);
    setCopied(true);
    setTimeout(() => setCopied(false), 2500);
  }

  function shareWhatsApp() {
    if (!referralLink) return;
    window.open(
      `https://wa.me/?text=${encodeURIComponent(`Join AdultWorld and get 6 months FREE Premium! ${referralLink}`)}`,
      "_blank"
    );
  }

  function shareTelegram() {
    if (!referralLink) return;
    window.open(
      `https://t.me/share/url?url=${encodeURIComponent(referralLink)}&text=${encodeURIComponent("Join AdultWorld and get 6 months FREE Premium!")}`,
      "_blank"
    );
  }

  function shareX() {
    if (!referralLink) return;
    window.open(
      `https://twitter.com/intent/tweet?text=${encodeURIComponent(`Join AdultWorld and get 6 months FREE Premium! ${referralLink}`)}`,
      "_blank"
    );
  }

  if (loading || authStatus === "loading") {
    return (
      <div className="max-w-5xl mx-auto py-12">
        <div className="animate-pulse space-y-6">
          <div className="h-8 w-64 bg-surface rounded" />
          <div className="grid grid-cols-1 sm:grid-cols-5 gap-4">
            {Array.from({ length: 5 }).map((_, i) => (
              <div key={i} className="h-24 bg-surface rounded-xl" />
            ))}
          </div>
          <div className="h-40 bg-surface rounded-xl" />
        </div>
      </div>
    );
  }

  if (error) {
    return (
      <div className="max-w-5xl mx-auto py-12 text-center text-red-400">
        {error}
      </div>
    );
  }

  const stats = data?.stats ?? {
    total: 0,
    successful: 0,
    pending: 0,
    credits_earned: 0,
    premium_months_earned: 0,
  };

  return (
    <div className="max-w-5xl mx-auto py-8 space-y-8">
      {/* Header */}
      <div>
        <h1 className="text-3xl font-bold text-gold font-heading">
          Referral Program
        </h1>
        <p className="text-text-muted mt-1">
          Invite providers and clients to earn Premium time and credits.
        </p>
      </div>

      {/* Stats Cards */}
      <div className="grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-5 gap-3 md:gap-4">
        <StatCard label="Total Referrals" value={stats.total} color="text-blue-400" />
        <StatCard label="Successful" value={stats.successful} color="text-green-400" />
        <StatCard label="Pending" value={stats.pending} color="text-yellow-400" />
        <StatCard
          label="Credits Earned"
          value={stats.credits_earned.toLocaleString()}
          color="text-primary"
          icon={
            <svg className="w-4 h-4 text-primary/60" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 8c-1.657 0-3 .895-3 2s1.343 2 3 2 3 .895 3 2-1.343 2-3 2m0-8c1.11 0 2.08.402 2.599 1M12 8V7m0 1v8m0 0v1m0-1c-1.11 0-2.08-.402-2.599-1M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
            </svg>
          }
        />
        <StatCard
          label="Premium Months"
          value={stats.premium_months_earned}
          color="text-gold"
          icon={
            <svg className="w-4 h-4 text-gold/60" fill="currentColor" viewBox="0 0 24 24">
              <path d="M12 2l3.09 6.26L22 9.27l-5 4.87 1.18 6.88L12 17.77l-6.18 3.25L7 14.14 2 9.27l6.91-1.01L12 2z" />
            </svg>
          }
        />
      </div>

      {/* Referral Link Section */}
      <div className="bg-surface rounded-xl border border-surface-light p-6">
        <h2 className="text-lg font-semibold mb-4">Your Referral Link</h2>
        {data?.referral_code ? (
          <div className="space-y-4">
            {/* Link + Copy */}
            <div className="flex flex-col sm:flex-row items-stretch sm: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 select-all">
                {referralLink}
              </div>
              <button
                onClick={copyLink}
                className="px-5 py-3 rounded-lg bg-primary hover:bg-primary-dark text-white font-medium transition-colors text-sm shrink-0"
              >
                {copied ? "Copied!" : "Copy Link"}
              </button>
            </div>

            {/* Share Buttons */}
            <div className="flex flex-wrap items-center gap-3">
              <span className="text-text-muted text-sm">Share via:</span>
              <button
                onClick={shareWhatsApp}
                className="inline-flex items-center gap-2 px-4 py-2 rounded-lg bg-green-600/20 text-green-400 hover:bg-green-600/30 transition-colors text-sm font-medium"
              >
                <svg className="w-4 h-4" fill="currentColor" viewBox="0 0 24 24">
                  <path d="M17.472 14.382c-.297-.149-1.758-.867-2.03-.967-.273-.099-.471-.148-.67.15-.197.297-.767.966-.94 1.164-.173.199-.347.223-.644.075-.297-.15-1.255-.463-2.39-1.475-.883-.788-1.48-1.761-1.653-2.059-.173-.297-.018-.458.13-.606.134-.133.298-.347.446-.52.149-.174.198-.298.298-.497.099-.198.05-.371-.025-.52-.075-.149-.669-1.612-.916-2.207-.242-.579-.487-.5-.669-.51-.173-.008-.371-.01-.57-.01-.198 0-.52.074-.792.372-.272.297-1.04 1.016-1.04 2.479 0 1.462 1.065 2.875 1.213 3.074.149.198 2.096 3.2 5.077 4.487.709.306 1.262.489 1.694.625.712.227 1.36.195 1.871.118.571-.085 1.758-.719 2.006-1.413.248-.694.248-1.289.173-1.413-.074-.124-.272-.198-.57-.347m-5.421 7.403h-.004a9.87 9.87 0 01-5.031-1.378l-.361-.214-3.741.982.998-3.648-.235-.374a9.86 9.86 0 01-1.51-5.26c.001-5.45 4.436-9.884 9.888-9.884 2.64 0 5.122 1.03 6.988 2.898a9.825 9.825 0 012.893 6.994c-.003 5.45-4.437 9.884-9.885 9.884m8.413-18.297A11.815 11.815 0 0012.05 0C5.495 0 .16 5.335.157 11.892c0 2.096.547 4.142 1.588 5.945L.057 24l6.305-1.654a11.882 11.882 0 005.683 1.448h.005c6.554 0 11.89-5.335 11.893-11.893a11.821 11.821 0 00-3.48-8.413z" />
                </svg>
                WhatsApp
              </button>
              <button
                onClick={shareTelegram}
                className="inline-flex items-center gap-2 px-4 py-2 rounded-lg bg-blue-500/20 text-blue-400 hover:bg-blue-500/30 transition-colors text-sm font-medium"
              >
                <svg className="w-4 h-4" fill="currentColor" viewBox="0 0 24 24">
                  <path d="M11.944 0A12 12 0 0 0 0 12a12 12 0 0 0 12 12 12 12 0 0 0 12-12A12 12 0 0 0 12 0a12 12 0 0 0-.056 0zm4.962 7.224c.1-.002.321.023.465.14a.506.506 0 0 1 .171.325c.016.093.036.306.02.472-.18 1.898-.962 6.502-1.36 8.627-.168.9-.499 1.201-.82 1.23-.696.065-1.225-.46-1.9-.902-1.056-.693-1.653-1.124-2.678-1.8-1.185-.78-.417-1.21.258-1.91.177-.184 3.247-2.977 3.307-3.23.007-.032.014-.15-.056-.212s-.174-.041-.249-.024c-.106.024-1.793 1.14-5.061 3.345-.479.33-.913.49-1.302.48-.428-.008-1.252-.241-1.865-.44-.752-.245-1.349-.374-1.297-.789.027-.216.325-.437.893-.663 3.498-1.524 5.83-2.529 6.998-3.014 3.332-1.386 4.025-1.627 4.476-1.635z" />
                </svg>
                Telegram
              </button>
              <button
                onClick={shareX}
                className="inline-flex items-center gap-2 px-4 py-2 rounded-lg bg-white/10 text-white hover:bg-white/20 transition-colors text-sm font-medium"
              >
                <svg className="w-4 h-4" fill="currentColor" viewBox="0 0 24 24">
                  <path d="M18.244 2.25h3.308l-7.227 8.26 8.502 11.24H16.17l-5.214-6.817L4.99 21.75H1.68l7.73-8.835L1.254 2.25H8.08l4.713 6.231zm-1.161 17.52h1.833L7.084 4.126H5.117z" />
                </svg>
                X / Twitter
              </button>
            </div>

            {/* Code display */}
            <div className="flex items-center gap-2 text-sm text-text-muted pt-1">
              <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>

      {/* Referred Providers Table */}
      <div className="bg-surface rounded-xl border border-surface-light p-6">
        <h2 className="text-lg font-semibold mb-4">Referred Users</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">Username</th>
                  <th className="pb-3 font-medium">Signup Date</th>
                  <th className="pb-3 font-medium">Status</th>
                  <th className="pb-3 font-medium">Reward</th>
                </tr>
              </thead>
              <tbody>
                {data.history.map((item) => {
                  const sc = statusConfig[item.status] ?? {
                    label: item.status,
                    className: "bg-gray-500/20 text-gray-400",
                  };
                  return (
                    <tr
                      key={item.id}
                      className="border-b border-surface-light last:border-0"
                    >
                      <td className="py-3 text-sm font-medium">
                        {item.referred_username ?? (
                          <span className="text-text-muted italic">
                            Awaiting signup
                          </span>
                        )}
                      </td>
                      <td className="py-3 text-text-muted text-sm">
                        {new Date(item.created_at).toLocaleDateString()}
                      </td>
                      <td className="py-3">
                        <span
                          className={`inline-block px-2 py-0.5 rounded text-xs font-medium ${sc.className}`}
                        >
                          {sc.label}
                        </span>
                      </td>
                      <td className="py-3 text-sm">
                        {item.status === "completed" ? (
                          <span className="text-primary font-medium">
                            +{item.reward_credits.toLocaleString()} credits
                          </span>
                        ) : (
                          <span className="text-text-muted">-</span>
                        )}
                      </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>

      {/* How It Works */}
      <div className="bg-surface rounded-xl border border-surface-light p-6">
        <h2 className="text-lg font-semibold mb-5">How It Works</h2>
        <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
          {/* Provider Referral */}
          <div className="bg-gradient-to-br from-amber-500/10 to-yellow-500/5 rounded-xl border border-amber-500/20 p-5">
            <div className="flex items-center gap-3 mb-3">
              <div className="w-10 h-10 rounded-full bg-amber-500/20 flex items-center justify-center">
                <svg className="w-5 h-5 text-amber-400" fill="currentColor" viewBox="0 0 24 24">
                  <path d="M12 2l3.09 6.26L22 9.27l-5 4.87 1.18 6.88L12 17.77l-6.18 3.25L7 14.14 2 9.27l6.91-1.01L12 2z" />
                </svg>
              </div>
              <h3 className="font-bold text-amber-400">Refer a Provider</h3>
            </div>
            <ul className="space-y-2 text-sm text-text-muted">
              <li className="flex items-start gap-2">
                <svg className="w-4 h-4 text-green-400 mt-0.5 shrink-0" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M5 13l4 4L19 7" />
                </svg>
                <span>
                  <strong className="text-white">They get:</strong> 6 months FREE Premium
                </span>
              </li>
              <li className="flex items-start gap-2">
                <svg className="w-4 h-4 text-green-400 mt-0.5 shrink-0" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M5 13l4 4L19 7" />
                </svg>
                <span>
                  <strong className="text-white">You get:</strong> 3 months Premium + 5,000 credits
                </span>
              </li>
            </ul>
          </div>

          {/* Client Referral */}
          <div className="bg-gradient-to-br from-blue-500/10 to-indigo-500/5 rounded-xl border border-blue-500/20 p-5">
            <div className="flex items-center gap-3 mb-3">
              <div className="w-10 h-10 rounded-full bg-blue-500/20 flex items-center justify-center">
                <svg className="w-5 h-5 text-blue-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M16 7a4 4 0 11-8 0 4 4 0 018 0zM12 14a7 7 0 00-7 7h14a7 7 0 00-7-7z" />
                </svg>
              </div>
              <h3 className="font-bold text-blue-400">Refer a Client</h3>
            </div>
            <ul className="space-y-2 text-sm text-text-muted">
              <li className="flex items-start gap-2">
                <svg className="w-4 h-4 text-green-400 mt-0.5 shrink-0" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M5 13l4 4L19 7" />
                </svg>
                <span>
                  <strong className="text-white">Both get:</strong> 1,000 credits when they buy their first credits
                </span>
              </li>
              <li className="flex items-start gap-2">
                <svg className="w-4 h-4 text-blue-400 mt-0.5 shrink-0" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
                </svg>
                <span className="text-text-muted">
                  Credits are awarded after their first purchase
                </span>
              </li>
            </ul>
          </div>
        </div>

        {/* Steps */}
        <div className="mt-6 flex flex-col sm:flex-row items-start sm:items-center gap-4 text-sm text-text-muted">
          <div className="flex items-center gap-2">
            <span className="w-7 h-7 rounded-full bg-primary/20 text-primary font-bold text-xs flex items-center justify-center">1</span>
            Share your unique link
          </div>
          <svg className="w-4 h-4 text-text-muted/40 hidden sm:block" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 5l7 7-7 7" />
          </svg>
          <div className="flex items-center gap-2">
            <span className="w-7 h-7 rounded-full bg-primary/20 text-primary font-bold text-xs flex items-center justify-center">2</span>
            They sign up using your link
          </div>
          <svg className="w-4 h-4 text-text-muted/40 hidden sm:block" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 5l7 7-7 7" />
          </svg>
          <div className="flex items-center gap-2">
            <span className="w-7 h-7 rounded-full bg-primary/20 text-primary font-bold text-xs flex items-center justify-center">3</span>
            Both earn rewards automatically
          </div>
        </div>
      </div>
    </div>
  );
}

function StatCard({
  label,
  value,
  color,
  icon,
}: {
  label: string;
  value: number | string;
  color: string;
  icon?: React.ReactNode;
}) {
  return (
    <div className="bg-surface rounded-xl border border-surface-light p-4 md:p-5 text-center">
      {icon && <div className="flex justify-center mb-1">{icon}</div>}
      <p className="text-text-muted text-xs mb-1">{label}</p>
      <p className={`text-2xl md:text-3xl font-bold ${color}`}>{value}</p>
    </div>
  );
}
