import { notFound } 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 { getCardImageUrl, shouldBypassImageOptimizer } from "@/lib/cards";

export default async function PanelReadingDetailPage({
  params,
}: {
  params: Promise<{ id: string }>;
}) {
  const session = await getSession();
  if (!session?.user?.id) return null;
  const { id } = await params;

  const reading = await prisma.reading.findFirst({
    where: { id, userId: session.user.id },
    include: {
      readingCards: { include: { card: true }, orderBy: { position: "asc" } },
    },
  });

  if (!reading) notFound();
  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 && !reading.followUpSections;

  return (
    <div className="max-w-2xl">
      <h1 className="text-2xl font-bold mb-2">
        فال {reading.spreadType} — {reading.status}
      </h1>
      <p className="text-muted-foreground mb-6">
        {new Date(reading.createdAt).toLocaleDateString("fa-IR")}
      </p>

      <section className="mb-8">
        <h2 className="text-lg font-semibold mb-4">کارت‌ها</h2>
        <div className="flex flex-wrap gap-4">
          {reading.readingCards.map((rc, i) => {
            const imageUrl = getCardImageUrl(rc.card);
            return (
              <Card key={rc.id} className="w-24 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-1 text-xs text-center truncate">
                  {i + 1}. {rc.card.nameFa}
                </p>
              </Card>
            );
          })}
        </div>
      </section>

      {reading.status !== "PENDING_PAYMENT" && (
        <>
          {isMainPendingManual && (
            <Card className="mb-4 border-amber-300">
              <CardHeader>
                <CardTitle className="text-base text-amber-700">پاسخ فال در حال آماده‌سازی</CardTitle>
              </CardHeader>
              <CardContent>
                <p className="text-sm">
                  تیم ما پاسخ فال شما را به زودی ارسال می‌کند.
                </p>
              </CardContent>
            </Card>
          )}
          {reading.title && (
            <section className="mb-4">
              <h2 className="text-lg font-semibold mb-2">عنوان</h2>
              <p>{reading.title}</p>
            </section>
          )}
          {reading.sections && (
            <section className="mb-4">
              <h2 className="text-lg font-semibold mb-2">تفسیر</h2>
              <div className="whitespace-pre-wrap text-sm">{reading.sections}</div>
            </section>
          )}
          {reading.advice && (
            <section className="mb-4">
              <h2 className="text-lg font-semibold mb-2">پند</h2>
              <p className="whitespace-pre-wrap text-sm">{reading.advice}</p>
            </section>
          )}
          {reading.summary && (
            <section className="mb-6">
              <h2 className="text-lg font-semibold mb-2">خلاصه</h2>
              <p className="whitespace-pre-wrap text-sm">{reading.summary}</p>
            </section>
          )}
          {isFollowUpPendingManual && (
            <Card className="mb-6 border-amber-300">
              <CardHeader>
                <CardTitle className="text-base text-amber-700">
                  پاسخ سوال پیگیری در حال آماده‌سازی
                </CardTitle>
              </CardHeader>
              <CardContent>
                <p className="text-sm">سوال و ۱۰ کارت شما ثبت شده و منتظر پاسخ تیم است.</p>
              </CardContent>
            </Card>
          )}
          {reading.followUpSections && (
            <section className="mb-4">
              <h2 className="text-lg font-semibold mb-2">پاسخ سوال پیگیری</h2>
              <p className="whitespace-pre-wrap text-sm">{reading.followUpSections}</p>
            </section>
          )}
          {reading.followUpAdvice && (
            <section className="mb-4">
              <h2 className="text-lg font-semibold mb-2">پند پیگیری</h2>
              <p className="whitespace-pre-wrap text-sm">{reading.followUpAdvice}</p>
            </section>
          )}
          {reading.followUpSummary && (
            <section className="mb-6">
              <h2 className="text-lg font-semibold mb-2">خلاصه پیگیری</h2>
              <p className="whitespace-pre-wrap text-sm">{reading.followUpSummary}</p>
            </section>
          )}
        </>
      )}

      {reading.status === "PENDING_PAYMENT" && (
        <Card className="mb-8">
          <CardHeader>
            <CardTitle className="text-base">پرداخت انجام نشده</CardTitle>
          </CardHeader>
          <CardContent>
            <Button asChild>
              <Link href={`/checkout?readingId=${reading.id}`}>ادامه به پرداخت</Link>
            </Button>
          </CardContent>
        </Card>
      )}

      <div className="flex gap-4">
        <Button variant="outline" asChild>
          <Link href="/panel/readings">لیست فال‌ها</Link>
        </Button>
        <Button asChild>
          <Link href={`/reading/result/${reading.id}`}>مشاهده صفحه نتیجه</Link>
        </Button>
      </div>
    </div>
  );
}
