"use client"

import { useState } from "react"
import Link from "next/link"
import { useRouter } from "next/navigation"
import {
  Search,
  ArrowRight,
  ArrowLeft,
  Building2,
  Users as UsersIcon,
  ShieldAlert,
  Ban,
} from "lucide-react"
import type { AdminUserRow } from "@/lib/db/admin-queries"
import { Select } from "@/components/ui/select"
import { EmptyState } from "@/components/shared/empty-state"
import { formatDate, initials, cn } from "@/lib/utils"

interface UsersTableProps {
  data: {
    rows: AdminUserRow[]
    total: number
    page: number
    pageSize: number
    pageCount: number
  }
  query: { q?: string; plan?: string; sort?: string; dir?: string }
}

const PLAN_BADGE: Record<string, string> = {
  starter: "border-white/15 bg-white/[0.04] text-white/40",
  pro: "border-indigo-500/30 bg-indigo-500/10 text-indigo-300",
  landlord: "border-violet-500/30 bg-violet-500/10 text-violet-300",
  lifetime: "border-amber-500/30 bg-amber-500/10 text-amber-300",
}

function PlanBadge({ plan }: { plan: string | null }) {
  const key = plan ?? "starter"
  return (
    <span
      className={cn(
        "inline-flex items-center rounded-full border px-2 py-0.5 text-xs font-medium capitalize",
        PLAN_BADGE[key] ?? PLAN_BADGE.starter
      )}
    >
      {key}
    </span>
  )
}

const PLAN_OPTIONS = [
  { value: "", label: "All plans" },
  { value: "starter", label: "Starter" },
  { value: "pro", label: "Pro" },
  { value: "landlord", label: "Landlord" },
  { value: "lifetime", label: "Lifetime" },
]

export function UsersTable({ data, query }: UsersTableProps) {
  const router = useRouter()
  const [search, setSearch] = useState(query.q ?? "")
  const { rows, total, page, pageCount } = data

  // Build a /admin/users URL preserving existing params, applying overrides,
  // and resetting to page 1 whenever a filter/search changes.
  function buildUrl(overrides: Record<string, string | undefined>) {
    const params = new URLSearchParams()
    const merged: Record<string, string | undefined> = {
      q: query.q,
      plan: query.plan,
      sort: query.sort,
      dir: query.dir,
      ...overrides,
    }
    for (const [k, v] of Object.entries(merged)) {
      if (v != null && v !== "") params.set(k, v)
    }
    const qs = params.toString()
    return qs ? `/admin/users?${qs}` : "/admin/users"
  }

  function submitSearch() {
    router.push(buildUrl({ q: search.trim() || undefined, page: undefined }))
  }

  function onPlanChange(plan: string) {
    router.push(buildUrl({ plan: plan || undefined, page: undefined }))
  }

  return (
    <div className="space-y-4">
      {/* Filters */}
      <div className="flex flex-col gap-3 sm:flex-row sm:items-center">
        <div className="relative flex-1">
          <Search className="absolute left-3.5 top-1/2 h-4 w-4 -translate-y-1/2 text-white/25" />
          <input
            value={search}
            onChange={(e) => setSearch(e.target.value)}
            onKeyDown={(e) => {
              if (e.key === "Enter") submitSearch()
            }}
            placeholder="Search by name or email…"
            className="w-full rounded-xl border border-white/[0.08] bg-white/[0.03] py-2.5 pl-10 pr-4 text-sm text-white placeholder-white/25 outline-none transition focus:border-rose-500/50 focus:bg-white/[0.05] focus:ring-1 focus:ring-rose-500/30"
          />
        </div>
        <div className="flex items-center gap-3">
          <div className="w-40">
            <Select
              value={query.plan ?? ""}
              onChange={onPlanChange}
              options={PLAN_OPTIONS}
              placeholder="All plans"
            />
          </div>
          <button
            onClick={submitSearch}
            className="rounded-xl bg-rose-600 px-4 py-2.5 text-sm font-semibold text-white transition hover:bg-rose-500 hover:shadow-lg hover:shadow-rose-500/20"
          >
            Search
          </button>
        </div>
      </div>

      {rows.length === 0 ? (
        <EmptyState
          icon={UsersIcon}
          title="No users found"
          description="No accounts match the current search or filter. Try adjusting your query."
        />
      ) : (
        <>
          {/* Desktop table */}
          <div className="hidden overflow-hidden rounded-2xl border border-white/[0.06] bg-[#16161f] lg:block">
            <table className="w-full">
              <thead>
                <tr className="border-b border-white/[0.06]">
                  <th className="px-5 py-3.5 text-left text-xs font-medium tracking-wide text-white/30">Email</th>
                  <th className="px-5 py-3.5 text-left text-xs font-medium tracking-wide text-white/30">Name</th>
                  <th className="px-5 py-3.5 text-left text-xs font-medium tracking-wide text-white/30">Plan</th>
                  <th className="px-5 py-3.5 text-left text-xs font-medium tracking-wide text-white/30">Status</th>
                  <th className="px-5 py-3.5 text-right text-xs font-medium tracking-wide text-white/30">Properties</th>
                  <th className="px-5 py-3.5 text-right text-xs font-medium tracking-wide text-white/30">Tenants</th>
                  <th className="px-5 py-3.5 text-left text-xs font-medium tracking-wide text-white/30">Joined</th>
                  <th className="px-5 py-3.5" />
                </tr>
              </thead>
              <tbody className="divide-y divide-white/[0.04]">
                {rows.map((row) => (
                  <tr key={row.id} className="group transition-colors hover:bg-white/[0.02]">
                    <td className="px-5 py-4">
                      <Link href={`/admin/users/${row.id}`} className="flex items-center gap-3">
                        <div className="flex h-9 w-9 shrink-0 items-center justify-center rounded-full bg-gradient-to-br from-rose-500/20 to-red-500/20 text-xs font-bold text-rose-300 ring-1 ring-inset ring-rose-500/20">
                          {initials(row.full_name || row.email)}
                        </div>
                        <span className="text-sm font-medium text-white">{row.email}</span>
                      </Link>
                    </td>
                    <td className="px-5 py-4">
                      <span className="text-sm text-white/70">{row.full_name || "—"}</span>
                    </td>
                    <td className="px-5 py-4">
                      <PlanBadge plan={row.plan} />
                    </td>
                    <td className="px-5 py-4">
                      {row.banned ? (
                        <span className="inline-flex items-center gap-1 rounded-full border border-red-500/30 bg-red-500/10 px-2 py-0.5 text-xs font-medium text-red-400">
                          <Ban className="h-3 w-3" /> Banned
                        </span>
                      ) : row.role === "admin" ? (
                        <span className="inline-flex items-center gap-1 rounded-full border border-rose-500/30 bg-rose-500/10 px-2 py-0.5 text-xs font-medium text-rose-300">
                          <ShieldAlert className="h-3 w-3" /> Admin
                        </span>
                      ) : (
                        <span className="text-xs capitalize text-white/40">
                          {row.subscription_status || "active"}
                        </span>
                      )}
                    </td>
                    <td className="px-5 py-4 text-right text-sm tabular-nums text-white/70">{row.propertyCount}</td>
                    <td className="px-5 py-4 text-right text-sm tabular-nums text-white/70">{row.tenantCount}</td>
                    <td className="px-5 py-4 text-sm text-white/50">{formatDate(row.created_at)}</td>
                    <td className="px-5 py-4 text-right">
                      <Link
                        href={`/admin/users/${row.id}`}
                        className="inline-flex items-center gap-1 text-xs text-white/30 transition group-hover:text-rose-400"
                      >
                        View <ArrowRight className="h-3 w-3" />
                      </Link>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>

          {/* Mobile / tablet cards */}
          <div className="space-y-2 lg:hidden">
            {rows.map((row) => (
              <Link
                key={row.id}
                href={`/admin/users/${row.id}`}
                className="flex items-center gap-3 rounded-2xl border border-white/[0.06] bg-[#16161f] p-4 transition hover:border-rose-500/20 hover:bg-[#1a1a2e]"
              >
                <div className="flex h-10 w-10 shrink-0 items-center justify-center rounded-full bg-gradient-to-br from-rose-500/20 to-red-500/20 text-sm font-bold text-rose-300 ring-1 ring-inset ring-rose-500/20">
                  {initials(row.full_name || row.email)}
                </div>
                <div className="min-w-0 flex-1">
                  <div className="flex items-center gap-2">
                    <p className="truncate text-sm font-semibold text-white">{row.full_name || row.email}</p>
                    {row.banned && (
                      <span className="inline-flex shrink-0 items-center gap-1 rounded-full border border-red-500/30 bg-red-500/10 px-1.5 py-0.5 text-[10px] font-medium text-red-400">
                        <Ban className="h-2.5 w-2.5" /> Banned
                      </span>
                    )}
                  </div>
                  <p className="truncate text-xs text-white/35">{row.email}</p>
                  <div className="mt-1.5 flex items-center gap-3 text-xs text-white/40">
                    <span className="flex items-center gap-1">
                      <Building2 className="h-3 w-3" />
                      {row.propertyCount}
                    </span>
                    <span className="flex items-center gap-1">
                      <UsersIcon className="h-3 w-3" />
                      {row.tenantCount}
                    </span>
                    <span>{formatDate(row.created_at)}</span>
                  </div>
                </div>
                <PlanBadge plan={row.plan} />
              </Link>
            ))}
          </div>

          {/* Pagination */}
          <div className="flex flex-col items-center justify-between gap-3 pt-1 sm:flex-row">
            <p className="text-xs text-white/40">
              Page {page} of {pageCount} · {total.toLocaleString()} {total === 1 ? "user" : "users"}
            </p>
            <div className="flex items-center gap-2">
              {page > 1 ? (
                <Link
                  href={buildUrl({ page: String(page - 1) })}
                  className="inline-flex items-center gap-1 rounded-lg border border-white/10 px-3 py-1.5 text-xs font-medium text-white/60 transition hover:border-white/20 hover:text-white"
                >
                  <ArrowLeft className="h-3 w-3" /> Prev
                </Link>
              ) : (
                <span className="inline-flex cursor-not-allowed items-center gap-1 rounded-lg border border-white/[0.04] px-3 py-1.5 text-xs font-medium text-white/20">
                  <ArrowLeft className="h-3 w-3" /> Prev
                </span>
              )}
              {page < pageCount ? (
                <Link
                  href={buildUrl({ page: String(page + 1) })}
                  className="inline-flex items-center gap-1 rounded-lg border border-white/10 px-3 py-1.5 text-xs font-medium text-white/60 transition hover:border-white/20 hover:text-white"
                >
                  Next <ArrowRight className="h-3 w-3" />
                </Link>
              ) : (
                <span className="inline-flex cursor-not-allowed items-center gap-1 rounded-lg border border-white/[0.04] px-3 py-1.5 text-xs font-medium text-white/20">
                  Next <ArrowRight className="h-3 w-3" />
                </span>
              )}
            </div>
          </div>
        </>
      )}
    </div>
  )
}
