import { redirect } from "next/navigation";
import Link from "next/link";
import Image from "next/image";
import { getSession } from "@/lib/auth/session";
import { prisma } from "@/lib/prisma";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { ReadingCommentForm } from "./comment-form";
import { ReadingFollowUpForm } from "./follow-up-form";
import { ReadingResultDebugLogger } from "./reading-result-debug-logger";
import { AnimatedSection } from "@/components/animated-section";
import { SiteFooter } from "@/components/site-footer";
import { getCardImageUrl, shouldBypassImageOptimizer } from "@/lib/cards";
import { canUseFollowUp } from "@/lib/readings/follow-up";

export default async function ReadingResultPage({
  params,
  searchParams,
}: {
  params: Promise<{ id: string }>;
  searchParams: Promise<Record<string, string | string[] | undefined>>;
}) {
  const session = await getSession();
  const { id } = await params;
  const rawSearchParams = await searchParams;
  const paymentDebug = rawSearchParams.paymentDebug === "1";
  if (!session?.user?.id) redirect("/login?callbackUrl=/reading/result/" + id);

  const reading = await prisma.reading.findFirst({
    where: { id, userId: session.user.id },
    include: {
      readingCards: { include: { card: true }, orderBy: { position: "asc" } },
    },
  });

  if (!reading) redirect("/panel");
  if (reading.status === "PENDING_PAYMENT") redirect("/checkout?readingId=" + id);

  const showFollowUp = canUseFollowUp(reading.spreadType);
  const hasFollowUpAnswer = Boolean(
    reading.followUpSections || reading.followUpAdvice || reading.followUpSummary
  );
  const followUpCardIds = reading.followUpCardIds as string[] | null;
  const hasSubmittedFollowUpCards = Array.isArray(followUpCardIds) && followUpCardIds.length === 10;
  const isMainPendingManual = reading.status === "PAID" && !reading.sections;
  const isFollowUpPendingManual =
    Boolean(reading.followUpQuestion) && hasSubmittedFollowUpCards && !hasFollowUpAnswer;

  const approvedComments = await prisma.comment.findMany({
    where: { readingId: id, status: "APPROVED" },
    include: { user: { select: { phone: true } } },
    orderBy: { createdAt: "desc" },
  });

  return (
    <div className="min-h-screen flex flex-col">
    {paymentDebug && (
      <ReadingResultDebugLogger
        data={{
          readingId: id,
          provider: typeof rawSearchParams.provider === "string" ? rawSearchParams.provider : null,
          mode: typeof rawSearchParams.mode === "string" ? rawSearchParams.mode : null,
          authority: typeof rawSearchParams.authority === "string" ? rawSearchParams.authority : null,
          stage: typeof rawSearchParams.stage === "string" ? rawSearchParams.stage : null,
          flow: typeof rawSearchParams.flow === "string" ? rawSearchParams.flow : null,
          useAi: typeof rawSearchParams.useAi === "string" ? rawSearchParams.useAi : null,
          paymentError:
            typeof rawSearchParams.paymentError === "string" ? rawSearchParams.paymentError : null,
          detail: typeof rawSearchParams.detail === "string" ? rawSearchParams.detail : null,
          smsDebug: typeof rawSearchParams.smsDebug === "string" ? rawSearchParams.smsDebug : null,
          readingStatus: reading.status,
          hasSections: Boolean(reading.sections),
          hasSummary: Boolean(reading.summary),
        }}
      />
    )}
    <div className="container mx-auto px-4 py-12 max-w-3xl flex-1">
      <AnimatedSection>
        <h1 className="text-3xl font-bold mb-2">{reading.title ?? "نتیجه فال شما"}</h1>
        <p className="text-muted-foreground mb-8">
          نوع فال: {reading.spreadType} — تاریخ:{" "}
          {new Date(reading.createdAt).toLocaleDateString("fa-IR")}
        </p>
      </AnimatedSection>

      <AnimatedSection delay={0.1}>
      <section className="mb-12">
        <h2 className="text-xl font-semibold mb-4">کارت‌های شما</h2>
        <div className="flex flex-wrap gap-4 justify-center">
          {reading.readingCards.map((rc, i) => {
            const imageUrl = getCardImageUrl(rc.card);
            return (
              <Card key={rc.id} className="w-28 overflow-hidden">
                <div className="relative aspect-[200/340]">
                  <Image
                    src={imageUrl}
                    alt={rc.card.nameFa}
                    fill
                    className="object-cover"
                    unoptimized={shouldBypassImageOptimizer(imageUrl)}
                  />
                </div>
                <p className="p-2 text-xs text-center">
                  {i + 1}. {rc.card.nameFa}
                </p>
              </Card>
            );
          })}
        </div>
      </section>
      </AnimatedSection>

      {isMainPendingManual && (
        <AnimatedSection delay={0.18}>
          <Card className="mb-8 border-amber-300">
            <CardHeader>
              <CardTitle className="text-base text-amber-700">پاسخ فال در حال آماده‌سازی</CardTitle>
            </CardHeader>
            <CardContent>
              <div className="space-y-2 text-sm">
                <p>
                  درخواست شما با موفقیت ثبت شد. پاسخ فال شما حداکثر تا ۴۸ ساعت آینده
                  می‌شود.
                </p>
                <p>
                  پس از آماده شدن، برای شما پیامک اطلاع‌رسانی ارسال می‌شود. لطفا بعد از دریافت
                  پیامک، به پنل کاربری خود مراجعه کنید و نتیجه فال را از بخش فال‌های من مشاهده
                  کنید.
                </p>
                <p>
                  از صبوری و اعتماد شما سپاسگزاریم.
                </p>
              </div>
            </CardContent>
          </Card>
        </AnimatedSection>
      )}

      {reading.sections && (
        <AnimatedSection delay={0.2}>
        <section className="mb-8">
          {reading.spreadType !== "18-card" && (
            <h2 className="text-xl font-semibold mb-2">تحلیل فال</h2>
          )}
          <div className="prose prose-sm max-w-none whitespace-pre-wrap text-foreground">
            {reading.sections}
          </div>
        </section>
        </AnimatedSection>
      )}
      {reading.advice && (
        <AnimatedSection delay={0.25}>
        <section className="mb-8">
          <h2 className="text-xl font-semibold mb-2">💡 یک نکته عملی</h2>
          <p className="whitespace-pre-wrap">{reading.advice}</p>
        </section>
        </AnimatedSection>
      )}
      {reading.summary && (
        <AnimatedSection delay={0.3}>
        <section className="mb-8">
          <h2 className="text-xl font-semibold mb-2">📌 جمع‌بندی کوتاه</h2>
          <p className="whitespace-pre-wrap">{reading.summary}</p>
        </section>
        </AnimatedSection>
      )}

      {showFollowUp && !isMainPendingManual && (
        <AnimatedSection delay={0.32}>
        <section className="mb-8">
          <ReadingFollowUpForm
            readingId={id}
            hasFollowUpAnswer={hasFollowUpAnswer}
            hasSubmittedFollowUpCards={hasSubmittedFollowUpCards}
            followUpQuestion={reading.followUpQuestion}
          />
        </section>
        </AnimatedSection>
      )}

      {isFollowUpPendingManual && (
        <AnimatedSection delay={0.325}>
          <Card className="mb-8 border-amber-300">
            <CardHeader>
              <CardTitle className="text-base text-amber-700">پاسخ سوال پیگیری در حال آماده‌سازی</CardTitle>
            </CardHeader>
            <CardContent>
              <p className="text-sm">
                سوال و ۱۰ کارت شما ثبت شد. تیم ما پاسخ این بخش را به زودی اضافه می‌کند.
              </p>
            </CardContent>
          </Card>
        </AnimatedSection>
      )}

      {hasFollowUpAnswer && (
        <>
          <AnimatedSection delay={0.33}>
          <section className="mb-8">
            <h2 className="text-xl font-semibold mb-2">پاسخ سوال شما</h2>
            {reading.followUpSections && (
              <div className="prose prose-sm max-w-none whitespace-pre-wrap text-foreground mb-4">
                {reading.followUpSections}
              </div>
            )}
            {reading.followUpAdvice && (
              <p className="whitespace-pre-wrap mb-4"><strong>💡 یک نکته عملی:</strong> {reading.followUpAdvice}</p>
            )}
            {reading.followUpSummary && (
              <p className="whitespace-pre-wrap"><strong>📌 جمع‌بندی کوتاه:</strong> {reading.followUpSummary}</p>
            )}
          </section>
          </AnimatedSection>
        </>
      )}

      <AnimatedSection delay={0.35}>
      <section className="mb-8">
        <ReadingCommentForm readingId={id} />
      </section>
      </AnimatedSection>
      {approvedComments.length > 0 && (
        <AnimatedSection delay={0.4}>
        <section>
          <h2 className="text-xl font-semibold mb-4">نظرات</h2>
          <ul className="space-y-4">
            {approvedComments.map((c) => (
              <li key={c.id}>
                <Card>
                  <CardHeader className="py-3">
                    <CardTitle className="text-sm">
                      {c.user.phone}
                      <span className="text-muted-foreground font-normal mr-2">
                        — {new Date(c.createdAt).toLocaleDateString("fa-IR")}
                      </span>
                    </CardTitle>
                  </CardHeader>
                  <CardContent className="pt-0">
                    <p className="text-sm whitespace-pre-wrap">{c.content}</p>
                  </CardContent>
                </Card>
              </li>
            ))}
          </ul>
        </section>
        </AnimatedSection>
      )}

      <AnimatedSection delay={0.45}>
      <div className="mt-12 flex gap-4">
        <Button variant="outline" asChild>
          <Link href="/panel/readings">لیست فال‌های من</Link>
        </Button>
        <Button asChild>
          <Link href="/reading">فال جدید</Link>
        </Button>
      </div>
      </AnimatedSection>
    </div>
    <SiteFooter />
    </div>
  );
}
