"use client";

import { useEffect, useState } from "react";
import { useRouter } from "next/navigation";
import {
  Gift,
  Copy,
  CheckCircle2,
  Share2,
  Coins,
  Users,
  Infinity,
  Loader2,
  AlertCircle,
} from "lucide-react";
import { profileService, type RawFullProfile } from "@/services/profileService";
import { isLoggedIn } from "@/utils/auth";
import { useTranslation } from "@/i18n";

/* ── Skeleton ───────────────────────────────────────────────────────────────── */

function Skeleton({ className = "", style = {} }: { className?: string; style?: React.CSSProperties }) {
  return (
    <div
      className={`animate-pulse rounded-xl ${className}`}
      style={{ background: "var(--border)", ...style }}
    />
  );
}

function PageSkeleton() {
  return (
    <div className="flex flex-col gap-6">
      <Skeleton style={{ height: 200 }} />
      <Skeleton style={{ height: 80 }} />
      <Skeleton style={{ height: 140 }} />
    </div>
  );
}

/* ── Benefit row ────────────────────────────────────────────────────────────── */

function BenefitRow({
  icon: Icon,
  iconColor,
  iconBg,
  text,
  delay = 0,
}: {
  icon: React.ElementType;
  iconColor: string;
  iconBg: string;
  text: string;
  delay?: number;
}) {
  return (
    <div
      className="flex items-center gap-3"
      style={{ animation: `ref-rise 0.45s ease both`, animationDelay: `${delay}ms` }}
    >
      <div
        className="w-8 h-8 rounded-lg flex-shrink-0 flex items-center justify-center"
        style={{ background: iconBg, border: `1px solid ${iconColor}33` }}
      >
        <Icon size={15} color={iconColor} strokeWidth={1.8} />
      </div>
      <p className="text-[13px]" style={{ color: "var(--text-secondary)" }}>
        {text}
      </p>
    </div>
  );
}

/* ── Main page ──────────────────────────────────────────────────────────────── */

export default function ReferralPage() {
  const { t } = useTranslation();
  const router = useRouter();

  const [profile, setProfile] = useState<RawFullProfile | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState("");
  const [copied, setCopied] = useState(false);
  const [shareFeedback, setShareFeedback] = useState(false);

  useEffect(() => {
    if (!isLoggedIn()) {
      router.replace("/auth/login");
      return;
    }

    profileService
      .getProfile()
      .then((res) => {
        if (res.status === 1 && res.result.length > 0) {
          setProfile(res.result[0]);
        } else {
          setError(t("referral_error_load") || "Failed to load referral code.");
        }
      })
      .catch(() => {
        setError(t("referral_error_load") || "Failed to load referral code.");
      })
      .finally(() => setLoading(false));
  }, [router, t]);

  const referralCode = profile?.reference_code ?? "";

  const shareMessage = `${t("referral_share_msg_pre") || "Hey! Join Doliplay using my code"} ${referralCode} ${t("referral_share_msg_post") || "and we both get rewarded! Download now."}`;

  const handleCopy = () => {
    if (!referralCode) return;
    navigator.clipboard
      .writeText(referralCode)
      .then(() => {
        setCopied(true);
        setTimeout(() => setCopied(false), 2200);
      })
      .catch(() => {
        // fallback for older browsers
        const el = document.createElement("textarea");
        el.value = referralCode;
        document.body.appendChild(el);
        el.select();
        document.execCommand("copy");
        document.body.removeChild(el);
        setCopied(true);
        setTimeout(() => setCopied(false), 2200);
      });
  };

  const handleShare = async () => {
    if (navigator.share) {
      try {
        await navigator.share({ text: shareMessage });
      } catch {
        // user cancelled — no-op
      }
    } else {
      await navigator.clipboard.writeText(shareMessage);
      setShareFeedback(true);
      setTimeout(() => setShareFeedback(false), 2200);
    }
  };

  const benefits = [
    {
      icon: Coins,
      iconColor: "#f59e0b",
      iconBg: "rgba(245,158,11,0.1)",
      text: t("referral_benefit_1") || "Earn coins for every successful referral",
    },
    {
      icon: Users,
      iconColor: "#10b981",
      iconBg: "rgba(16,185,129,0.1)",
      text: t("referral_benefit_2") || "Your friends get bonus coins when they join",
    },
    {
      icon: Infinity,
      iconColor: "var(--accent)",
      iconBg: "rgba(var(--accent-rgb),0.1)",
      text: t("referral_benefit_3") || "No limit on how many friends you can refer",
    },
  ];

  return (
    <>
      <style>{`
        @keyframes ref-rise { from { opacity:0; transform:translateY(14px); } to { opacity:1; transform:none; } }
        @keyframes ref-pulse { 0%,100%{box-shadow:0 0 0 0 rgba(var(--accent-rgb),0.25)} 50%{box-shadow:0 0 0 8px rgba(var(--accent-rgb),0)} }
      `}</style>

      <div
        className="min-h-screen px-4 py-6 pb-28 md:px-6"
        style={{ background: "var(--bg)" }}
      >
        <div className="mx-auto max-w-xl flex flex-col gap-6">

          {/* Page header */}
          <div
            className="flex items-center gap-3"
            style={{ animation: "ref-rise 0.35s ease both" }}
          >
            <div
              className="w-9 h-9 rounded-xl flex items-center justify-center flex-shrink-0"
              style={{
                background: "rgba(245,158,11,0.1)",
                border: "1px solid rgba(245,158,11,0.2)",
              }}
            >
              <Gift size={17} color="#f59e0b" strokeWidth={1.8} />
            </div>
            <div>
              <h1
                className="text-lg font-black tracking-tight"
                style={{ letterSpacing: "-0.02em", color: "var(--text-primary)" }}
              >
                {t("referral_title") || "Refer & Earn"}
              </h1>
              <p className="text-[11px] mt-0.5" style={{ color: "var(--text-muted)" }}>
                {t("referral_subtitle") || "Invite friends and earn rewards together"}
              </p>
            </div>
          </div>

          {loading ? (
            <PageSkeleton />
          ) : error ? (
            <div
              className="rounded-xl px-4 py-4 flex items-center gap-3"
              style={{
                background: "rgba(239,68,68,0.08)",
                border: "1px solid rgba(239,68,68,0.15)",
                color: "#ef4444",
              }}
            >
              <AlertCircle size={16} strokeWidth={2} />
              <p className="text-[12px]">{error}</p>
            </div>
          ) : (
            <>
              {/* Hero card */}
              <div
                className="relative overflow-hidden rounded-2xl p-6"
                style={{
                  background: "linear-gradient(135deg, #1a1208 0%, #0f0f1a 50%, #12100a 100%)",
                  border: "1px solid rgba(245,158,11,0.18)",
                  boxShadow: "0 0 60px rgba(245,158,11,0.06), 0 20px 60px rgba(0,0,0,0.5)",
                  animation: "ref-rise 0.45s ease both 0.05s",
                }}
              >
                {/* Glow */}
                <div
                  className="absolute pointer-events-none"
                  style={{
                    width: 280,
                    height: 280,
                    borderRadius: "50%",
                    background: "radial-gradient(circle, rgba(245,158,11,0.1) 0%, transparent 70%)",
                    top: -80,
                    right: -60,
                  }}
                />

                {/* Headline */}
                <p
                  className="text-[11px] font-bold uppercase tracking-widest mb-1 relative z-10"
                  style={{ color: "#f59e0b" }}
                >
                  {t("referral_your_code") || "Your Referral Code"}
                </p>
                <p
                  className="text-[13px] mb-5 relative z-10"
                  style={{ color: "#888" }}
                >
                  {t("referral_hero_desc") || "Share your code with friends. When they sign up and join, you both earn coins!"}
                </p>

                {/* Code box */}
                <div
                  className="relative z-10 flex items-center justify-between rounded-xl px-5 py-4 mb-4"
                  style={{
                    background: "rgba(245,158,11,0.06)",
                    border: "1.5px dashed rgba(245,158,11,0.3)",
                    animation: "ref-pulse 2.5s ease infinite",
                  }}
                >
                  {loading ? (
                    <Loader2 size={18} className="animate-spin" style={{ color: "#f59e0b" }} />
                  ) : (
                    <span
                      className="text-3xl font-black tracking-[0.15em]"
                      style={{
                        color: "#f59e0b",
                        fontVariantNumeric: "tabular-nums",
                        textShadow: "0 0 24px rgba(245,158,11,0.3)",
                        letterSpacing: "0.15em",
                      }}
                    >
                      {referralCode || "—"}
                    </span>
                  )}
                  <button
                    onClick={handleCopy}
                    disabled={!referralCode}
                    className="flex items-center gap-1.5 px-3 py-2 rounded-lg text-[11px] font-bold transition-all duration-200 active:scale-95 disabled:opacity-50"
                    style={{
                      background: copied
                        ? "rgba(16,185,129,0.15)"
                        : "rgba(245,158,11,0.12)",
                      color: copied ? "#10b981" : "#f59e0b",
                      border: `1px solid ${copied ? "rgba(16,185,129,0.25)" : "rgba(245,158,11,0.2)"}`,
                    }}
                  >
                    {copied ? (
                      <>
                        <CheckCircle2 size={13} strokeWidth={2.2} />
                        {t("referral_copied") || "Copied!"}
                      </>
                    ) : (
                      <>
                        <Copy size={13} strokeWidth={2.2} />
                        {t("referral_copy") || "Copy Code"}
                      </>
                    )}
                  </button>
                </div>

                {/* Share button */}
                <button
                  onClick={handleShare}
                  disabled={!referralCode}
                  className="relative z-10 w-full flex items-center justify-center gap-2 py-3 rounded-xl text-[13px] font-black transition-all duration-200 active:scale-[0.98] disabled:opacity-50"
                  style={{
                    background: shareFeedback
                      ? "linear-gradient(135deg, #10b981, #059669)"
                      : "linear-gradient(135deg, #f59e0b, #d97706)",
                    color: "#000",
                    boxShadow: "0 4px 16px rgba(245,158,11,0.25)",
                  }}
                >
                  {shareFeedback ? (
                    <>
                      <CheckCircle2 size={15} strokeWidth={2.2} />
                      {t("referral_link_copied") || "Link Copied!"}
                    </>
                  ) : (
                    <>
                      <Share2 size={15} strokeWidth={2.2} />
                      {t("referral_share") || "Share with Friends"}
                    </>
                  )}
                </button>
              </div>

              {/* Benefits card */}
              <div
                className="rounded-2xl p-5 flex flex-col gap-4"
                style={{
                  background: "var(--card)",
                  border: "1px solid var(--border)",
                  animation: "ref-rise 0.5s ease both 0.1s",
                }}
              >
                <div className="flex items-center gap-2 mb-1">
                  <Gift size={14} color="#f59e0b" strokeWidth={2} />
                  <h2 className="text-[13px] font-bold" style={{ color: "var(--text-primary)" }}>
                    {t("referral_benefits_title") || "Referral Benefits"}
                  </h2>
                </div>
                <div className="flex flex-col gap-3.5">
                  {benefits.map((b, i) => (
                    <BenefitRow
                      key={i}
                      icon={b.icon}
                      iconColor={b.iconColor}
                      iconBg={b.iconBg}
                      text={b.text}
                      delay={i * 80}
                    />
                  ))}
                </div>
              </div>

              {/* Share preview */}
              <div
                className="rounded-2xl px-5 py-4 flex flex-col gap-2"
                style={{
                  background: "var(--card)",
                  border: "1px solid var(--border)",
                  animation: "ref-rise 0.55s ease both 0.15s",
                }}
              >
                <p
                  className="text-[10px] font-bold uppercase tracking-wider"
                  style={{ color: "var(--text-muted)" }}
                >
                  {t("referral_share_preview") || "Share message preview"}
                </p>
                <p
                  className="text-[12px] leading-relaxed italic"
                  style={{ color: "var(--text-secondary)" }}
                >
                  &ldquo;{shareMessage}&rdquo;
                </p>
              </div>
            </>
          )}
        </div>
      </div>
    </>
  );
}
