"use client";

import { useEffect, useState } from "react";

import { useRouter } from "next/navigation";

import Header from "@/app/components/layout/Header";
import Footer from "@/app/components/layout/Footer";

import TarotCardPicker from "@/app/components/tarot/TarotCardPicker";
import TarotCardVisual from "@/app/components/tarot/TarotCardVisual";

import { DrawnCard, drawRandomCards, TAROT_DECK } from "@/app/lib/tarotCards";
import { getOneCardReading, getTarotCardDetail } from "@/app/lib/tarot";
import { useLanguage } from "@/app/context/LanguageContext";
import { toContentLang } from "@/app/i18n/locales";
import {
  extractCardBackCandidates,
  extractCardImage,
  looksLikeContent,
  unwrapUntil,
} from "@/app/lib/tarotParse";

import "../tarot.css";

type Step = "form" | "picking" | "revealed";

export default function OneCardReadingPage() {
  const router = useRouter();

  const { locale } = useLanguage();

  const contentLocale = toContentLang(locale);

  const [pageLoading, setPageLoading] = useState(true);

  const [step, setStep] = useState<Step>("form");

  const [name, setName] = useState("");

  const [drawn, setDrawn] = useState<DrawnCard | null>(null);

  const [revealImageUrl, setRevealImageUrl] = useState<string | undefined>(undefined);

  const [backImageCandidates, setBackImageCandidates] = useState<string[]>([]);

  const [loadingPrediction, setLoadingPrediction] = useState(false);

  const [error, setError] = useState("");

  useEffect(() => {
    const token = localStorage.getItem("token");

    if (!token) {
      router.replace("/signin?redirect=/tarot/one-card-reading");
      return;
    }

    setPageLoading(false);

    // Best-effort: every card shares the same back design, so one
    // lookup is enough to skin the whole face-down fan with real
    // artwork instead of the CSS placeholder.
    getTarotCardDetail(TAROT_DECK[0].slug)
      .then((result) => {
        if (!result.authenticated || !result.success) return;

        const report = unwrapUntil(result.data, looksLikeContent);
        const candidates = extractCardBackCandidates(report);

        if (candidates.length) setBackImageCandidates(candidates);
      })
      .catch(() => {});
  }, [router]);

  const handleStartPicking = () => {
    setError("");

    if (!name.trim()) {
      setError("Please enter your name first.");
      return;
    }

    const token = localStorage.getItem("token");

    if (!token) {
      router.replace("/signin?redirect=/tarot/one-card-reading");
      return;
    }

    setStep("picking");
  };

  const handlePickCard = () => {
    const [picked] = drawRandomCards(1);

    setDrawn(picked);
    setRevealImageUrl(undefined);
    setStep("revealed");

    // Best-effort: upgrade the reveal from the CSS placeholder to real
    // artwork once the card detail loads. The reveal already looks fine
    // without it, so a failure here is silently ignored.
    getTarotCardDetail(picked.card.slug)
      .then((result) => {
        if (!result.authenticated || !result.success) return;

        const report = unwrapUntil(result.data, looksLikeContent);
        const url = extractCardImage(report, picked.direction);

        if (url) setRevealImageUrl(url);
      })
      .catch(() => {});
  };

  const handleSeePredictions = async () => {
    if (!drawn) return;

    setError("");

    const token = localStorage.getItem("token");

    if (!token) {
      router.replace("/signin?redirect=/tarot/one-card-reading");
      return;
    }

    setLoadingPrediction(true);

    try {
      const response = await getOneCardReading({
        name: name.trim(),
        card: drawn.card.slug,
        direction: drawn.direction,
        lang: contentLocale,
      });

      if (!response.authenticated) {
        router.replace("/signin?redirect=/tarot/one-card-reading");
        return;
      }

      if (!response.success) {
        setError(response.message || "Unable to draw a card right now.");
        return;
      }

      sessionStorage.setItem(
        "tarot_one_card_result",
        JSON.stringify({
          name: name.trim(),
          slug: drawn.card.slug,
          direction: drawn.direction,
          data: response.data,
        }),
      );

      router.push("/tarot/one-card-reading/result");
    } catch (err) {
      console.error("One card reading error:", err);
      setError("Something went wrong. Please try again.");
    } finally {
      setLoadingPrediction(false);
    }
  };

  const handleChooseAgain = () => {
    setDrawn(null);
    setRevealImageUrl(undefined);
    setError("");
    setStep("picking");
  };

  if (pageLoading) {
    return (
      <>
        <Header />
        <main className="horoscope-loading">Loading One Card Reading...</main>
        <Footer />
      </>
    );
  }

  return (
    <>
      <Header />

      <main className="tarot-page">
        <div className="tarot-container">
          <div className="tarot-hero">
            <h1>One Card Reading</h1>

            <p>
              Do you wish to know how a situation will unfold, or whether a problem in your life
              is close to resolving? Pull a single card for a quick, focused answer.
            </p>
          </div>

          {step === "form" && (
            <div className="tarot-form-card">
              <div className="tarot-field">
                <label>Your Name</label>

                <input
                  type="text"
                  value={name}
                  onChange={(event) => setName(event.target.value)}
                  placeholder="Enter your name"
                />
              </div>

              <p className="tarot-hint">
                Take a moment to think about your question before you draw — the deeper you think
                about it, the more useful the reading will feel.
              </p>

              {error && <div className="tarot-error">{error}</div>}

              <button type="button" className="tarot-submit-btn" onClick={handleStartPicking}>
                🎴 Draw a Card
              </button>
            </div>
          )}

          {step === "picking" && (
            <div className="tarot-form-card tarot-picking-card">
              <h2 className="tarot-picking-title">Pick Your Card</h2>

              <p className="tarot-hint">
                Focus on your question, then tap any card from the spread below.
              </p>

              <TarotCardPicker onPick={handlePickCard} backImageCandidates={backImageCandidates} />
            </div>
          )}

          {step === "revealed" && drawn && (
            <div className="tarot-form-card tarot-reveal-card">
              <TarotCardVisual
                card={drawn.card}
                direction={drawn.direction}
                size="lg"
                imageUrl={revealImageUrl}
                eager
              />

              <h2 className="tarot-reveal-title">
                {drawn.card.name} ({drawn.direction === "upright" ? "Upright" : "Reversed"})
              </h2>

              {error && <div className="tarot-error">{error}</div>}

              <button
                type="button"
                className="tarot-submit-btn"
                onClick={handleSeePredictions}
                disabled={loadingPrediction}
              >
                {loadingPrediction ? "Loading..." : "I want to see predictions"}
              </button>

              <button type="button" className="tarot-secondary-btn" onClick={handleChooseAgain}>
                Choose Card Again
              </button>
            </div>
          )}

          <section className="tarot-section-card">
            <h2>Frequently Asked Questions</h2>

            <div className="tarot-faq-item">
              <strong>Is a self-drawn tarot reading valid?</strong>

              <p>
                Yes — plenty of people read tarot for themselves. Approach the card with an open
                mind and let it prompt reflection rather than treating it as a strict rulebook.
              </p>
            </div>

            <div className="tarot-faq-item">
              <strong>How often should I pull a card?</strong>

              <p>
                One to three card pulls a day is a good rule of thumb — pulling repeatedly for the
                same question tends to confuse the answer rather than clarify it.
              </p>
            </div>

            <div className="tarot-faq-item">
              <strong>How accurate is a one card reading?</strong>

              <p>
                A single card gives a focused snapshot rather than a full prediction — it works
                best as a prompt for your own judgment about the situation at hand.
              </p>
            </div>
          </section>
        </div>
      </main>

      <Footer />
    </>
  );
}
