"use client";

import { useState, useEffect } from "react";
import { useAuth } from "@/lib/AuthContext";
import Link from "next/link";
import { useRouter } from "next/navigation";
import {
  Bot, ShoppingBag, MessageCircle, Wallet,
  Flame, Sparkles, Star, ChevronRight,
  BookOpen, MapPin, Crown, Zap, TrendingUp,
  Gift, Trophy, CircleDot, Compass,
} from "lucide-react";
import { DAILY_VERSE, generateAIResponse } from "@/lib/ai";
import PremiumBadge from "@/components/PremiumBadge";

export default function HomePage() {
  const { user, token, loading, streak, xp, refreshStreak, refreshXp, refreshUser } = useAuth();
  const router = useRouter();
  const [verse] = useState(DAILY_VERSE[Math.floor(Math.random() * DAILY_VERSE.length)]);
  const [claiming, setClaiming] = useState(false);
  const [claimResult, setClaimResult] = useState<string | null>(null);
  const [dhikrTodayCount, setDhikrTodayCount] = useState(0);

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

  // Refresh streak/XP data every 60 seconds
  useEffect(() => {
    if (!token) return;
    const interval = setInterval(() => {
      refreshStreak();
      refreshXp();
    }, 60000);
    return () => clearInterval(interval);
  }, [token, refreshStreak, refreshXp]);

  // Fetch dhikr stats
  useEffect(() => {
    if (!token) return;
    fetch("/mobile/api/dhikr/stats", {
      headers: { Authorization: `Bearer ${token}` },
    })
      .then((r) => r.ok ? r.json() : null)
      .then((data) => {
        if (data?.dayStats?.totalCount != null) setDhikrTodayCount(data.dayStats.totalCount);
      })
      .catch(() => {});
  }, [token]);

  const handleClaimReward = async () => {
    if (!token || claiming) return;
    setClaiming(true);
    setClaimResult(null);
    try {
      const res = await fetch("/mobile/api/gamification/streak", {
        method: "POST",
        headers: { Authorization: `Bearer ${token}` },
      });
      if (res.ok) {
        const data = await res.json();
        setClaimResult(
          `Claimed! +${data.reward} FLH, +${data.xpGain} XP${
            data.newLevel ? ` — Level Up! You're now level ${data.newLevel}! 🎉` : ""
          }`
        );
        refreshStreak();
        refreshXp();
        refreshUser(); // update FLH balance
      } else if (res.status === 409) {
        setClaimResult("Already claimed today!");
      } else {
        const err = await res.json();
        setClaimResult(err.error || "Failed to claim");
      }
    } catch {
      setClaimResult("Network error — try again");
    } finally {
      setClaiming(false);
      setTimeout(() => setClaimResult(null), 5000);
    }
  };

  if (loading) return <LoadingScreen />;
  if (!user) return null;

  const isPremium = user.isPremium || user.isPro;
  const isPro = user.isPro;
  const currentStreak = streak?.currentStreak ?? 0;
  const canClaim = streak?.canClaim ?? false;
  const todayReward = streak?.todayReward ?? 0;
  const level = xp?.level ?? 1;
  const currentXp = xp?.xp ?? 0;
  const xpToNext = xp?.xpToNext ?? 100;
  const xpPercent = xpToNext > 0 ? Math.min(Math.round((currentXp / xpToNext) * 100), 100) : 0;

  return (
    <div className="min-h-dvh bg-[#0a0a0f] pb-24">
      {/* Header */}
      <div className="px-4 pt-6 pb-4">
        <div className="flex items-center justify-between mb-1">
          <div className="flex-1">
            <h1 className="text-xl font-bold text-white flex items-center gap-2">
              Assalamualaikum, {user.name.split(" ")[0]} ☪️
              {/* Level Badge */}
              <div className="flex items-center gap-1 bg-gradient-to-r from-purple-900/40 to-purple-800/20 border border-purple-700/30 rounded-full px-2.5 py-0.5">
                <Trophy size={12} className="text-purple-400" />
                <span className="text-xs font-bold text-purple-300">Lv.{level}</span>
              </div>
              {user.isPro && <PremiumBadge tier="pro" size="sm" />}
              {user.isPremium && !user.isPro && <PremiumBadge tier="premium" size="sm" />}
            </h1>
            <p className="text-xs text-gray-500 mt-0.5">
              {new Date().toLocaleDateString("en-MY", { weekday: "long", day: "numeric", month: "long", year: "numeric" })}
            </p>
          </div>
          {/* Streak */}
          <div className={`flex items-center gap-1.5 rounded-xl px-3 py-2 ${
            currentStreak > 0
              ? "bg-gradient-to-r from-orange-900/40 to-orange-800/20 border border-orange-700/30"
              : "bg-gray-900/40 border border-gray-800/30"
          }`}>
            <Flame size={16} className={currentStreak > 0 ? "text-orange-400 flame" : "text-gray-600"} />
            <span className={`text-sm font-bold ${currentStreak > 0 ? "text-orange-300" : "text-gray-500"}`}>
              {currentStreak}
            </span>
            <span className="text-xs text-gray-500">day</span>
          </div>
        </div>

        {/* XP Progress Bar */}
        <div className="mt-2">
          <div className="flex items-center justify-between mb-1">
            <span className="text-xs text-gray-500">XP Progress</span>
            <span className="text-xs text-gray-500">{currentXp} / {xpToNext} XP</span>
          </div>
          <div className="h-1.5 bg-gray-800 rounded-full overflow-hidden">
            <div
              className="h-full bg-gradient-to-r from-purple-500 to-amber-400 rounded-full transition-all duration-500"
              style={{ width: `${xpPercent}%` }}
            />
          </div>
        </div>

        {/* Premium banner */}
        {!isPremium && (
          <Link href="/upgrade"
            className="mt-3 flex items-center justify-between glass-gold rounded-2xl px-4 py-3.5 active:opacity-80 transition min-h-[44px]">
            <div className="flex items-center gap-3">
              <div className="w-8 h-8 rounded-full bg-[#D4AF37]/20 flex items-center justify-center">
                <Sparkles size={16} className="text-[#D4AF37]" />
              </div>
              <div>
                <p className="text-sm font-semibold text-[#D4AF37]">Go Premium</p>
                <p className="text-xs text-gray-500">Unlock unlimited AI & more</p>
              </div>
            </div>
            <ChevronRight size={16} className="text-[#D4AF37]" />
          </Link>
        )}

        {/* Pro badge */}
        {isPro && (
          <div className="mt-3 flex items-center gap-2 bg-purple-900/20 border border-purple-500/30 rounded-2xl px-4 py-3 min-h-[44px]">
            <Crown size={16} className="text-purple-400" />
            <span className="text-sm font-medium text-purple-300">Pro Member — Unlimited Everything</span>
          </div>
        )}

        {/* FLH Earning Rate - shown for premium/pro */}
        {(isPremium || isPro) && (
          <div className="mt-2 flex items-center gap-2 bg-gradient-to-r from-[#D4AF37]/10 to-purple-900/10 border border-[#D4AF37]/20 rounded-2xl px-4 py-3 min-h-[44px]">
            <TrendingUp size={14} className="text-[#D4AF37]" />
            <span className="text-xs font-semibold text-[#D4AF37]">2x Earning Active</span>
            <span className="text-xs text-gray-500">— Earn double FLH on marketplace sales</span>
          </div>
        )}
      </div>

      {/* Daily Verse */}
      <div className="mx-4 mb-5 bg-gradient-to-br from-emerald-900/20 to-[#111118] border border-emerald-800/30 rounded-2xl p-5">
        <div className="flex items-center gap-2 mb-3">
          <BookOpen size={14} className="text-emerald-400" />
          <span className="text-xs font-medium text-emerald-400">Daily Verse</span>
        </div>
        <p className="text-lg text-center font-arabic text-emerald-100 mb-3" dir="rtl">
          {verse.arabic}
        </p>
        <p className="text-sm text-gray-400 text-center italic">
          &ldquo;{verse.translation}&rdquo;
        </p>
        <p className="text-xs text-gray-600 text-center mt-2">— {verse.reference}</p>
      </div>

      {/* Streak Reward Card */}
      <div className="mx-4 mb-5">
        <div className={`bg-gradient-to-br ${
          canClaim
            ? "from-orange-900/20 to-amber-900/10 border-orange-700/30"
            : "from-gray-900/30 to-gray-800/10 border-gray-800/30"
        } border rounded-2xl p-5`}>
          <div className="flex items-center justify-between mb-3">
            <div className="flex items-center gap-2">
              <div className={`w-9 h-9 rounded-xl ${canClaim ? "bg-orange-900/40" : "bg-gray-800/40"} flex items-center justify-center`}>
                <Gift size={18} className={canClaim ? "text-orange-400" : "text-gray-600"} />
              </div>
              <div>
                <h3 className="text-sm font-semibold text-white">Daily Reward</h3>
                <p className="text-xs text-gray-500">
                  {canClaim
                    ? `Claim your streak reward — +${todayReward} FLH`
                    : "Reward claimed — come back tomorrow!"}
                </p>
              </div>
            </div>
            <div className="text-right">
              <p className="text-lg font-bold text-orange-400">{todayReward.toLocaleString()}</p>
              <p className="text-[10px] text-gray-600">FLH reward</p>
            </div>
          </div>

          {/* Claim button */}
          {canClaim ? (
            <button
              onClick={handleClaimReward}
              disabled={claiming}
              className="w-full py-3.5 bg-gradient-to-r from-orange-600 to-amber-600 hover:from-orange-500 hover:to-amber-500 disabled:opacity-50 text-white text-sm font-semibold rounded-xl active:scale-[0.98] transition-all min-h-[44px]"
            >
              {claiming ? "Claiming..." : "🔥 Claim Streak Reward"}
            </button>
          ) : (
            <div className="w-full py-3.5 bg-gray-800/50 text-gray-500 text-sm font-medium rounded-xl text-center min-h-[44px] flex items-center justify-center">
              ✅ Claimed
            </div>
          )}

          {/* Claim result toast */}
          {claimResult && (
            <div className="mt-2 text-xs text-center font-medium text-orange-300 animate-pulse">
              {claimResult}
            </div>
          )}

          {/* XP hint */}
          <p className="text-xs text-gray-700 text-center mt-3">
            +{Math.min(10 + currentStreak * 2, 100)} XP also awarded on claim
          </p>
        </div>
      </div>

      {/* Quick Actions */}
      <div className="px-4 mb-5">
        <h2 className="text-xs font-semibold text-gray-500 uppercase tracking-wider mb-3">Quick Actions</h2>
        <div className="grid grid-cols-2 gap-4">
          <QuickAction href="/nur" icon={Bot} label="Nur AI" color="bg-amber-900/30 text-amber-300" />
          <QuickAction href="/souq" icon={ShoppingBag} label="Souq" color="bg-[#D4AF37]/15 text-[#D4AF37]" />
          <QuickAction href="/halal-monitor" icon={MapPin} label="Halal Monitor" color="bg-emerald-900/30 text-emerald-300" />
          <QuickAction href="/wallet" icon={Wallet} label="Wallet" color="bg-blue-900/30 text-blue-300" />
        </div>
      </div>

      {/* Dhikr Today */}
      <div className="mx-4 mb-5">
        <Link href="/dhikr" className="block bg-gradient-to-br from-emerald-900/15 via-[#111118] to-gray-900/80 border border-emerald-800/25 rounded-2xl p-5 active:scale-[0.98] transition-all">
          <div className="flex items-center justify-between mb-3">
            <div className="flex items-center gap-2">
              <div className="w-9 h-9 rounded-xl bg-emerald-900/30 flex items-center justify-center">
                <CircleDot size={18} className="text-emerald-400" />
              </div>
              <div>
                <h3 className="text-sm font-semibold text-white">Dhikr Today</h3>
                <p className="text-xs text-gray-500">Digital Tasbih Counter</p>
              </div>
            </div>
            <div className="text-right">
              <p className="text-lg font-bold text-emerald-400 tabular-nums">{dhikrTodayCount.toLocaleString()}</p>
              <p className="text-[10px] text-gray-600">counts</p>
            </div>
          </div>
          <div className="flex items-center justify-center gap-3 text-xs text-gray-500">
            <span className="text-emerald-400/70">سُبْحَانَ ٱللَّٰهِ</span>
            <span className="text-gray-600">·</span>
            <span className="text-amber-400/70">ٱلْحَمْدُ لِلَّٰهِ</span>
            <span className="text-gray-600">·</span>
            <span className="text-sky-400/70">ٱللَّٰهُ أَكْبَرُ</span>
          </div>
        </Link>
      </div>

      {/* Qibla Finder */}
      <div className="mx-4 mb-5">
        <Link href="/qibla" className="block bg-gradient-to-br from-amber-900/15 via-[#111118] to-gray-900/80 border border-amber-800/25 rounded-2xl p-5 active:scale-[0.98] transition-all">
          <div className="flex items-center justify-between">
            <div className="flex items-center gap-2">
              <div className="w-9 h-9 rounded-xl bg-amber-900/30 flex items-center justify-center">
                <Compass size={18} className="text-amber-400" />
              </div>
              <div>
                <h3 className="text-sm font-semibold text-white">Qibla Finder</h3>
                <p className="text-xs text-gray-500">Find direction to the Kaaba</p>
              </div>
            </div>
            <ChevronRight size={16} className="text-amber-600" />
          </div>
        </Link>
      </div>

      {/* Stats Row */}
      <div className="mx-4 mb-5">
        <div className="flex gap-3">
          <StatCard label="FLH Balance" value={user.flhBalance.toLocaleString()} icon={Zap} color="text-[#D4AF37]" />
          <StatCard label="AI Today" value={`${user.dailyMsgCount}/10`} icon={Bot} color="text-amber-400" />
          <StatCard label="Tier" value={isPro ? "Pro" : isPremium ? "Premium" : "Free"} icon={Crown}
            color={isPro ? "text-purple-400" : isPremium ? "text-[#D4AF37]" : "text-gray-500"} />
        </div>
      </div>

      {/* Activity Feed */}
      <div className="px-4">
        <div className="flex items-center justify-between mb-3">
          <h2 className="text-xs font-semibold text-gray-500 uppercase tracking-wider">Activity</h2>
          <Link href="/forum" className="text-xs text-[#D4AF37] min-h-[44px] inline-flex items-center">View all</Link>
        </div>
        <div className="bg-[#111118] border border-gray-800/60 rounded-2xl p-5 text-center">
          <MessageCircle size={24} className="mx-auto text-gray-700 mb-2" />
          <p className="text-sm text-gray-500">No recent activity</p>
          <p className="text-xs text-gray-700 mt-1">Start a conversation with Nur AI</p>
        </div>
      </div>

      {/* Premium upsell at bottom for free users */}
      {!isPremium && (
        <div className="mx-4 mt-5 bg-gradient-to-r from-[#D4AF37]/10 to-purple-900/10 border border-[#D4AF37]/20 rounded-2xl p-5 relative overflow-hidden">
          <div className="absolute top-0 right-0 w-24 h-24 bg-[#D4AF37]/5 rounded-full -translate-y-1/2 translate-x-1/2 blur-2xl" />
          <div className="flex items-start gap-3 relative">
            <div className="w-10 h-10 rounded-2xl bg-[#D4AF37]/15 flex items-center justify-center shrink-0">
              <Star size={20} className="text-[#D4AF37]" />
            </div>
            <div className="flex-1">
              <h3 className="font-semibold text-white text-sm flex items-center gap-2">
                Unlock Your Full Potential
                <PremiumBadge tier="free" size="sm" />
              </h3>
              <p className="text-xs text-gray-500 mt-1">Premium gives you unlimited AI, halal monitor, <strong className="text-gray-400">2x FLH earning</strong>, and marketplace access.</p>
              <Link href="/upgrade"
                className="inline-block mt-3 text-xs font-semibold text-[#D4AF37] border border-[#D4AF37]/40 rounded-full px-6 py-3 active:bg-[#D4AF37]/10 transition hover:shadow-[0_0_12px_rgba(212,175,55,0.3)] min-h-[44px] leading-tight">
                See Plans
              </Link>
            </div>
          </div>
        </div>
      )}

      {/* Browser Extension Card */}
      <div className="mx-4 mt-5 mb-6">
        <a
          href="https://github.com/maifors/falah-extension"
          target="_blank"
          rel="noopener noreferrer"
          className="block bg-gradient-to-br from-sky-900/15 via-[#111118] to-indigo-900/20 border border-sky-700/25 rounded-2xl p-5 active:scale-[0.98] transition-all"
        >
          <div className="flex items-center justify-between mb-3">
            <div className="flex items-center gap-2">
              <div className="w-9 h-9 rounded-xl bg-sky-900/30 flex items-center justify-center">
                <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" className="text-sky-400"><polyline points="4 7 4 4 20 4 20 7"/><line x1="9" y1="20" x2="15" y2="20"/><line x1="12" y1="4" x2="12" y2="20"/></svg>
              </div>
              <div>
                <h3 className="text-sm font-semibold text-white">Falah Browser Extension</h3>
                <p className="text-xs text-gray-500">v2.4.0 — Chrome Extension</p>
              </div>
            </div>
            <ChevronRight size={16} className="text-sky-600" />
          </div>
          <div className="flex flex-wrap gap-2">
            <span className="text-[10px] px-2 py-1 rounded-full bg-amber-900/30 text-amber-300 border border-amber-700/30">🕌 Prayer Grid</span>
            <span className="text-[10px] px-2 py-1 rounded-full bg-orange-900/30 text-orange-300 border border-orange-700/30">⏱ Live Countdown</span>
            <span className="text-[10px] px-2 py-1 rounded-full bg-emerald-900/30 text-emerald-300 border border-emerald-700/30">🌱 Day Progress</span>
            <span className="text-[10px] px-2 py-1 rounded-full bg-[#D4AF37]/15 text-[#D4AF37] border border-[#D4AF37]/30">🛍️ Souq Mini-Feed</span>
            <span className="text-[10px] px-2 py-1 rounded-full bg-purple-900/30 text-purple-300 border border-purple-700/30">⭐ XP & Level</span>
          </div>
        </a>
      </div>
    </div>
  );
}

function QuickAction({ href, icon: Icon, label, color, external }: { href: string; icon: any; label: string; color: string; external?: boolean }) {
  const content = (
    <div className="flex flex-col items-center gap-1.5 active:scale-95 transition">
      <div className={`w-14 h-14 rounded-2xl flex items-center justify-center ${color} bg-opacity-20`}>
        <Icon size={22} />
      </div>
      <span className="text-xs text-gray-500 font-medium">{label}</span>
    </div>
  );

  if (external) {
    return (
      <a href={href} target="_blank" rel="noopener noreferrer" className="active:scale-95 transition">
        {content}
      </a>
    );
  }

  return <Link href={href} className="active:scale-95 transition">{content}</Link>;
}

function StatCard({ label, value, icon: Icon, color }: { label: string; value: string; icon: any; color: string }) {
  return (
    <div className="flex-1 bg-[#111118] border border-gray-800/60 rounded-2xl p-3 text-center">
      <Icon size={16} className={`mx-auto mb-1 ${color}`} />
      <p className="text-sm font-bold text-white">{value}</p>
      <p className="text-[10px] text-gray-600 mt-0.5">{label}</p>
    </div>
  );
}

function LoadingScreen() {
  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>
  );
}
