import Link from "next/link"
import { redirect } from "next/navigation"
import { ArrowLeft, UserCircle2 } from "lucide-react"
import { Button } from "@/components/ui/button"
import { BlueTick } from "@/components/ui/blue-tick"
import { createClient } from "@/lib/supabase/server"
import { createAdminClient } from "@/lib/supabase/admin"
import { ProfileForm } from "@/components/profile/profile-form"
import { VerificationCard } from "@/components/profile/verification-card"

export const dynamic = "force-dynamic"

export default async function ProfilePage() {
  const supabase = await createClient()
  const {
    data: { user },
  } = await supabase.auth.getUser()
  if (!user) {
    redirect("/auth/login?redirect=/profile")
  }

  // Load the profile row. If missing (e.g. user signed up before the trigger
  // existed), backfill a placeholder row via the service-role client so the
  // edit form has something to edit.
  const admin = createAdminClient()
  const { data: profile } = await admin
    .from("profiles")
    .select("*")
    .eq("id", user.id)
    .maybeSingle()

  let loaded = profile
  if (!loaded) {
    const meta = (user.user_metadata ?? {}) as Record<string, unknown>
    const ageRaw = typeof meta.age === "string" ? Number.parseInt(meta.age, 10) : null
    const fallback = {
      id: user.id,
      display_name:
        (meta.display_name as string | undefined) ||
        user.email?.split("@")[0] ||
        "User",
      age: ageRaw && Number.isFinite(ageRaw) ? Math.min(120, Math.max(13, ageRaw)) : 18,
      gender: (meta.gender as string | undefined) || "prefer-not-to-say",
      country: (meta.country as string | undefined) || "Unknown",
      state: (meta.state as string | undefined) || "Unknown",
      bio: null as string | null,
      avatar_url: null as string | null,
      verified: false,
    }
    const { data: inserted } = await admin
      .from("profiles")
      .insert(fallback)
      .select("*")
      .maybeSingle()
    loaded = inserted ?? fallback
  }

  // Read the user's most-recent verification request so the card knows
  // which state to render (pending / rejected / none). The `verified`
  // flag on the profile itself takes priority — once approved, the
  // request row's status ceases to matter for UI purposes.
  const verified = !!(loaded as { verified?: boolean }).verified
  const { data: latestReq } = await admin
    .from("verification_requests")
    .select("status, rejection_reason")
    .eq("user_id", user.id)
    .order("created_at", { ascending: false })
    .limit(1)
    .maybeSingle()
  const latestStatus = (latestReq?.status ?? "none") as
    | "none"
    | "pending"
    | "approved"
    | "rejected"
  const rejectionReason = latestReq?.rejection_reason ?? null

  return (
    <div className="min-h-dvh bg-muted/30">
      <header className="border-b border-border bg-background">
        <div className="mx-auto flex max-w-3xl items-center justify-between gap-3 px-4 py-4 md:px-6">
          <div className="flex items-center gap-3">
            <Button asChild variant="ghost" size="icon" className="h-9 w-9">
              <Link href="/" aria-label="Back to app">
                <ArrowLeft className="h-4 w-4" aria-hidden="true" />
              </Link>
            </Button>
            <div className="flex items-center gap-2">
              {(loaded as { avatar_url?: string | null }).avatar_url ? (
                // eslint-disable-next-line @next/next/no-img-element
                <img
                  src={
                    (loaded as { avatar_url?: string | null }).avatar_url ||
                    "/placeholder.svg"
                  }
                  alt="Your profile photo"
                  className="h-9 w-9 rounded-lg object-cover shadow-sm"
                />
              ) : (
                <div className="flex h-9 w-9 items-center justify-center rounded-lg bg-primary text-primary-foreground shadow-sm">
                  <UserCircle2 className="h-4 w-4" aria-hidden="true" />
                </div>
              )}
              <div className="leading-tight">
                <h1 className="inline-flex items-center gap-1.5 text-base font-semibold tracking-tight md:text-lg">
                  My profile
                  {verified && <BlueTick size={16} title="Verified" />}
                </h1>
                <p className="truncate text-xs text-muted-foreground">{user.email}</p>
              </div>
            </div>
          </div>
        </div>
      </header>

      <main className="mx-auto flex max-w-3xl flex-col gap-5 px-4 py-6 md:px-6 md:py-8">
        <div className="overflow-hidden rounded-2xl border border-border bg-background p-6 shadow-sm md:p-8">
          <ProfileForm
            userId={user.id}
            email={user.email ?? ""}
            initial={{
              display_name: loaded.display_name,
              age: loaded.age,
              gender: loaded.gender,
              country: loaded.country,
              state: loaded.state,
              bio: loaded.bio ?? null,
              avatar_url:
                (loaded as { avatar_url?: string | null }).avatar_url ?? null,
            }}
          />
        </div>

        <VerificationCard
          verified={verified}
          latestStatus={latestStatus}
          rejectionReason={rejectionReason}
        />
      </main>
    </div>
  )
}
