"use client";

import { useCallback, useEffect, useMemo, useState } from "react";
import Link from "next/link";
import { Loader2, Search, Smartphone, UserCheck, Users, X } from "lucide-react";
import { AdminGuard } from "@/components/admin/AdminGuard";
import { AdminShell } from "@/components/admin/AdminShell";
import { adminRequest, type AdminUser } from "@/lib/admin-api";

function formatDate(value: string | null) {
  if (!value) {
    return "-";
  }

  const date = new Date(value);

  if (Number.isNaN(date.getTime())) {
    return value;
  }

  return new Intl.DateTimeFormat("en-IN", {
    day: "2-digit",
    month: "short",
    year: "numeric",
    hour: "2-digit",
    minute: "2-digit",
  }).format(date);
}

export default function AdminUsersPage() {
  const [users, setUsers] = useState<AdminUser[]>([]);
  const [search, setSearch] = useState("");
  const [isLoading, setIsLoading] = useState(true);
  const [errorMessage, setErrorMessage] = useState("");

  const loadUsers = useCallback(async () => {
    setIsLoading(true);
    setErrorMessage("");

    try {
      const params = new URLSearchParams();

      if (search.trim()) {
        params.set("search", search.trim());
      }

      const data = await adminRequest<{ users: AdminUser[] }>(
        `/api/admin/users${params.toString() ? `?${params.toString()}` : ""}`,
      );
      setUsers(data.users);
    } catch (error) {
      setErrorMessage(error instanceof Error ? error.message : "Could not load users");
    } finally {
      setIsLoading(false);
    }
  }, [search]);

  useEffect(() => {
    const timer = window.setTimeout(loadUsers, 250);

    return () => window.clearTimeout(timer);
  }, [loadUsers]);

  const totals = useMemo(
    () => ({
      all: users.length,
      verified: users.filter((user) => user.isMobileVerified).length,
      activeSessions: users.reduce((sum, user) => sum + user.activeSessionCount, 0),
      orders: users.reduce((sum, user) => sum + (user.orderCount ?? 0), 0),
    }),
    [users],
  );

  return (
    <AdminGuard>
      <AdminShell
        title="Users"
        lead="Customer accounts created from website mobile OTP authentication."
      >
        <section className="space-y-5">
          <div className="grid gap-3 md:grid-cols-4">
            <StatCard label="Users" value={totals.all} icon={Users} />
            <StatCard label="Mobile verified" value={totals.verified} icon={UserCheck} />
            <StatCard label="Active sessions" value={totals.activeSessions} icon={Smartphone} />
            <StatCard label="Orders" value={totals.orders} icon={UserCheck} />
          </div>

          <div className="rounded-lg border border-border bg-white p-4 shadow-sm">
            <div className="relative">
              <Search className="pointer-events-none absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" />
              <input
                value={search}
                onChange={(event) => setSearch(event.target.value)}
                placeholder="Search by name, mobile, or email"
                className="h-11 w-full rounded-md border border-border bg-white pl-10 pr-11 text-sm font-semibold outline-none transition focus:border-primary focus:ring-2 focus:ring-primary/15"
              />
              {search ? (
                <button
                  type="button"
                  onClick={() => setSearch("")}
                  className="absolute right-2 top-1/2 grid h-8 w-8 -translate-y-1/2 place-items-center rounded-md text-muted-foreground hover:bg-slate-100 hover:text-foreground"
                  aria-label="Clear user search"
                >
                  <X className="h-4 w-4" />
                </button>
              ) : null}
            </div>
          </div>

          {errorMessage ? (
            <p className="rounded-md border border-destructive/30 bg-destructive/10 px-3 py-2 text-sm font-bold text-destructive">
              {errorMessage}
            </p>
          ) : null}

          <div className="overflow-hidden rounded-lg border border-border bg-white shadow-sm">
            <div className="flex items-center justify-between border-b border-border px-4 py-3">
              <p className="text-xs font-black uppercase tracking-[0.14em] text-muted-foreground">
                Customer users
              </p>
              {isLoading ? (
                <span className="inline-flex items-center gap-2 text-xs font-black uppercase tracking-[0.14em] text-muted-foreground">
                  <Loader2 className="h-4 w-4 animate-spin" />
                  Loading
                </span>
              ) : null}
            </div>

            {isLoading ? (
              <div className="p-4">
                {Array.from({ length: 6 }).map((_, index) => (
                  <div key={index} className="mb-3 h-16 rounded-md bg-slate-100" />
                ))}
              </div>
            ) : users.length === 0 ? (
              <p className="px-4 py-10 text-center text-sm font-semibold text-muted-foreground">
                No users found.
              </p>
            ) : (
              <div className="overflow-x-auto">
                <table className="w-full min-w-[980px] text-left text-sm">
                  <thead className="bg-slate-50 text-xs font-black uppercase tracking-[0.12em] text-muted-foreground">
                    <tr>
                      <th className="px-4 py-3">User</th>
                      <th className="px-4 py-3">Mobile</th>
                      <th className="px-4 py-3">Status</th>
                      <th className="px-4 py-3">Sessions</th>
                      <th className="px-4 py-3">Orders</th>
                      <th className="px-4 py-3">Last login</th>
                      <th className="px-4 py-3">Created</th>
                      <th className="px-4 py-3">Details</th>
                    </tr>
                  </thead>
                  <tbody className="divide-y divide-border">
                    {users.map((user) => (
                      <tr key={user.id} className="align-top">
                        <td className="px-4 py-4">
                          <p className="font-black text-foreground">
                            {user.name && user.name !== "User" ? user.name : "Profile pending"}
                          </p>
                          <p className="mt-1 text-xs font-bold text-muted-foreground">
                            {user.email ?? "No email saved"}
                          </p>
                        </td>
                        <td className="px-4 py-4 font-bold text-foreground">{user.mobile}</td>
                        <td className="px-4 py-4">
                          <span
                            className={`inline-flex rounded-md px-2 py-1 text-xs font-black uppercase tracking-[0.12em] ${
                              user.status === "active"
                                ? "bg-emerald-100 text-emerald-700"
                                : "bg-slate-100 text-muted-foreground"
                            }`}
                          >
                            {user.status}
                          </span>
                          <p className="mt-2 text-xs font-bold text-muted-foreground">
                            {user.isMobileVerified ? "Mobile verified" : "Mobile not verified"}
                          </p>
                        </td>
                        <td className="px-4 py-4 font-bold text-muted-foreground">
                          <span className="text-foreground">{user.activeSessionCount}</span> active
                          <br />
                          {user.sessionCount} total
                        </td>
                        <td className="px-4 py-4 font-bold text-foreground">
                          {user.orderCount ?? 0}
                        </td>
                        <td className="px-4 py-4 font-bold text-muted-foreground">
                          {formatDate(user.lastLoginAt)}
                        </td>
                        <td className="px-4 py-4 font-bold text-muted-foreground">
                          {formatDate(user.createdAt)}
                        </td>
                        <td className="px-4 py-4">
                          <Link
                            href={`/admin/users/${user.id}`}
                            className="inline-flex h-9 items-center justify-center rounded-md border border-border px-3 text-xs font-black text-muted-foreground transition hover:bg-slate-100 hover:text-foreground"
                          >
                            View
                          </Link>
                        </td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            )}
          </div>
        </section>
      </AdminShell>
    </AdminGuard>
  );
}

function StatCard({
  label,
  value,
  icon: Icon,
}: {
  label: string;
  value: number;
  icon: React.ComponentType<{ className?: string }>;
}) {
  return (
    <div className="rounded-lg border border-border bg-white p-4 shadow-sm">
      <div className="flex items-center justify-between gap-4">
        <div>
          <p className="text-xs font-black uppercase tracking-[0.14em] text-muted-foreground">
            {label}
          </p>
          <p className="mt-2 text-3xl font-black text-foreground">{value}</p>
        </div>
        <div className="grid h-11 w-11 place-items-center rounded-md bg-primary/10 text-primary">
          <Icon className="h-5 w-5" />
        </div>
      </div>
    </div>
  );
}
