import { adminGetUserSessionsApi } from "@/api/admin/sessions";
import Breadcrumbs from "@/components/ui/breadcrumbs";
import { Button } from "@/components/ui/button";
import Avatar from "@/feature/Avatar";
import type { DeviceInfo, UserSession } from "@/types";
import { Ban } from "lucide-react";
import { useEffect, useMemo, useState, type FC } from "react";
import { Link } from "react-router";
import moment from "moment";
import Pagination from "@/components/ui/pagination";

const SessionSource: FC<{ deviceInfo: string }> = ({ deviceInfo }) => {
  const parsed = useMemo<DeviceInfo>(
    () => JSON.parse(atob(deviceInfo)),
    [deviceInfo],
  );

  return (
    <p>
      {parsed.os} {parsed.os_version} {parsed.browser} {parsed.browser_version}
    </p>
  );
};

const AdminSessionsPage: FC = () => {
  const loading = false;
  const [sessions, setSessions] = useState<UserSession[]>([]);

  useEffect(() => {
    adminGetUserSessionsApi({
      limit: 10,
      offset: 0,
    }).then((res) => {
      console.log("get sessions response:", res);
      if (Array.isArray(res)) {
        return setSessions(res);
      }
    });
  }, []);

  return (
    <div className="relative flex flex-col items-stretch w-full">
      <div className="p-4">
        <Breadcrumbs
          className="pb-2"
          items={[
            {
              href: "/admin",
              label: "Admin",
            },
            {
              label: "User Sessions",
            },
          ]}
        />
      </div>
      <div className="p-4 flex flex-row items-center justify-between">
        <p className="text-gray-800 dark:text-gray-300">Search...</p>
        {/* TODO: Filters */}
      </div>

      <div className="flex-1 overflow-x-auto">
        <table className="relative min-w-full border-l-0 border border-gray-300 dark:border-gray-700 border-collapse divide-y divide-gray-200 dark:divide-gray-800">
          {loading && (
            <div className="absolute inset-0 z-10 flex items-center justify-center bg-white/60 dark:bg-gray-900/60 backdrop-blur-sm">
              <div className="text-gray-800 dark:text-gray-200 font-medium">
                Loading...
              </div>
            </div>
          )}

          <thead className="bg-black/5 dark:bg-white/5 text-nowrap">
            <tr>
              <th className="px-6 py-3 text-left text-sm font-semibold text-gray-700 dark:text-white/70 border border-l-0 border-gray-300 dark:border-gray-700">
                User
              </th>
              <th className="px-6 py-3 text-left text-sm font-semibold text-gray-700 dark:text-white/70 border border-l-0 border-gray-300 dark:border-gray-700">
                Source
              </th>
              <th className="px-6 py-3 text-left text-sm font-semibold text-gray-700 dark:text-white/70 border border-l-0 border-gray-300 dark:border-gray-700">
                Status
              </th>
              <th className="px-6 py-3 text-left text-sm font-semibold text-gray-700 dark:text-white/70 border border-l-0 border-gray-300 dark:border-gray-700">
                Issued At
              </th>
              <th className="px-6 py-3 text-left text-sm font-semibold text-gray-700 dark:text-white/70 border border-l-0 border-gray-300 dark:border-gray-700">
                Expires At
              </th>
              <th className="px-6 py-3 text-left text-sm font-semibold text-gray-700 dark:text-white/70 border border-l-0 border-gray-300 dark:border-gray-700">
                Last Active
              </th>
              <th className="px-6 py-3 text-left text-sm font-semibold text-gray-700 dark:text-white/70 border border-l-0 border-gray-300 dark:border-gray-700">
                Revoked At
              </th>
              <th className="px-6 py-3 text-left text-sm font-semibold text-gray-700 dark:text-white/70 border border-l-0 border-gray-300 dark:border-gray-700">
                Actions
              </th>
            </tr>
          </thead>
          <tbody className="divide-y divide-gray-200 dark:divide-gray-700">
            {!loading && sessions.length === 0 ? (
              <tr>
                <td
                  colSpan={5}
                  className="px-6 py-12 text-center text-gray-500 dark:text-gray-400"
                >
                  No sessions found.
                </td>
              </tr>
            ) : (
              sessions.map((session) => (
                <tr
                  key={session.id}
                  className="hover:bg-gray-50 dark:hover:bg-gray-800"
                >
                  {/* <td className="px-6 py-4 text-sm font-medium text-blue-600 border border-gray-300 dark:border-gray-700">
                    <span className="inline-block px-2 py-1 text-xs rounded-full font-semibold bg-green-100 text-green-800 dark:bg-green-900 dark:text-green-300">
                      {sessionsType}
                    </span>
                  </td> */}
                  <td className="px-6 py-4 text-sm text-gray-700 dark:text-gray-300 border border-gray-300 dark:border-gray-700">
                    <div className="flex flex-row items-center gap-2 justify-start">
                      {typeof session.user?.profile_picture === "string" && (
                        <Avatar
                          avatarId={session.user.profile_picture}
                          className="w-7 h-7 min-w-7"
                        />
                      )}
                      <Link to={`/admin/users/${session.user_id}`}>
                        <p className="cursor-pointer text-blue-500">
                          {session.user?.full_name ?? ""}
                        </p>
                      </Link>
                    </div>
                  </td>
                  <td className="px-6 py-4 text-sm text-gray-700 dark:text-gray-300 border border-gray-300 dark:border-gray-700">
                    <SessionSource deviceInfo={session.device_info} />
                  </td>
                  <td className="px-6 py-4 text-sm border border-gray-300 dark:border-gray-700">
                    <span
                      className={`inline-block px-2 py-1 text-xs rounded-full font-semibold ${
                        !session.is_active ||
                        (session.expires_at &&
                          moment(session.expires_at).isSameOrBefore(
                            moment(new Date()),
                          ))
                          ? "bg-red-100 text-red-800 dark:bg-red-900 dark:text-red-300"
                          : "bg-green-100 text-green-800 dark:bg-green-900 dark:text-green-300"
                      }`}
                    >
                      {session.is_active ? "Active" : "Inactive"}
                      {moment(session.expires_at).isSameOrBefore(
                        moment(new Date()),
                      ) && " (Expired)"}
                    </span>
                  </td>
                  <td className="px-6 py-4 text-sm text-gray-500 dark:text-gray-400 border border-gray-300 dark:border-gray-700">
                    {moment(session.issued_at).format("LLLL")}
                  </td>
                  <td className="px-6 py-4 text-sm text-gray-500 dark:text-gray-400 border border-gray-300 dark:border-gray-700">
                    {session.expires_at
                      ? moment(session.expires_at).format("LLLL")
                      : "never"}
                  </td>
                  <td className="px-6 py-4 text-sm text-gray-500 dark:text-gray-400 border border-gray-300 dark:border-gray-700">
                    {session.last_active
                      ? moment(session.last_active).format("LLLL")
                      : "never"}
                  </td>
                  <td className="px-6 py-4 text-sm text-gray-500 dark:text-gray-400 border border-gray-300 dark:border-gray-700">
                    {session.revoked_at
                      ? new Date(session.revoked_at).toLocaleString()
                      : "never"}
                  </td>
                  <td>
                    <div className="flex flex-row items-center justify-center gap-2">
                      <Button
                        variant="contained"
                        className="bg-red-500 hover:bg-red-600 !px-1.5 !py-1.5"
                      >
                        <Ban size={18} />
                      </Button>
                    </div>
                  </td>
                </tr>
              ))
            )}
          </tbody>
        </table>

        <Pagination currentPage={1} onPageChange={console.log} totalPages={2} />
      </div>
    </div>
  );
};

export default AdminSessionsPage;
