import { useEffect, useRef, useState } from "react";
import { queryOptions, useQuery } from "@tanstack/react-query";
import { BookOpen, ChevronDown, ChevronUp } from "lucide-react";
import type { Devotional } from "@/lib/devotional";
import { getBiblePassage, type BiblePassage } from "@/lib/api/bible.functions";
import { TopicTag } from "./TopicTag";
import { ShareButton } from "./ShareButton";

const biblePassageQuery = (reference: string, translation = "kjv") =>
  queryOptions({
    queryKey: ["bible", reference, translation],
    queryFn: () => getBiblePassage({ data: { reference, translation } }),
    staleTime: 30 * 24 * 60 * 60 * 1000,
    gcTime: 30 * 24 * 60 * 60 * 1000,
  });

export function TopicDevotionalCard({
  devotional,
  eager = false,
}: {
  devotional: Devotional;
  eager?: boolean;
}) {
  const { scripture_reference, context, text, topics, date } = devotional;
  const reference = (context || scripture_reference || "").trim();

  const [expanded, setExpanded] = useState<boolean>(eager);
  const [inView, setInView] = useState<boolean>(eager);
  const ref = useRef<HTMLElement | null>(null);

  useEffect(() => {
    if (eager || inView) return;
    const el = ref.current;
    if (!el || typeof IntersectionObserver === "undefined") return;
    const io = new IntersectionObserver(
      (entries) => {
        for (const e of entries) {
          if (e.isIntersecting) {
            setInView(true);
            io.disconnect();
            break;
          }
        }
      },
      { rootMargin: "400px 0px" }
    );
    io.observe(el);
    return () => io.disconnect();
  }, [eager, inView]);

  const shouldFetch = Boolean(reference) && (eager || expanded || inView);
  const { data: passage, isLoading } = useQuery({
    ...biblePassageQuery(reference),
    enabled: shouldFetch,
  });

  return (
    <article
      ref={ref}
      className="group relative overflow-hidden rounded-2xl border border-border bg-card p-6 shadow-soft transition hover:-translate-y-0.5 hover:shadow-glow"
    >
      {date && (
        <p className="text-xs font-medium uppercase tracking-[0.18em] text-muted-foreground">
          {new Date(date).toLocaleDateString(undefined, {
            year: "numeric",
            month: "long",
            day: "numeric",
          })}
        </p>
      )}
      <h2 className="mt-1 font-serif text-xl font-semibold tracking-tight text-primary sm:text-2xl">
        {scripture_reference}
      </h2>

      <BiblePassageBlock
        reference={reference}
        passage={passage}
        isLoading={shouldFetch && isLoading}
        expanded={expanded}
        onToggle={() => setExpanded((v) => !v)}
      />

      <div className="mt-5">
        <p className="text-xs font-medium uppercase tracking-[0.18em] text-muted-foreground">
          Today's Message
        </p>
        <p className="mt-2 text-[15px] leading-relaxed text-foreground/85">{text}</p>
      </div>

      {topics.length > 0 && (
        <div className="mt-5 flex flex-wrap gap-2">
          {topics.slice(0, 5).map((t) => (
            <TopicTag key={t} topic={t} />
          ))}
        </div>
      )}

      <div className="mt-5 flex flex-wrap gap-2">
        <ShareButton reference={scripture_reference} text={text} />
      </div>
    </article>
  );
}

function BiblePassageBlock({
  reference,
  passage,
  isLoading,
  expanded,
  onToggle,
}: {
  reference: string;
  passage: BiblePassage | undefined;
  isLoading: boolean;
  expanded: boolean;
  onToggle: () => void;
}) {
  if (!reference) return null;

  return (
    <div className="mt-4 rounded-xl border border-border/70 bg-secondary/40 p-4">
      <button
        type="button"
        onClick={onToggle}
        aria-expanded={expanded}
        className="flex w-full items-center justify-between gap-3 text-left"
      >
        <span className="inline-flex items-center gap-1.5 text-xs font-medium uppercase tracking-[0.18em] text-muted-foreground">
          <BookOpen className="h-3.5 w-3.5 text-[var(--gold)]" />
          Scripture · {reference}
        </span>
        {expanded ? (
          <ChevronUp className="h-4 w-4 text-muted-foreground" />
        ) : (
          <ChevronDown className="h-4 w-4 text-muted-foreground" />
        )}
      </button>

      {expanded && (
        <div className="mt-3 border-l-2 border-[var(--gold)]/60 pl-4">
          {isLoading || !passage ? (
            <div className="space-y-2">
              <div className="h-3.5 w-full animate-pulse rounded bg-muted" />
              <div className="h-3.5 w-11/12 animate-pulse rounded bg-muted" />
              <div className="h-3.5 w-9/12 animate-pulse rounded bg-muted" />
            </div>
          ) : passage.error || (!passage.fullText && passage.verses.length === 0) ? (
            <p className="font-serif text-sm italic text-muted-foreground">
              Bible passage temporarily unavailable.
            </p>
          ) : passage.verses.length > 0 ? (
            <p className="font-serif text-base leading-relaxed text-foreground/90">
              {passage.verses.map((v) => (
                <span key={v.verse}>
                  <sup className="mr-1 align-super text-[10px] font-semibold text-[var(--gold)]">
                    {v.verse}
                  </sup>
                  {v.text.replace(/\s+/g, " ").trim()}{" "}
                </span>
              ))}
            </p>
          ) : (
            <p className="font-serif text-base leading-relaxed text-foreground/90">
              {passage.fullText}
            </p>
          )}
        </div>
      )}
    </div>
  );
}
