"use client";

import { useState, useEffect } from "react";
import { useAuth } from "@/lib/AuthContext";
import { useRouter } from "next/navigation";
import {
  Users,
  Gift,
  Share2,
  Copy,
  Check,
  ExternalLink,
  TrendingUp,
  Crown,
} from "lucide-react";
import ErrorFeedback from "@/components/ErrorFeedback";

interface ReferralStats {
  totalReferrals: number;
  upgradedCount: number;
  totalEarned: number;
  referralCode: string;
  shareLink: string;
}

interface ToastState {
  type: "success" | "error";
  text: string;
}

export default function ReferPage() {
  const { user, token, loading } = useAuth();
  const router = useRouter();

  const [stats, setStats] = useState<ReferralStats | null>(null);
  const [dataLoading, setDataLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [toast, setToast] = useState<ToastState | null>(null);
  const [copied, setCopied] = useState(false);

  useEffect(() => {
    if (!loading && !token) router.push("/auth");
  }, [loading, token, router]);

  useEffect(() => {
    if (token) {
      fetchStats();
    }
  }, [token]);

  const fetchStats = async () => {
    setDataLoading(true);
    setError(null);
    try {
      const res = await fetch("/mobile/api/referrals/stats", {
        headers: { Authorization: `Bearer ${token}` },
      });
      if (!res.ok) {
        const err = await res.json().catch(() => ({}));
        throw new Error(err.error || "Failed to load referral stats");
      }
      const data: ReferralStats = await res.json();
      setStats(data);
    } catch (err: unknown) {
      const message =
        err instanceof Error ? err.message : "Something went wrong";
      setError(message);
    } finally {
      setDataLoading(false);
    }
  };

  const getShareLink = (): string => {
    const code = stats?.referralCode || "";
    const base =
      (typeof window !== "undefined" &&
        (window as any).NEXT_PUBLIC_APP_URL) ||
      process.env.NEXT_PUBLIC_APP_URL ||
      "https://falahos.my/mobile";
    return `${base}/auth?ref=${code}`;
  };

  const handleShare = async () => {
    const link = getShareLink();
    const shareData = {
      title: "Join me on Falah",
      text: "Assalamu alaikum! Join me on Falah — the Islamic lifestyle app for daily AI coaching, Quran, and community. Use my referral link to get started!",
      url: link,
    };

    if (typeof navigator !== "undefined" && navigator.share) {
      try {
        await navigator.share(shareData);
        showToast("success", "Shared successfully!");
      } catch {
        // User cancelled or share failed — don't show error
      }
    } else {
      // Fallback: copy link instead
      handleCopyLink();
    }
  };

  const handleCopyLink = async () => {
    const link = getShareLink();
    try {
      await navigator.clipboard.writeText(link);
      setCopied(true);
      showToast("success", "Referral link copied!");
      setTimeout(() => setCopied(false), 2000);
    } catch {
      showToast("error", "Failed to copy link");
    }
  };

  const showToast = (type: "success" | "error", text: string) => {
    setToast({ type, text });
    setTimeout(() => setToast(null), 3000);
  };

  // Loading state
  if (loading) {
    return (
      <div className="min-h-dvh bg-[#0a0a0f] flex items-center justify-center">
        <div className="w-8 h-8 rounded-full border-2 border-[#D4AF37]/30 border-t-[#D4AF37] animate-spin" />
      </div>
    );
  }

  // Not authenticated
  if (!user) return null;

  return (
    <div className="min-h-dvh bg-[#0a0a0f] pb-24">
      {/* Header */}
      <div className="px-4 pt-6 pb-2">
        <h1 className="text-xl font-bold text-white">Refer & Earn</h1>
      </div>

      <div className="px-4 space-y-5 animate-fade-in">
        {/* Toast Notification */}
        {toast && toast.type === "success" && (
          <div className="flex items-center gap-2 p-3 rounded-xl text-sm bg-emerald-900/20 border border-emerald-800/40 text-emerald-400">
            <Check size={16} />
            {toast.text}
          </div>
        )}
        {toast && toast.type === "error" && (
          <ErrorFeedback error={toast.text} kind="default" onRetry={() => setToast(null)} context="referral" />
        )}

        {/* Error State */}
        {error && !dataLoading && (
          <ErrorFeedback error={error} kind="network" onRetry={fetchStats} context="referral stats" />
        )}

        {/* Data Loading */}
        {dataLoading && !error && (
          <div className="bg-[#111118] border border-gray-800/60 rounded-2xl p-10 text-center">
            <div className="w-8 h-8 rounded-full border-2 border-[#D4AF37]/30 border-t-[#D4AF37] animate-spin mx-auto mb-3" />
            <p className="text-sm text-gray-500">Loading referral stats...</p>
          </div>
        )}

        {/* Referral Code Card */}
        {stats && !dataLoading && (
          <div className="bg-gradient-to-br from-[#D4AF37]/20 to-[#0a0a0f] border border-[#D4AF37]/30 rounded-2xl p-6 text-center">
            <div className="w-14 h-14 rounded-full bg-[#D4AF37]/20 flex items-center justify-center mx-auto mb-3">
              <Gift size={24} className="text-[#D4AF37]" />
            </div>
            <p className="text-xs text-gray-500 uppercase tracking-wider mb-1">
              Your Referral Code
            </p>
            <p className="text-3xl font-mono font-bold tracking-widest text-[#D4AF37] select-all">
              {stats.referralCode}
            </p>
            <p className="text-xs text-gray-500 mt-2">
              Share this code or link to earn rewards
            </p>
          </div>
        )}

        {/* Action Buttons */}
        {stats && !dataLoading && (
          <div className="grid grid-cols-2 gap-4">
            {/* Share Button */}
            <button
              onClick={handleShare}
              className="bg-[#111118] border border-gray-800/60 rounded-2xl p-5 text-center active:scale-95 transition hover:border-[#D4AF37]/30 min-h-[80px]"
            >
              <Share2 size={20} className="mx-auto text-[#D4AF37] mb-2" />
              <p className="text-sm font-medium text-white">Share</p>
              <p className="text-xs text-gray-500 mt-0.5">Invite friends</p>
            </button>

            {/* Copy Link Button */}
            <button
              onClick={handleCopyLink}
              className="bg-[#111118] border border-gray-800/60 rounded-2xl p-5 text-center active:scale-95 transition hover:border-[#D4AF37]/30 min-h-[80px]"
            >
              {copied ? (
                <Check size={20} className="mx-auto text-emerald-400 mb-2" />
              ) : (
                <Copy size={20} className="mx-auto text-[#D4AF37] mb-2" />
              )}
              <p className="text-sm font-medium text-white">
                {copied ? "Copied!" : "Copy Link"}
              </p>
              <p className="text-xs text-gray-500 mt-0.5">
                {copied ? "Link copied to clipboard" : "Share your link"}
              </p>
            </button>
          </div>
        )}

        {/* Stats Cards */}
        {stats && !dataLoading && (
          <div>
            <h2 className="text-sm font-semibold text-white mb-3 flex items-center gap-2">
              <TrendingUp size={16} className="text-[#D4AF37]" />
              Your Referral Stats
            </h2>
            <div className="grid grid-cols-3 gap-3">
              {/* Total Referrals */}
              <div className="bg-[#111118] border border-gray-800/60 rounded-2xl p-4 text-center">
                <Users size={18} className="mx-auto text-[#D4AF37] mb-2" />
                <p className="text-xl font-bold text-white">
                  {stats.totalReferrals}
                </p>
                <p className="text-xs text-gray-500 mt-1">Referrals</p>
              </div>

              {/* FLH Earned */}
              <div className="bg-[#111118] border border-gray-800/60 rounded-2xl p-4 text-center">
                <Gift size={18} className="mx-auto text-[#D4AF37] mb-2" />
                <p className="text-xl font-bold text-[#D4AF37]">
                  {stats.totalEarned.toLocaleString()}
                </p>
                <p className="text-xs text-gray-500 mt-1">FLH Earned</p>
              </div>

              {/* Upgraded Count */}
              <div className="bg-[#111118] border border-gray-800/60 rounded-2xl p-4 text-center">
                <Crown size={18} className="mx-auto text-[#D4AF37] mb-2" />
                <p className="text-xl font-bold text-white">
                  {stats.upgradedCount}
                </p>
                <p className="text-xs text-gray-500 mt-1">Upgraded</p>
              </div>
            </div>
          </div>
        )}

        {/* How It Works */}
        {stats && !dataLoading && (
          <div className="bg-[#111118] border border-gray-800/60 rounded-2xl p-5">
            <h3 className="text-sm font-semibold text-white mb-3 flex items-center gap-2">
              <Gift size={16} className="text-[#D4AF37]" />
              How It Works
            </h3>
            <ul className="space-y-3">
              <li className="flex items-start gap-3 text-sm text-gray-400">
                <span className="w-5 h-5 rounded-full bg-[#D4AF37]/20 text-[#D4AF37] text-xs font-bold flex items-center justify-center shrink-0 mt-0.5">
                  1
                </span>
                <span>
                  Share your referral code or link with friends and family
                </span>
              </li>
              <li className="flex items-start gap-3 text-sm text-gray-400">
                <span className="w-5 h-5 rounded-full bg-[#D4AF37]/20 text-[#D4AF37] text-xs font-bold flex items-center justify-center shrink-0 mt-0.5">
                  2
                </span>
                <span>
                  They sign up using your link — you earn{" "}
                  <span className="text-[#D4AF37] font-medium">200 FLH</span>{" "}
                  per referral
                </span>
              </li>
              <li className="flex items-start gap-3 text-sm text-gray-400">
                <span className="w-5 h-5 rounded-full bg-[#D4AF37]/20 text-[#D4AF37] text-xs font-bold flex items-center justify-center shrink-0 mt-0.5">
                  3
                </span>
                <span>
                  When they upgrade to Premium, you earn a{" "}
                  <span className="text-[#D4AF37] font-medium">bonus</span> on
                  top!
                </span>
              </li>
            </ul>
          </div>
        )}

        {/* Share Link Card (visible at bottom) */}
        {stats && !dataLoading && (
          <div className="bg-[#111118] border border-gray-800/60 rounded-2xl p-5">
            <h3 className="text-sm font-semibold text-white mb-3 flex items-center gap-2">
              <ExternalLink size={16} className="text-[#D4AF37]" />
              Your Share Link
            </h3>
            <div className="flex items-center gap-3">
              <div className="flex-1 bg-[#1a1a24] border border-gray-800/60 rounded-xl px-4 py-3 min-h-[48px] flex items-center">
                <code className="text-sm text-gray-400 truncate select-all">
                  {getShareLink()}
                </code>
              </div>
              <button
                onClick={handleCopyLink}
                className="w-12 h-12 rounded-xl bg-[#D4AF37]/10 border border-[#D4AF37]/30 flex items-center justify-center active:scale-95 transition hover:bg-[#D4AF37]/20 shrink-0 min-h-[48px] min-w-[48px]"
              >
                {copied ? (
                  <Check size={18} className="text-emerald-400" />
                ) : (
                  <Copy size={18} className="text-[#D4AF37]" />
                )}
              </button>
            </div>
          </div>
        )}

        <div className="h-4" />
      </div>
    </div>
  );
}
