import Breadcrumbs from "@/components/ui/breadcrumbs";
import { Button } from "@/components/ui/button";
import Avatar from "@/feature/Avatar";
import { Ban } from "lucide-react";
import { useCallback, useEffect, type FC } from "react";
import { Link } from "react-router";
import moment from "moment";
import Pagination from "@/components/ui/pagination";
import { useAuth } from "@/store/auth";
import { useServiceSessions } from "@/store/admin/serviceSessions";

const AdminServiceSessionsPage: FC = () => {
  const loading = useServiceSessions((s) => s.loading);
  const sessions = useServiceSessions((s) => s.items);

  const page = useServiceSessions((s) => s.page);
  const totalPages = useServiceSessions((s) => s.totalPages);

  const fetchSessions = useServiceSessions((s) => s.fetch);
  const revokeSession = useServiceSessions((s) => s.revoke);

  const revokingId = useServiceSessions((s) => s.revokingId);

  const profile = useAuth((s) => s.profile);

  const handleRevokeSession = useCallback(
    (id: string) => {
      revokeSession(id);
    },
    [revokeSession],
  );

  useEffect(() => {
    fetchSessions(1);
  }, [fetchSessions]);

  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: "Service 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">
                Service
              </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">
                User + IP
              </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-5 py-3 text-sm text-gray-700 dark:text-gray-300 border border-gray-300 dark:border-gray-700">
                    {/* <SessionSource deviceInfo={session.} /> */}
                    {typeof session.api_service?.icon_url === "string" && (
                      <Avatar
                        avatarId={session.api_service.icon_url}
                        className="w-7 h-7 min-w-7"
                      />
                    )}
                    <Link to={`/admin/api-services/view/${session.service_id}`}>
                      <p className="cursor-pointer text-blue-500 text-nowrap">
                        {session.api_service?.name ?? session.client_id}
                      </p>
                    </Link>
                  </td>

                  <td className="px-5 py-3 text-sm text-gray-700 dark:text-gray-300 border border-gray-300 dark:border-gray-700">
                    <div className="flex flex-col items-stretch gap-2 justify-start">
                      <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"
                          />
                        )}

                        <div className="flex flex-col items-stretch justify-center">
                          <Link to={`/admin/users/view/${session.user_id}`}>
                            <p className="cursor-pointer text-blue-500 text-nowrap">
                              {session.user?.full_name ?? ""}{" "}
                              {session.user_id === profile?.id ? "(You)" : ""}
                            </p>
                          </Link>
                          <p className="opacity-75">
                            {session.ip_address ?? "No IP available"}
                          </p>
                        </div>
                      </div>
                    </div>
                  </td>
                  <td className="px-5 py-3 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-5 py-3 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-5 py-3 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-5 py-3 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-5 py-3 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"
                        onClick={() => handleRevokeSession(session.id)}
                        disabled={revokingId === session.id}
                      >
                        <Ban size={18} />
                      </Button>
                    </div>
                  </td>
                </tr>
              ))
            )}
          </tbody>
        </table>
      </div>
      <Pagination
        currentPage={page}
        onPageChange={(newPage) => fetchSessions(newPage)}
        totalPages={totalPages}
      />
    </div>
  );
};

export default AdminServiceSessionsPage;
