import type { Metadata } from "next";
import Link from "next/link";
import { asc, eq } from "drizzle-orm";
import { redirect } from "next/navigation";
import {
  ArrowRight,
  Bot,
  Check,
  FileText,
  Lock,
  MessageCircleQuestion,
  PencilLine,
  ShieldCheck,
  Sparkles,
} from "lucide-react";
import { verifySession, getCurrentUser } from "@/lib/session";
import { appDb, schema } from "@/lib/appdb";
import { PUAN_TURLERI } from "@/lib/db";
import { URUNLER, MAX_REVIZYON } from "@/lib/credits";
import type { RaporSonuc } from "@/lib/ai/rapor";
import type { RaporParams } from "@/lib/rapor-havuzu";
import { Button } from "@/components/ui/button";
import { RaporListesi } from "@/components/rapor-listesi";
import { ViewportPortal } from "@/components/viewport-portal";
import { SiteFooter } from "@/components/site-footer";
import { SectionEyebrow } from "@/components/pixel-decor";
import { raporMaskele, ACIK_SATIR } from "@/lib/rapor-maske";
import { SohbetClient, type Mesaj } from "./sohbet-client";
import { RevizyonKutusu } from "./revizyon-kutusu";
import { ListemBosCta } from "./listem-bos-cta";

export const metadata: Metadata = {
  title: "Listem",
  robots: { index: false, follow: false },
};

const PAKET_FIYATI = (URUNLER.paket.amountKurus / 100).toLocaleString("tr-TR", {
  maximumFractionDigits: 0,
});

export default async function ListemPage({
  searchParams,
}: {
  searchParams: Promise<{ acildi?: string }>;
}) {
  const session = await verifySession("/listem");
  const [user, params, satir, sohbetGecmisi] = await Promise.all([
    getCurrentUser(),
    searchParams,
    appDb.query.reports.findFirst({
      where: eq(schema.reports.userId, session.user.id),
    }),
    appDb
      .select({
        id: schema.chatMessages.id,
        role: schema.chatMessages.role,
        content: schema.chatMessages.content,
      })
      .from(schema.chatMessages)
      .where(eq(schema.chatMessages.userId, session.user.id))
      .orderBy(asc(schema.chatMessages.createdAt))
      .limit(100),
  ]);
  if (!user) redirect("/giris?callback=/listem");

  const { acildi } = params;
  const kilitAcilisi = Boolean(user.hasPaket && acildi === "1");
  const raporVar = Boolean(satir?.result);

  if (!raporVar) {
    return (
      <>
        <main className="mx-auto w-full max-w-4xl px-4 py-12">
          <section className="mx-auto flex max-w-2xl flex-col items-center px-4 py-16 text-center">
            <Sparkles className="size-10 text-primary" aria-hidden />
            <h1 className="mt-4 font-heading text-2xl font-bold">
              Henüz AI listen yok
            </h1>
            <ListemBosCta />
          </section>
        </main>
        <SiteFooter />
      </>
    );
  }

  const rapor = user.hasPaket
    ? (satir!.result as RaporSonuc)
    : raporMaskele(satir!.result as RaporSonuc);
  const raporParams = satir!.params as RaporParams;
  // Danışman özeti sohbetin açılış mesajı olarak gösterilir; sohbet
  // /api/soru üzerinden zaten liste + seçim bağlamıyla çalışıyor.
  const danismanOzeti = rapor.genelDegerlendirme
    ? {
        metin: rapor.genelDegerlendirme,
        uyarilar: user.hasPaket ? rapor.uyarilar : undefined,
        kilitli: !user.hasPaket,
      }
    : undefined;

  return (
    <>
    <main className="mx-auto w-full max-w-4xl px-4 py-12">
      {kilitAcilisi ? (
        <div
          role="status"
          className="mb-6 flex items-center gap-3 rounded-2xl border border-emerald-200 bg-emerald-50 px-4 py-3 text-sm font-medium text-emerald-800"
        >
          <Sparkles className="size-4 shrink-0" aria-hidden />
          Paketin aktif — 24 tercihinin tamamı, gerekçeler, riskler ve PDF
          artık açık.
        </div>
      ) : null}
      <div className="flex flex-wrap items-end justify-between gap-4">
        <div>
          {user.hasPaket ? (
            <SectionEyebrow className="mb-3">Paketin aktif</SectionEyebrow>
          ) : null}
          <h1 className="max-w-2xl font-heading text-xl font-bold tracking-tight sm:text-2xl">
            {user.hasPaket
              ? "AI tercih listen"
              : "Veriyi ücretsiz incele. Kararı AI ile netleştir."}
          </h1>
          {user.hasPaket ? (
            <p className="mt-2 max-w-2xl text-sm leading-6 text-slate-600">
              {raporParams.sira.toLocaleString("tr-TR")}. sıra ·{" "}
              {PUAN_TURLERI[raporParams.tur as keyof typeof PUAN_TURLERI] ??
                raporParams.tur}{" "}
              · 24 tercihinin tamamını gerekçe, risk analizi ve trendleriyle
              aşağıda inceleyebilirsin.
            </p>
          ) : null}
        </div>
        {user.hasPaket ? (
          <div className="flex gap-2">
            <Button
              asChild
              variant="outline"
              size="sm"
              className="cursor-pointer"
            >
              <Link href="#revizyon">
                <PencilLine className="size-4" aria-hidden />
                Revize et
              </Link>
            </Button>
            <Button
              asChild
              variant="outline"
              size="sm"
              className="cursor-pointer"
            >
              <Link href="/rapor/yazdir" target="_blank">
                <FileText className="size-4" aria-hidden />
                PDF
              </Link>
            </Button>
          </div>
        ) : null}
      </div>

      <div className="mt-8 grid items-start gap-8 lg:grid-cols-[minmax(0,1fr)_340px]">
        <div className="flex min-w-0 flex-col gap-6">
          <section
            className={`min-w-0 rounded-2xl border border-slate-200 bg-slate-50/60 p-3 sm:p-5${
              kilitAcilisi ? " kt-unblur" : ""
            }`}
          >
            <RaporListesi
              rapor={rapor}
              adaySira={raporParams.sira}
              kilitliBaslangic={user.hasPaket ? undefined : ACIK_SATIR}
              kilitOverlay={
                <div className="flex flex-col items-start gap-3 sm:flex-row sm:items-center sm:justify-between">
                  <div className="flex gap-3">
                    <span className="flex size-10 shrink-0 items-center justify-center rounded-full bg-orange-100 text-orange-700">
                      <Lock className="size-4" aria-hidden />
                    </span>
                    <div>
                      <p className="font-heading font-bold text-slate-900">
                        İlk {ACIK_SATIR} tercihte AI analizini gördün
                      </p>
                      <p className="mt-1 max-w-xl text-sm text-slate-600">
                        Kalan {24 - ACIK_SATIR} tercihin kişisel risk, gerekçe ve
                        AI yorumu paketle açılır. Program adları ve taban
                        verileri her zaman ücretsiz.
                      </p>
                    </div>
                  </div>
                  <Button
                    asChild
                    className="h-11 w-full shrink-0 cursor-pointer bg-orange-500 text-white transition-[background-color,transform] duration-200 active:scale-[0.97] hover:bg-orange-600 sm:w-auto"
                  >
                    <Link href="/paket">
                      Analizleri aç — {PAKET_FIYATI} TL
                      <ArrowRight data-icon="inline-end" aria-hidden />
                    </Link>
                  </Button>
                </div>
              }
            />
          </section>

          {user.hasPaket ? (
            <RevizyonKutusu
              kalanHak={Math.max(0, MAX_REVIZYON - (satir!.revisionCount ?? 0))}
            />
          ) : null}
        </div>

        <div id="sohbet" className="scroll-mt-24 lg:sticky lg:top-28">
          {user.hasPaket ? (
            <SohbetClient
              baslangicKredi={user.creditBalance}
              initialMesajlar={sohbetGecmisi as Mesaj[]}
              ozet={danismanOzeti}
            />
          ) : (
            <div className="flex flex-col gap-6">
              <section className="overflow-hidden rounded-2xl border border-slate-200 bg-white shadow-sm">
                <div className="border-b border-slate-100 p-6">
                  <h3 className="font-heading text-xl font-bold tracking-tight">
                    Tablo ücretsiz.
                    <br />
                    Karar desteği pakette.
                  </h3>
                  <p className="mt-2 text-sm leading-6 text-slate-600">
                    Sadece veriyi göstermez; hangi tercihin neden mantıklı
                    olduğunu sıralamana göre açıklar.
                  </p>
                </div>

                <div className="p-6">
                  <ul className="flex flex-col gap-3 text-sm">
                    {[
                      "24 tercihin tamamında kişisel risk analizi",
                      "Her program için kısa, gerekçeli AI yorumu",
                      "2 liste revizyonu ve paylaşılabilir PDF",
                      `${URUNLER.paket.credits} AI danışman sorusu`,
                    ].map((ozellik) => (
                      <li key={ozellik} className="flex items-start gap-2.5">
                        <Check
                          className="mt-0.5 size-4 shrink-0 text-emerald-600"
                          aria-hidden
                        />
                        <span>{ozellik}</span>
                      </li>
                    ))}
                  </ul>

                  <div className="mt-6">
                    <p className="text-xs text-slate-500">Tek seferlik</p>
                    <p className="font-heading text-3xl font-bold">
                      {PAKET_FIYATI} TL
                    </p>
                  </div>

                  <Button
                    asChild
                    size="lg"
                    className="mt-5 h-12 w-full cursor-pointer bg-orange-500 text-white transition-[background-color,transform] duration-200 active:scale-[0.97] hover:bg-orange-600"
                  >
                    <Link href="/paket">
                      Kişisel analizi aç
                      <ArrowRight data-icon="inline-end" aria-hidden />
                    </Link>
                  </Button>

                  <div className="mt-4 flex items-center justify-center gap-4 text-[11px] text-slate-500">
                    <span className="inline-flex items-center gap-1">
                      <ShieldCheck className="size-3.5" aria-hidden />
                      iyzico güvenli ödeme
                    </span>
                    <span className="inline-flex items-center gap-1">
                      <Bot className="size-3.5" aria-hidden />
                      Gerçek YÖK verisi
                    </span>
                  </div>
                </div>
              </section>

              <SohbetClient
                baslangicKredi={user.creditBalance}
                initialMesajlar={sohbetGecmisi as Mesaj[]}
                ozet={danismanOzeti}
                className="h-[520px]"
              />
            </div>
          )}
        </div>
      </div>

      <ViewportPortal>
        <a
          href="#sohbet"
          className="fixed bottom-5 right-4 z-40 inline-flex h-11 items-center gap-2 rounded-full bg-primary px-4 text-sm font-semibold text-white shadow-lg transition-transform duration-200 active:scale-[0.97] lg:hidden print:hidden"
        >
          <MessageCircleQuestion className="size-4" aria-hidden />
          Danışmana sor
        </a>
      </ViewportPortal>
    </main>
    <SiteFooter />
    </>
  );
}
