"use client";

import { useCallback, useEffect, useState } from "react";

import { NoPermissionState } from "@/components/auth/no-permission-state";
import { useSuperAdminSession } from "@/components/auth/session-context";
import { PageHeader } from "@/components/dashboard/page-header";
import { PaginationControls } from "@/components/dashboard/pagination-controls";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { EmptyState } from "@/components/ui/empty-state";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import { useToast } from "@/components/ui/toast";
import { listAuditLogs } from "@/lib/api/audit";
import { listSuperAdminSessions, revokeSuperAdminSession } from "@/lib/api/auth";
import { getItems, getPagination } from "@/lib/api/core";
import { getSuperAdminOps } from "@/lib/api/superadmin";
import { formatDateTime } from "@/lib/format";
import { SUPERADMIN_PERMISSIONS, hasPermission } from "@/lib/permissions";
import type {
  AuditLogsResponse,
  SessionItem,
  SessionsResponse,
  SuperAdminOpsResponse,
} from "@/types/api";

const EMPTY_SESSIONS: SessionsResponse = { items: [] };
const EMPTY_AUDIT: AuditLogsResponse = { items: [], data: [] };
const EMPTY_OPS: SuperAdminOpsResponse = {
  services: {
    mongodb: { status: "unknown" },
    redis: { enabled: false, status: "unknown" },
    queue: { enabled: false },
    storage: {},
    email: { enabled: false },
    websocket: { redisAdapterEnabled: false },
  },
  queues: {
    outbox: { pending: 0, failed: 0 },
  },
  workload: {
    openCasesCount: 0,
    activeSuperAdminSessionsCount: 0,
  },
};

export default function SecurityPage() {
  const { session, permissions } = useSuperAdminSession();
  const [sessionsResponse, setSessionsResponse] = useState<SessionsResponse | null>(null);
  const [auditResponse, setAuditResponse] = useState<AuditLogsResponse | null>(null);
  const [ops, setOps] = useState<SuperAdminOpsResponse | null>(null);
  const [auditPage, setAuditPage] = useState(1);
  const [loading, setLoading] = useState(true);
  const { toast } = useToast();

  const canManageSessions = hasPermission(
    permissions,
    SUPERADMIN_PERMISSIONS.SESSIONS_MANAGE,
  );
  const canReadAudit = hasPermission(permissions, SUPERADMIN_PERMISSIONS.AUDIT_READ);
  const canReadOps = hasPermission(permissions, SUPERADMIN_PERMISSIONS.OPS_READ);

  const loadSecurity = useCallback(async () => {
    if (!canManageSessions && !canReadAudit && !canReadOps) {
      setLoading(false);
      return;
    }

    setLoading(true);
    try {
      const [sessions, audit, nextOps] = await Promise.all([
        canManageSessions ? listSuperAdminSessions() : Promise.resolve(EMPTY_SESSIONS),
        canReadAudit
          ? listAuditLogs({ page: auditPage, limit: 12, sortOrder: "desc" })
          : Promise.resolve(EMPTY_AUDIT),
        canReadOps ? getSuperAdminOps() : Promise.resolve(EMPTY_OPS),
      ]);
      setSessionsResponse(sessions);
      setAuditResponse(audit);
      setOps(nextOps);
    } catch (error) {
      toast({ title: "Failed to load security page", description: String(error), variant: "danger" });
    } finally {
      setLoading(false);
    }
  }, [auditPage, canManageSessions, canReadAudit, canReadOps, toast]);

  useEffect(() => {
    void loadSecurity();
  }, [loadSecurity]);

  const sessions = (sessionsResponse?.items ?? []) as SessionItem[];

  if (!canManageSessions && !canReadAudit && !canReadOps) {
    return (
      <div className="space-y-5 pb-8">
        <PageHeader
          title="Security and sessions"
          subtitle="SuperAdmin sessions, granted permissions, audit trail, and live operational status."
        />
        <NoPermissionState description="This page needs sessions.manage, audit.read, ops.read, or a combination of them." />
      </div>
    );
  }

  return (
    <div className="space-y-5 pb-8">
      <PageHeader
        title="Security and sessions"
        subtitle="SuperAdmin sessions, granted permissions, audit trail, and live operational status."
      />

      <section className="grid gap-4 md:grid-cols-4">
        {canManageSessions ? (
          <Card>
            <CardHeader>
              <CardTitle>Active sessions</CardTitle>
            </CardHeader>
            <CardContent className="text-3xl font-bold text-foreground">{sessions.length}</CardContent>
          </Card>
        ) : null}
        <Card>
          <CardHeader>
            <CardTitle>Session strategy</CardTitle>
          </CardHeader>
          <CardContent className="space-y-2">
            <Badge variant="success">{session?.sessionStrategy ?? "httpOnly_cookies"}</Badge>
            <p className="text-sm text-muted-foreground">Proxy-managed secure cookies.</p>
          </CardContent>
        </Card>
        {canReadOps ? (
          <>
            <Card>
              <CardHeader>
                <CardTitle>Mongo / Redis</CardTitle>
              </CardHeader>
              <CardContent className="space-y-2 text-sm text-muted-foreground">
                <div>MongoDB: {ops?.services.mongodb.status ?? "-"}</div>
                <div>Redis: {ops?.services.redis.status ?? "-"}</div>
              </CardContent>
            </Card>
            <Card>
              <CardHeader>
                <CardTitle>Outbox</CardTitle>
              </CardHeader>
              <CardContent className="space-y-2 text-sm text-muted-foreground">
                <div>Pending: {ops?.queues.outbox.pending ?? 0}</div>
                <div>Failed: {ops?.queues.outbox.failed ?? 0}</div>
              </CardContent>
            </Card>
          </>
        ) : null}
      </section>

      <Card>
        <CardHeader>
          <CardTitle>Granted permissions</CardTitle>
        </CardHeader>
        <CardContent className="flex flex-wrap gap-2">
          {(session?.permissions ?? []).map((permission) => (
            <Badge key={permission} variant="muted">
              {permission}
            </Badge>
          ))}
        </CardContent>
      </Card>

      <section className="grid gap-4 xl:grid-cols-12">
        {canManageSessions ? (
          <Card className={canReadAudit ? "xl:col-span-5" : "xl:col-span-12"}>
            <CardHeader>
              <CardTitle>SuperAdmin sessions</CardTitle>
            </CardHeader>
            <CardContent>
              {!sessions.length && !loading ? (
                <EmptyState title="No sessions" description="The backend returned no active SuperAdmin sessions." />
              ) : (
                <div className="space-y-3">
                  {sessions.map((sessionItem) => (
                    <div key={sessionItem.id ?? sessionItem.jti} className="rounded-xl border border-border/70 bg-secondary/20 p-4">
                      <div className="flex items-center justify-between gap-3">
                        <div>
                          <p className="text-sm font-medium text-foreground">{sessionItem.id ?? sessionItem.jti ?? "-"}</p>
                          <p className="mt-1 text-xs text-muted-foreground">
                            {formatDateTime(sessionItem.createdAt)} - {formatDateTime(sessionItem.expiresAt)}
                          </p>
                        </div>
                        <Button
                          size="sm"
                          variant="danger"
                          onClick={async () => {
                            const sessionId = sessionItem.id ?? sessionItem.jti;
                            if (!sessionId) return;
                            try {
                              await revokeSuperAdminSession(sessionId);
                              await loadSecurity();
                              toast({ title: "Session revoked", description: sessionId, variant: "warning" });
                            } catch (error) {
                              toast({ title: "Failed to revoke session", description: String(error), variant: "danger" });
                            }
                          }}
                        >
                          Revoke
                        </Button>
                      </div>
                    </div>
                  ))}
                </div>
              )}
            </CardContent>
          </Card>
        ) : null}

        {canReadAudit ? (
          <Card className={canManageSessions ? "xl:col-span-7" : "xl:col-span-12"}>
            <CardHeader>
              <CardTitle>Audit log</CardTitle>
            </CardHeader>
            <CardContent className="space-y-4">
              {!getItems(auditResponse).length && !loading ? (
                <EmptyState title="No audit records" description="Recent SuperAdmin actions will appear here." />
              ) : (
                <Table>
                  <TableHeader>
                    <TableRow>
                      <TableHead>Action</TableHead>
                      <TableHead>Actor</TableHead>
                      <TableHead>Target</TableHead>
                      <TableHead>Time</TableHead>
                    </TableRow>
                  </TableHeader>
                  <TableBody>
                    {getItems(auditResponse).map((log) => (
                      <TableRow key={log._id}>
                        <TableCell>{log.action}</TableCell>
                        <TableCell>{log.actorIdentifier ?? log.actorType}</TableCell>
                        <TableCell>{log.targetType}</TableCell>
                        <TableCell>{formatDateTime(log.createdAt)}</TableCell>
                      </TableRow>
                    ))}
                  </TableBody>
                </Table>
              )}
              <PaginationControls pagination={getPagination(auditResponse)} loading={loading} onPageChange={setAuditPage} />
            </CardContent>
          </Card>
        ) : null}
      </section>
    </div>
  );
}
