import type { Metadata } from "next"
import Link from "next/link"
import { redirect } from "next/navigation"
import { eq } from "drizzle-orm"
import type Stripe from "stripe"

import { parallaxSignOut } from "@/app/auth/actions"
import { auth } from "@/auth"
import ManageBillingButton from "@/components/account/ManageBillingButton"
import { db } from "@/lib/db"
import { users } from "@/lib/db/schema"
import { stripe } from "@/lib/stripe"

export const metadata: Metadata = {
  title: "My Account — Parallax",
}

type AccountPageProps = {
  searchParams?: Promise<{
    checkout?: string
    plan?: string
    session_id?: string
  }>
}

function formatDate(date: Date | null) {
  if (!date) return "Not available"

  return date.toLocaleDateString("en-GB", {
    day: "numeric",
    month: "short",
    year: "numeric",
  })
}

function getPlanLabel(priceId: string | null) {
  if (priceId === process.env.STRIPE_MONTHLY_PRICE_ID) {
    return "Monthly · $9/month"
  }

  if (priceId === process.env.STRIPE_YEARLY_PRICE_ID) {
    return "Yearly · $72/year"
  }

  return "Parallax Pro"
}

export default async function AccountPage({ searchParams }: AccountPageProps) {
  const [session, params] = await Promise.all([auth(), searchParams])

  if (!session?.user) {
    redirect("/auth/signin?callbackUrl=/account")
  }

  const checkoutStatus = params?.checkout
  const sessionId = params?.session_id

  if (checkoutStatus === "success" && sessionId) {
    try {
      const stripeSession = await stripe.checkout.sessions.retrieve(sessionId, {
        expand: ["subscription"],
      })

      if (stripeSession.payment_status === "paid" && stripeSession.subscription) {
        const subscription = stripeSession.subscription as Stripe.Subscription
        const periodEnd = new Date(
          subscription.items.data[0].current_period_end * 1000,
        )

        await db
          .update(users)
          .set({
            role: "pro",
            stripeCustomerId: stripeSession.customer as string,
            stripeSubscriptionId: subscription.id,
            stripePriceId: subscription.items.data[0].price.id,
            stripeCurrentPeriodEnd: periodEnd,
          })
          .where(eq(users.id, session.user.id))

        console.log("[Account] Direct verification - user upgraded to Pro")
      }
    } catch (err) {
      console.error("[Account] Direct verification failed:", err)
    }
  }

  const user = await db
    .select()
    .from(users)
    .where(eq(users.id, session.user.id))
    .then((result) => result[0])

  if (!user) {
    redirect("/auth/signin?callbackUrl=/account")
  }

  const displayName = user.name ?? user.email ?? "User"
  const initial = displayName.charAt(0).toUpperCase()

  return (
    <main className="min-h-screen bg-[var(--color-bg)] px-6 pb-20 pt-28">
      <div className="mx-auto max-w-[680px]">
        <header className="flex items-center gap-4">
          {user.image ? (
            // eslint-disable-next-line @next/next/no-img-element
            <img
              src={user.image}
              alt=""
              className="h-[52px] w-[52px] rounded-full object-cover"
            />
          ) : (
            <div className="flex h-[52px] w-[52px] items-center justify-center rounded-full bg-[var(--color-tag-bg)] text-[18px] font-semibold text-[var(--color-text-primary)]">
              {initial}
            </div>
          )}
          <div>
            <h1 className="font-serif text-[1.6rem] font-normal text-[var(--color-text-primary)]">
              {displayName}
            </h1>
            <p className="text-[14px] text-[var(--color-text-secondary)]">
              {user.email}
            </p>
          </div>
        </header>

        {checkoutStatus === "success" ? (
          <div className="mb-8 mt-8 flex items-center gap-3 rounded-lg border border-[#166534] bg-[#14532d] p-4 text-[14px] text-[#4ade80]">
            <span>✓</span>
            <span>Welcome to Parallax Pro! Your subscription is active.</span>
          </div>
        ) : null}

        <section className="mt-8 rounded-xl border border-[var(--color-border)] bg-[var(--color-surface)] p-6">
          {user.role === "pro" ? (
            <>
              <div className="flex items-center justify-between gap-4">
                <div className="text-[11px] font-semibold uppercase tracking-widest text-[#7c3aed]">
                  PARALLAX PRO
                </div>
                <span className="rounded bg-[#14532d] px-2 py-0.5 text-[11px] font-medium text-[#4ade80]">
                  Active
                </span>
              </div>
              <div className="mt-3 space-y-2 text-[14px] text-[var(--color-text-secondary)]">
                <p>{getPlanLabel(user.stripePriceId)}</p>
                <p>
                  Current period ends:{" "}
                  {formatDate(user.stripeCurrentPeriodEnd)}
                </p>
              </div>
              <ManageBillingButton />
            </>
          ) : user.role === "admin" ? (
            <>
              <span className="rounded bg-[#7c3aed] px-2 py-1 text-[11px] font-semibold text-white">
                ADMIN
              </span>
              <p className="mt-2 text-[14px] text-[var(--color-text-secondary)]">
                You have full access as an administrator.
              </p>
            </>
          ) : (
            <>
              <h2 className="text-[13px] text-[var(--color-text-secondary)]">
                Free plan
              </h2>
              <p className="mt-2 text-[14px] text-[var(--color-text-secondary)]">
                Upgrade to Pro to access all reports, Data Boards, and weekly
                analysis.
              </p>
              <Link
                href="/pro"
                className="mt-4 inline-block rounded bg-[var(--color-accent)] px-5 py-2.5 text-[13px] font-medium text-white transition hover:bg-[var(--color-accent-hover)]"
              >
                Upgrade to Pro
              </Link>
            </>
          )}
        </section>

        <section className="mt-8">
          <h2 className="mb-3 text-[12px] uppercase tracking-[0.16em] text-[var(--color-accent)]">
            Quick links
          </h2>
          <div className="rounded-lg border border-[var(--color-border)] bg-[var(--color-surface)] px-4">
            {[
              ["Browse reports", "/directory"],
              ["Data Boards", "/pro/data-boards"],
              ["About Parallax", "/about"],
              ["Contact", "/contact"],
            ].map(([label, href], index, links) => (
              <Link
                key={href}
                href={href}
                className={`block py-1.5 text-[14px] text-[var(--color-accent)] hover:underline ${
                  index === links.length - 1
                    ? ""
                    : "border-b border-[var(--color-border)]"
                }`}
              >
                {label}
              </Link>
            ))}
          </div>
        </section>

        <section className="mt-8">
          <form action={parallaxSignOut}>
            <button
              type="submit"
              suppressHydrationWarning
              className="cursor-pointer bg-transparent text-[13px] text-[var(--color-text-secondary)] hover:underline"
            >
              Sign out of Parallax
            </button>
          </form>
        </section>
      </div>
    </main>
  )
}
