import prisma from "@/lib/prisma";
import { auth } from "@/lib/auth";
import { redirect } from "next/navigation";
import Link from "next/link";

interface Props {
  searchParams: Promise<{ page?: string; search?: string }>;
}

export default async function AdminLoginHistoryPage({ searchParams }: Props) {
  const session = await auth();
  if (!session?.user || session.user.userType !== "admin") {
    redirect("/login");
  }

  const sp = await searchParams;
  const page = parseInt(sp.page || "1");
  const search = sp.search || "";
  const perPage = 50;
  const offset = (page - 1) * perPage;

  let totalCount = 0;
  let totalPages = 0;
  let sessions: {
    id: number;
    user_id: number | null;
    ip_address: string | null;
    user_agent: string | null;
    last_activity: number | null;
  }[] = [];

  try {
    // Ensure login_history table exists
    await prisma.$executeRawUnsafe(`
      CREATE TABLE IF NOT EXISTS login_history (
        id SERIAL PRIMARY KEY,
        user_id INT,
        ip_address VARCHAR(45),
        user_agent TEXT,
        created_at TIMESTAMP DEFAULT NOW()
      )
    `);

    // Build query from sessions table (already exists)
    let whereClause = "";
    const params: (string | number)[] = [];

    if (search) {
      whereClause = `WHERE CAST(s.user_id AS TEXT) LIKE $1 OR s.ip_address LIKE $1`;
      params.push(`%${search}%`);
    }

    const countResult = await prisma.$queryRawUnsafe<[{ count: bigint }]>(
      `SELECT COUNT(*) as count FROM sessions s ${whereClause}`,
      ...params
    );
    totalCount = Number(countResult[0]?.count || 0);
    totalPages = Math.ceil(totalCount / perPage);

    sessions = await prisma.$queryRawUnsafe(
      `SELECT id, user_id, ip_address, user_agent, last_activity
       FROM sessions s
       ${whereClause}
       ORDER BY last_activity DESC NULLS LAST
       LIMIT ${perPage} OFFSET ${offset}`,
      ...params
    );
  } catch (e) {
    console.error("Failed to load login history:", e);
  }

  function formatTimestamp(ts: number | null) {
    if (!ts) return "—";
    return new Date(ts * 1000).toLocaleString(undefined, {
      dateStyle: "short",
      timeStyle: "medium",
    });
  }

  function truncateUA(ua: string | null) {
    if (!ua) return "—";
    return ua.length > 80 ? ua.substring(0, 80) + "..." : ua;
  }

  return (
    <div className="space-y-6">
      <h1 className="text-2xl font-bold">Login History / Sessions</h1>

      {/* Search */}
      <form className="flex gap-2 max-w-lg">
        <input
          type="text"
          name="search"
          defaultValue={search}
          placeholder="Search by user ID or IP..."
          className="flex-1 bg-surface-light border border-surface-light rounded-lg px-4 py-2 text-white text-sm focus:outline-none focus:ring-2 focus:ring-primary"
        />
        <button
          type="submit"
          className="bg-primary hover:bg-primary-dark text-white px-4 py-2 rounded-lg text-sm transition-colors"
        >
          Search
        </button>
        {search && (
          <Link
            href="/login-history"
            className="bg-surface hover:bg-surface-light text-text-muted px-4 py-2 rounded-lg text-sm transition-colors"
          >
            Clear
          </Link>
        )}
      </form>

      <p className="text-text-muted text-sm">
        {totalCount} sessions total &middot; Page {page} of{" "}
        {Math.max(totalPages, 1)}
      </p>

      <div className="bg-surface rounded-lg overflow-hidden">
        <div className="overflow-x-auto">
          <table className="w-full text-left">
            <thead>
              <tr className="border-b border-surface-light text-text-muted text-sm">
                <th className="p-4 font-medium">ID</th>
                <th className="p-4 font-medium">User ID</th>
                <th className="p-4 font-medium">IP Address</th>
                <th className="p-4 font-medium">User Agent</th>
                <th className="p-4 font-medium">Last Activity</th>
              </tr>
            </thead>
            <tbody>
              {sessions.length === 0 && (
                <tr>
                  <td
                    colSpan={5}
                    className="p-8 text-center text-text-muted"
                  >
                    No sessions found
                  </td>
                </tr>
              )}
              {sessions.map((s) => (
                <tr
                  key={s.id}
                  className="border-b border-surface-light last:border-0 hover:bg-surface-light/50"
                >
                  <td className="p-4 text-text-muted font-mono text-sm">
                    {s.id}
                  </td>
                  <td className="p-4">
                    {s.user_id ? (
                      <Link
                        href={`/admin/users?search=${s.user_id}`}
                        className="text-primary hover:text-primary-dark text-sm transition-colors"
                      >
                        {s.user_id}
                      </Link>
                    ) : (
                      <span className="text-text-muted">—</span>
                    )}
                  </td>
                  <td className="p-4 font-mono text-sm">
                    {s.ip_address || "—"}
                  </td>
                  <td className="p-4 text-text-muted text-xs max-w-[300px] truncate">
                    {truncateUA(s.user_agent)}
                  </td>
                  <td className="p-4 text-text-muted text-sm whitespace-nowrap">
                    {formatTimestamp(s.last_activity)}
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </div>

      {/* Pagination */}
      {totalPages > 1 && (
        <div className="flex gap-2 justify-center">
          {page > 1 && (
            <Link
              href={`/login-history?page=${page - 1}${
                search ? `&search=${search}` : ""
              }`}
              className="bg-surface hover:bg-surface-light text-text-muted px-4 py-2 rounded-lg text-sm transition-colors"
            >
              Previous
            </Link>
          )}
          <span className="px-4 py-2 text-text-muted text-sm">
            Page {page} / {totalPages}
          </span>
          {page < totalPages && (
            <Link
              href={`/login-history?page=${page + 1}${
                search ? `&search=${search}` : ""
              }`}
              className="bg-surface hover:bg-surface-light text-text-muted px-4 py-2 rounded-lg text-sm transition-colors"
            >
              Next
            </Link>
          )}
        </div>
      )}
    </div>
  );
}
