"use client"

import { useState } from "react"
import Link from "next/link"
import { useRouter, useSearchParams } from "next/navigation"
import { ChevronLeft, ChevronRight, Pencil, Search, Users2 } from "lucide-react"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { BlueTick } from "@/components/ui/blue-tick"
import { cn } from "@/lib/utils"

export type AdminUser = {
  id: string
  email: string
  displayName: string | null
  avatarUrl: string | null
  createdAt: string
  lastSignInAt: string | null
  emailConfirmedAt: string | null
  // Joined from profiles (may be null if the row hasn't been created yet)
  age: number | null
  gender: string | null
  country: string | null
  state: string | null
  verified: boolean
}

export function AdminUsersTable({
  users,
  page,
  perPage,
  totalLabel,
  initialQuery,
}: {
  users: AdminUser[]
  page: number
  perPage: number
  totalLabel: string
  initialQuery: string
}) {
  const router = useRouter()
  const searchParams = useSearchParams()
  const [q, setQ] = useState(initialQuery)

  // This table is reused on /admin/users; all routing is scoped to that
  // page so the URL stays clean when admins paginate/search.
  const BASE = "/admin/users"

  const updateParam = (key: string, value: string | number | null) => {
    const p = new URLSearchParams(searchParams?.toString())
    if (value === null || value === "" || value === 0) {
      p.delete(key)
    } else {
      p.set(key, String(value))
    }
    router.push(`${BASE}${p.toString() ? `?${p.toString()}` : ""}`)
  }

  const onSearch = (e: React.FormEvent<HTMLFormElement>) => {
    e.preventDefault()
    const p = new URLSearchParams()
    if (q.trim()) p.set("q", q.trim())
    router.push(`${BASE}${p.toString() ? `?${p.toString()}` : ""}`)
  }

  return (
    <div className="space-y-4">
      <div className="flex flex-col items-stretch justify-between gap-3 sm:flex-row sm:items-center">
        <div className="flex items-center gap-2">
          <div className="flex h-9 w-9 items-center justify-center rounded-lg bg-primary/10 text-primary">
            <Users2 className="h-4 w-4" aria-hidden="true" />
          </div>
          <div>
            <h2 className="text-sm font-semibold text-foreground">Registered users</h2>
            <p className="text-xs text-muted-foreground">{totalLabel}</p>
          </div>
        </div>
        <form onSubmit={onSearch} className="relative flex-1 sm:max-w-xs">
          <Search
            className="pointer-events-none absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"
            aria-hidden="true"
          />
          <Input
            type="search"
            placeholder="Search name, email, country…"
            value={q}
            onChange={(e) => setQ(e.target.value)}
            className="h-9 pl-9"
          />
        </form>
      </div>

      <div className="overflow-hidden rounded-xl border border-border bg-background shadow-sm">
        {users.length === 0 ? (
          <div className="flex flex-col items-center justify-center gap-2 px-6 py-12 text-center">
            <Users2 className="h-8 w-8 text-muted-foreground" aria-hidden="true" />
            <p className="text-sm font-medium text-foreground">No users found</p>
            <p className="text-xs text-muted-foreground">
              {initialQuery ? "Try a different search." : "Users will appear here after they sign up."}
            </p>
          </div>
        ) : (
          <div className="overflow-x-auto">
            <table className="w-full text-sm">
              <thead className="bg-muted/40 text-xs uppercase tracking-wide text-muted-foreground">
                <tr>
                  <th className="px-4 py-3 text-left font-medium">User</th>
                  <th className="hidden px-4 py-3 text-left font-medium md:table-cell">
                    Age / Gender
                  </th>
                  <th className="hidden px-4 py-3 text-left font-medium lg:table-cell">
                    Location
                  </th>
                  <th className="px-4 py-3 text-left font-medium">Status</th>
                  <th className="hidden px-4 py-3 text-left font-medium md:table-cell">Joined</th>
                  <th className="hidden px-4 py-3 text-left font-medium lg:table-cell">
                    Last sign in
                  </th>
                  <th className="px-4 py-3 text-right font-medium">Actions</th>
                </tr>
              </thead>
              <tbody className="divide-y divide-border">
                {users.map((u) => {
                  const initial = (u.displayName || u.email || "?").trim().charAt(0).toUpperCase()
                  const confirmed = !!u.emailConfirmedAt
                  const location = [u.state, u.country].filter(Boolean).join(", ") || "—"
                  const ageGender = [u.age ? `${u.age}` : null, formatGender(u.gender)]
                    .filter(Boolean)
                    .join(" · ") || "—"
                  return (
                    <tr key={u.id} className="transition-colors hover:bg-muted/30">
                      <td className="px-4 py-3">
                        <div className="flex items-center gap-3">
                          {u.avatarUrl ? (
                            // eslint-disable-next-line @next/next/no-img-element
                            <img
                              src={u.avatarUrl || "/placeholder.svg"}
                              alt=""
                              className="h-9 w-9 shrink-0 rounded-full object-cover"
                            />
                          ) : (
                            <span
                              aria-hidden="true"
                              className="flex h-9 w-9 shrink-0 items-center justify-center rounded-full bg-primary text-xs font-semibold text-primary-foreground"
                            >
                              {initial}
                            </span>
                          )}
                          <div className="min-w-0">
                            <p className="flex items-center gap-1 truncate font-medium text-foreground">
                              <span className="truncate">
                                {u.displayName || u.email}
                              </span>
                              {u.verified && (
                                <BlueTick size={14} title="Verified" />
                              )}
                            </p>
                            <p className="truncate text-xs text-muted-foreground">{u.email}</p>
                          </div>
                        </div>
                      </td>
                      <td className="hidden whitespace-nowrap px-4 py-3 text-xs text-muted-foreground md:table-cell">
                        {ageGender}
                      </td>
                      <td className="hidden whitespace-nowrap px-4 py-3 text-xs text-muted-foreground lg:table-cell">
                        {location}
                      </td>
                      <td className="px-4 py-3">
                        <span
                          className={cn(
                            "inline-flex items-center gap-1.5 rounded-full border px-2 py-0.5 text-xs font-medium",
                            confirmed
                              ? "border-emerald-200 bg-emerald-50 text-emerald-700 dark:border-emerald-900 dark:bg-emerald-950 dark:text-emerald-300"
                              : "border-amber-200 bg-amber-50 text-amber-700 dark:border-amber-900 dark:bg-amber-950 dark:text-amber-300",
                          )}
                        >
                          <span
                            className={cn(
                              "h-1.5 w-1.5 rounded-full",
                              confirmed ? "bg-emerald-500" : "bg-amber-500",
                            )}
                            aria-hidden="true"
                          />
                          {confirmed ? "Confirmed" : "Pending"}
                        </span>
                      </td>
                      <td className="hidden whitespace-nowrap px-4 py-3 text-xs text-muted-foreground md:table-cell">
                        {formatDate(u.createdAt)}
                      </td>
                      <td className="hidden whitespace-nowrap px-4 py-3 text-xs text-muted-foreground lg:table-cell">
                        {u.lastSignInAt ? formatDate(u.lastSignInAt) : "—"}
                      </td>
                      <td className="whitespace-nowrap px-4 py-3 text-right">
                        <Button asChild size="sm" variant="ghost" className="h-8 px-2">
                          <Link href={`/admin/users/${u.id}`}>
                            <Pencil className="mr-1.5 h-3.5 w-3.5" aria-hidden="true" />
                            Edit
                          </Link>
                        </Button>
                      </td>
                    </tr>
                  )
                })}
              </tbody>
            </table>
          </div>
        )}
      </div>

      <div className="flex items-center justify-between gap-3">
        <p className="text-xs text-muted-foreground">
          Page {page} · {users.length} shown
        </p>
        <div className="flex items-center gap-2">
          <Button
            variant="outline"
            size="sm"
            onClick={() => updateParam("page", Math.max(1, page - 1))}
            disabled={page <= 1}
          >
            <ChevronLeft className="h-4 w-4" aria-hidden="true" />
            <span className="sr-only sm:not-sr-only sm:ml-1">Prev</span>
          </Button>
          <Button
            variant="outline"
            size="sm"
            onClick={() => updateParam("page", page + 1)}
            disabled={users.length < perPage}
          >
            <span className="sr-only sm:not-sr-only sm:mr-1">Next</span>
            <ChevronRight className="h-4 w-4" aria-hidden="true" />
          </Button>
        </div>
      </div>
    </div>
  )
}

function formatGender(g: string | null) {
  if (!g) return null
  switch (g) {
    case "male":
      return "Male"
    case "female":
      return "Female"
    case "non-binary":
      return "Non-binary"
    case "prefer-not-to-say":
      return "—"
    default:
      return g
  }
}

function formatDate(iso: string) {
  try {
    const d = new Date(iso)
    return d.toLocaleString(undefined, {
      year: "numeric",
      month: "short",
      day: "numeric",
      hour: "2-digit",
      minute: "2-digit",
    })
  } catch {
    return iso
  }
}
