import Link from "next/link";
import { Prisma } from "@prisma/client";
import { prisma } from "@/lib/prisma";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Button } from "@/components/ui/button";

type QueueFilter = "all" | "main" | "follow-up";

function normalizeFilter(v?: string): QueueFilter {
  if (v === "main" || v === "follow-up") return v;
  return "all";
}

export default async function AdminReadingsQueuePage({
  searchParams,
}: {
  searchParams: Promise<{ type?: string }>;
}) {
  const { type } = await searchParams;
  const filter = normalizeFilter(type);

  const mainWhere = { status: "PAID" as const, sections: null };
  const followUpWhere = {
    followUpQuestion: { not: null as string | null },
    followUpCardIds: { not: Prisma.JsonNull },
    followUpSections: null,
  };

  const where =
    filter === "main"
      ? mainWhere
      : filter === "follow-up"
        ? followUpWhere
        : { OR: [mainWhere, followUpWhere] };

  const [items, mainCount, followUpCount] = await Promise.all([
    prisma.reading.findMany({
      where,
      orderBy: { createdAt: "desc" },
      take: 200,
      include: {
        user: { select: { phone: true } },
        payment: { select: { amount: true, status: true } },
      },
    }),
    prisma.reading.count({ where: mainWhere }),
    prisma.reading.count({ where: followUpWhere }),
  ]);

  return (
    <div className="space-y-6">
      <div className="flex flex-wrap items-center justify-between gap-3">
        <h1 className="text-2xl font-bold">صف پاسخ فال</h1>
        <div className="flex gap-2">
          <Button asChild variant={filter === "all" ? "default" : "outline"} size="sm">
            <Link href="/admin/readings/queue?type=all">همه</Link>
          </Button>
          <Button asChild variant={filter === "main" ? "default" : "outline"} size="sm">
            <Link href="/admin/readings/queue?type=main">فقط فال اصلی</Link>
          </Button>
          <Button asChild variant={filter === "follow-up" ? "default" : "outline"} size="sm">
            <Link href="/admin/readings/queue?type=follow-up">فقط پیگیری</Link>
          </Button>
        </div>
      </div>

      <div className="grid gap-4 md:grid-cols-3">
        <Card>
          <CardHeader>
            <CardTitle className="text-base">در انتظار اصلی</CardTitle>
          </CardHeader>
          <CardContent>
            <p className="text-2xl font-bold">{mainCount}</p>
          </CardContent>
        </Card>
        <Card>
          <CardHeader>
            <CardTitle className="text-base">در انتظار پیگیری</CardTitle>
          </CardHeader>
          <CardContent>
            <p className="text-2xl font-bold">{followUpCount}</p>
          </CardContent>
        </Card>
        <Card>
          <CardHeader>
            <CardTitle className="text-base">جمع</CardTitle>
          </CardHeader>
          <CardContent>
            <p className="text-2xl font-bold">{mainCount + followUpCount}</p>
          </CardContent>
        </Card>
      </div>

      <Card>
        <CardContent className="p-0">
          <table className="w-full text-sm">
            <thead>
              <tr className="border-b">
                <th className="text-right p-4">کاربر</th>
                <th className="text-right p-4">نوع فال</th>
                <th className="text-right p-4">وضعیت صف</th>
                <th className="text-right p-4">پرداخت</th>
                <th className="text-right p-4">تاریخ</th>
                <th className="text-right p-4">اقدام</th>
              </tr>
            </thead>
            <tbody>
              {items.map((r) => {
                const mainPending = r.status === "PAID" && !r.sections;
                const followPending = Boolean(r.followUpQuestion && r.followUpCardIds && !r.followUpSections);
                const queueLabel =
                  mainPending && followPending
                    ? "اصلی + پیگیری"
                    : mainPending
                      ? "فال اصلی"
                      : "پیگیری";
                return (
                  <tr key={r.id} className="border-b last:border-0">
                    <td className="p-4">{r.user.phone}</td>
                    <td className="p-4">{r.spreadType}</td>
                    <td className="p-4">
                      <span className="text-amber-700">{queueLabel}</span>
                    </td>
                    <td className="p-4">
                      {r.payment
                        ? `${r.payment.status} - ${Number(r.payment.amount).toLocaleString("fa-IR")}`
                        : "-"}
                    </td>
                    <td className="p-4">{new Date(r.createdAt).toLocaleDateString("fa-IR")}</td>
                    <td className="p-4">
                      <Link className="underline" href={`/admin/readings/${r.id}`}>
                        باز کردن و پاسخ
                      </Link>
                    </td>
                  </tr>
                );
              })}
              {items.length === 0 && (
                <tr>
                  <td colSpan={6} className="p-8 text-center text-muted-foreground">
                    موردی در صف پاسخ دستی پیدا نشد.
                  </td>
                </tr>
              )}
            </tbody>
          </table>
        </CardContent>
      </Card>
    </div>
  );
}
