"use client";

import { useState, useEffect, useRef, Suspense, useCallback } from "react";
import { useAuth } from "@/lib/AuthContext";
import ErrorFeedback from "@/components/ErrorFeedback";
import { PERSONAS, getPersona } from "@/lib/personas";
import Link from "next/link";
import { useRouter } from "next/navigation";
import {
  Send,
  Lock,
  Sparkles,
  Crown,
  Bot,
  ChevronLeft,
  AlertTriangle,
  Loader2,
  CheckCircle2,
  MessageSquare,
} from "lucide-react";
import PremiumBadge from "@/components/PremiumBadge";

/* ── Types ── */
interface ChatMessage {
  id?: string;
  role: "user" | "assistant";
  content: string;
  createdAt?: string;
  metadata?: { personaId?: string } | null;
}

/* ── Main Page ── */
export default function NurPage() {
  return (
    <Suspense
      fallback={
        <div className="min-h-dvh bg-[#0a0a0f] flex items-center justify-center">
          <Loader2 size={24} className="text-[#D4AF37] animate-spin" />
        </div>
      }
    >
      <NurChat />
    </Suspense>
  );
}

/* ── Chat Component ── */
function NurChat() {
  const { user, token, loading } = useAuth();
  const router = useRouter();

  const [messages, setMessages] = useState<ChatMessage[]>([]);
  const [input, setInput] = useState("");
  const [activePersona, setActivePersona] = useState("nurbuddy");
  const [isTyping, setIsTyping] = useState(false);
  const [dailyCount, setDailyCount] = useState(0);
  const [dailyLimit, setDailyLimit] = useState(10);
  const [error, setError] = useState<string | null>(null);
  const [initialLoading, setInitialLoading] = useState(true);

  const messagesEndRef = useRef<HTMLDivElement>(null);
  const inputRef = useRef<HTMLTextAreaElement>(null);

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

  /* Load chat history + daily stats */
  useEffect(() => {
    if (!token || !user) return;

    const loadData = async () => {
      try {
        const [historyRes, dailyRes] = await Promise.all([
          fetch(`/mobile/api/chat/history/${user.id}`, {
            headers: { Authorization: `Bearer ${token}` },
          }),
          fetch("/mobile/api/chat/daily", {
            headers: { Authorization: `Bearer ${token}` },
          }),
        ]);

        if (historyRes.ok) {
          const hist = await historyRes.json();
          setMessages(hist.messages || []);
        }

        if (dailyRes.ok) {
          const daily = await dailyRes.json();
          setDailyCount(daily.count || 0);
          setDailyLimit(daily.limit === -1 ? Infinity : daily.limit);
        }
      } catch {
        // silent
      } finally {
        setInitialLoading(false);
      }
    };

    loadData();
  }, [token, user]);

  /* Auto-scroll on new messages */
  const scrollToBottom = useCallback(() => {
    setTimeout(() => {
      messagesEndRef.current?.scrollIntoView({ behavior: "smooth" });
    }, 100);
  }, []);

  useEffect(() => {
    scrollToBottom();
  }, [messages, isTyping, scrollToBottom]);

  /* Send message */
  const sendMessage = async () => {
    const trimmed = input.trim();
    if (!trimmed || isTyping) return;

    setError(null);

    const userMsg: ChatMessage = { role: "user", content: trimmed };
    setMessages((prev) => [...prev, userMsg]);
    setInput("");

    setIsTyping(true);

    try {
      const res = await fetch("/mobile/api/chat/send", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
          Authorization: `Bearer ${token}`,
        },
        body: JSON.stringify({
          messages: [{ role: "user", content: trimmed }],
          personaId: activePersona,
        }),
      });

      const data = await res.json();

      if (!res.ok) {
        if (res.status === 429) {
          setError("Daily message limit reached. Upgrade to continue chatting!");
        } else if (res.status === 403) {
          setError(data.error || "This persona requires an upgrade.");
        } else {
          setError(data.error || "Failed to send message");
        }
        // Remove the optimistic user message on error
        setMessages((prev) => prev.slice(0, -1));
        return;
      }

      const aiMsg: ChatMessage = {
        id: data.message.id,
        role: "assistant",
        content: data.message.content,
        createdAt: data.message.createdAt,
      };
      setMessages((prev) => [...prev, aiMsg]);

      // Update daily count
      if (data.daily) {
        setDailyCount(data.daily.count);
        setDailyLimit(data.daily.limit === -1 ? Infinity : data.daily.limit);
      }
    } catch {
      setError("Network error. Please try again.");
      setMessages((prev) => prev.slice(0, -1));
    } finally {
      setIsTyping(false);
    }
  };

  /* Keyboard shortcut */
  const handleKeyDown = (e: React.KeyboardEvent) => {
    if (e.key === "Enter" && !e.shiftKey) {
      e.preventDefault();
      sendMessage();
    }
  };

  if (loading || initialLoading) {
    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>
    );
  }

  if (!user || !token) return null;

  const isPremium = user.isPremium || user.isPro;
  const isPro = user.isPro;
  const isUnlimited = dailyLimit === Infinity;
  const atLimit = !isUnlimited && dailyCount >= dailyLimit;
  const limitPercent = isUnlimited ? 0 : Math.min(100, (dailyCount / dailyLimit) * 100);
  const remaining = isUnlimited ? -1 : dailyLimit - dailyCount;

  return (
    <div className="min-h-dvh bg-[#0a0a0f] flex flex-col pb-24">
      {/* ── Header ── */}
      <div className="sticky top-0 z-20 bg-[#0a0a0f]/95 backdrop-blur-md border-b border-gray-800/60">
        <div className="flex items-center justify-between px-4 py-3">
          <div className="flex items-center gap-2">
            <Link href="/" className="text-gray-500 hover:text-white transition">
              <ChevronLeft size={20} />
            </Link>
            <div>
              <h1 className="text-base font-bold text-white flex items-center gap-1.5">
                <Bot size={16} className="text-[#D4AF37]" />
                Nur AI
              </h1>
              <p className="text-xs text-gray-600">
                {isPro ? "Pro Plan" : isPremium ? "Premium Plan" : "Free Plan"}
              </p>
            </div>
          </div>
          {!isPremium && (
            <Link
              href="/upgrade"
              className="flex items-center gap-1.5 bg-[#D4AF37]/15 border border-[#D4AF37]/30 rounded-full px-4 py-2 min-h-[36px] text-xs font-semibold text-[#D4AF37] active:bg-[#D4AF37]/25 transition"
            >
              <Sparkles size={14} />
              Upgrade
            </Link>
          )}
        </div>
      </div>

      {/* ── Persona Selector ── */}
      <Suspense
        fallback={
          <div className="h-20 bg-[#111118] mx-4 mt-3 rounded-xl animate-pulse" />
        }
      >
        <PersonaSelector
          activePersona={activePersona}
          onSelect={setActivePersona}
          isPremium={isPremium}
          isPro={isPro}
        />
      </Suspense>

      {/* ── Daily Cap Bar ── */}
      <div className="px-4 mt-3">
        <div className="flex items-center justify-between mb-1.5">
          <span className="text-xs text-gray-500 font-medium">
            {isUnlimited ? (
              <span className="text-emerald-400 flex items-center gap-1">
                <CheckCircle2 size={12} />
                Unlimited messages
              </span>
            ) : (
              `${dailyCount}/${dailyLimit} messages today`
            )}
          </span>
          {!isUnlimited && remaining <= 3 && remaining > 0 && (
            <span className="text-xs text-amber-400 font-medium">
              {remaining} left
            </span>
          )}
        </div>
        {!isUnlimited && (
          <div className="w-full h-1.5 bg-gray-800 rounded-full overflow-hidden">
            <div
              className={`h-full rounded-full transition-all duration-500 ${
                limitPercent >= 80
                  ? "bg-red-500"
                  : limitPercent >= 50
                  ? "bg-amber-500"
                  : "bg-[#D4AF37]"
              }`}
              style={{ width: `${limitPercent}%` }}
            />
          </div>
        )}
      </div>

      {/* ── Upgrade Banner (hitting limit) ── */}
      {!isPremium && atLimit && (
        <div className="mx-4 mt-3 p-3 bg-gradient-to-r from-[#D4AF37]/10 to-purple-900/10 border border-[#D4AF37]/20 rounded-xl">
          <div className="flex items-start gap-2.5">
            <Crown size={18} className="text-[#D4AF37] shrink-0 mt-0.5" />
            <div className="flex-1">
              <p className="text-sm font-semibold text-white">
                You've hit your daily limit
              </p>
              <p className="text-xs text-gray-500 mt-0.5">
                Upgrade to Premium for 100 messages/day or Pro for unlimited access.
              </p>
              <Link
                href="/upgrade"
                className="inline-block mt-2 text-xs font-semibold text-[#D4AF37] border border-[#D4AF37]/40 rounded-full px-3 py-1 active:bg-[#D4AF37]/10 transition"
              >
                See Plans
              </Link>
            </div>
          </div>
        </div>
      )}

      {/* ── Messages Area ── */}
      <div className="flex-1 overflow-y-auto px-4 py-4 space-y-4">
        {messages.length === 0 && !isTyping && (
          <div className="flex flex-col items-center justify-center h-full text-center py-12">
            <div className="w-16 h-16 rounded-full bg-[#D4AF37]/10 flex items-center justify-center mb-4">
              <MessageSquare size={28} className="text-[#D4AF37]" />
            </div>
            <h3 className="text-sm font-semibold text-gray-300">
              Start a conversation
            </h3>
            <p className="text-xs text-gray-600 mt-1 max-w-xs">
              Choose a persona and send a message to get AI-powered Islamic guidance.
            </p>
          </div>
        )}

        {messages.map((msg, idx) => (
          <MessageBubble key={msg.id || idx} message={msg} isPremium={isPremium} isPro={isPro} />
        ))}

        {isTyping && (
          <div className="flex items-start gap-2.5 animate-fade-in">
            <div className="w-8 h-8 rounded-full bg-gray-800 flex items-center justify-center shrink-0">
              <Bot size={14} className="text-[#D4AF37]" />
            </div>
            <div className="bg-[#1a1a24] border border-gray-700/40 rounded-2xl rounded-tl-sm px-4 py-3 max-w-[85%]">
              <TypingIndicator />
            </div>
          </div>
        )}

        <div ref={messagesEndRef} />
      </div>

      {/* ── Error Message ── */}
      {error && (
        <ErrorFeedback
          error={error}
          kind={
            error.includes("Upgrade") || error.includes("upgrade") || error.includes("premium")
              ? "upgrade"
              : error.includes("Network") || error.includes("network")
              ? "network"
              : "default"
          }
          onRetry={() => setError(null)}
          context="Nur AI chat"
        />
      )}

      {/* ── Input Area ── */}
      <div className="sticky bottom-20 bg-[#0a0a0f]/95 backdrop-blur-md border-t border-gray-800/60 px-4 py-3">
        <div className="flex items-end gap-2 max-w-2xl mx-auto">
          <div className="flex-1 relative">
            <textarea
              ref={inputRef}
              value={input}
              onChange={(e) => setInput(e.target.value)}
              onKeyDown={handleKeyDown}
              placeholder={atLimit ? "Daily limit reached" : "Type a message..."}
              disabled={atLimit || isTyping}
              rows={1}
              className="w-full bg-[#111118] border border-gray-700/50 rounded-xl px-4 py-3 text-sm text-white placeholder-gray-600 resize-none focus:outline-none focus:border-[#D4AF37]/40 transition disabled:opacity-50 disabled:cursor-not-allowed"
              style={{ minHeight: "44px", maxHeight: "120px" }}
              onInput={(e) => {
                const el = e.currentTarget;
                el.style.height = "auto";
                el.style.height = `${Math.min(el.scrollHeight, 120)}px`;
              }}
            />
          </div>
          <button
            onClick={sendMessage}
            disabled={!input.trim() || atLimit || isTyping}
            className="w-11 h-11 rounded-xl bg-[#D4AF37] text-[#0a0a0f] flex items-center justify-center shrink-0 hover:bg-[#e0c040] active:scale-95 transition disabled:opacity-30 disabled:cursor-not-allowed"
          >
            {isTyping ? (
              <Loader2 size={18} className="animate-spin" />
            ) : (
              <Send size={18} />
            )}
          </button>
        </div>
      </div>
    </div>
  );
}

/* ── Persona Selector ── */
function PersonaSelector({
  activePersona,
  onSelect,
  isPremium,
  isPro,
}: {
  activePersona: string;
  onSelect: (id: string) => void;
  isPremium: boolean;
  isPro: boolean;
}) {
  const scrollRef = useRef<HTMLDivElement>(null);

  const canAccess = (personaId: string) => {
    if (personaId === "nurbuddy") return true;
    if (isPro) return true;
    if (isPremium && ["alim", "hakim", "murabbi", "mufti", "daie"].includes(personaId)) return true;
    return false;
  };

  return (
    <div className="px-4 mt-3">
      <div
        ref={scrollRef}
        className="flex gap-2 overflow-x-auto scrollbar-none pb-1"
        style={{ scrollbarWidth: "none", msOverflowStyle: "none" }}
      >
        {PERSONAS.map((persona) => {
          const accessible = canAccess(persona.id);
          const isActive = activePersona === persona.id;

          return (
            <button
              key={persona.id}
              onClick={() => {
                if (accessible) onSelect(persona.id);
                else window.location.href = "/upgrade";
              }}
              disabled={!accessible}
              className={`flex-shrink-0 flex flex-col items-center gap-1.5 px-4 py-3 rounded-xl border transition-all active:scale-95 ${
                isActive
                  ? "bg-[#D4AF37]/15 border-[#D4AF37]/50 text-white"
                  : accessible
                  ? "bg-[#111118] border-gray-800/60 text-gray-400 hover:border-gray-700"
                  : "bg-[#0a0a0f] border-gray-800/30 text-gray-700 opacity-60"
              }`}
              style={{
                minWidth: "80px",
              }}
            >
              <span className="text-xl">{persona.icon}</span>
              <span
                className={`text-xs font-semibold ${
                  isActive ? "text-[#D4AF37]" : ""
                }`}
              >
                {persona.name}
              </span>
              <span className="text-[10px] text-center leading-tight text-gray-600 max-w-[72px]">
                {persona.description}
              </span>
              {!accessible && (
                <div className="flex items-center gap-1 mt-1">
                  <Lock size={8} className="text-amber-400" />
                  <PremiumBadge tier="premium" size="sm" />
                </div>
              )}
              {isActive && (
                <div className="w-1.5 h-1.5 rounded-full bg-[#D4AF37]" />
              )}
            </button>
          );
        })}
      </div>
    </div>
  );
}

/* ── Message Bubble ── */
function MessageBubble({ message, isPremium, isPro }: { message: ChatMessage; isPremium?: boolean; isPro?: boolean }) {
  const isUser = message.role === "user";
  const premiumGlow = !isUser && (isPremium || isPro) && "shadow-[0_0_12px_rgba(212,175,55,0.15)] border-[#D4AF37]/20";

  return (
    <div
      className={`flex items-start gap-2.5 animate-fade-in ${
        isUser ? "flex-row-reverse" : ""
      }`}
    >
      {!isUser && (
        <div className="w-8 h-8 rounded-full bg-gray-800 flex items-center justify-center shrink-0">
          <Bot size={14} className="text-[#D4AF37]" />
        </div>
      )}
      <div
        className={`max-w-[85%] rounded-2xl px-4 py-3 text-sm leading-relaxed whitespace-pre-wrap ${
          isUser
            ? "bg-[#D4AF37] text-[#0a0a0f] rounded-tr-sm"
            : `bg-[#1a1a24] border border-gray-700/40 text-gray-200 rounded-tl-sm ${premiumGlow || ""}`
        }`}
      >
        {message.content}
        {message.createdAt && (
          <div
            className={`text-xs mt-2 ${
              isUser ? "text-[#0a0a0f]/50" : "text-gray-600"
            }`}
          >
            {new Date(message.createdAt).toLocaleTimeString("en-MY", {
              hour: "2-digit",
              minute: "2-digit",
            })}
          </div>
        )}
      </div>
    </div>
  );
}

/* ── Typing Indicator ── */
function TypingIndicator() {
  return (
    <div className="flex items-center gap-1.5 py-1">
      <span className="w-2 h-2 bg-gray-500 rounded-full animate-bounce" style={{ animationDelay: "0ms" }} />
      <span className="w-2 h-2 bg-gray-500 rounded-full animate-bounce" style={{ animationDelay: "150ms" }} />
      <span className="w-2 h-2 bg-gray-500 rounded-full animate-bounce" style={{ animationDelay: "300ms" }} />
    </div>
  );
}
