"use client";

import * as React from "react";
import { format } from "date-fns";
import { useSession } from "next-auth/react";
import {
  useGetSuspiciousActivityQuery,
  SUSPICIOUS_ACTIVITY_TYPE_OPTIONS,
} from "@/api/rtk/admin-suspicious-activity-api";
import { useGetProfileQuery } from "@/api/rtk/auth-api";
import { useAuthToken } from "@/hooks/use-auth-token";
import { hasPermission, type PermissionSource } from "@/lib/permissions";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { ReactSelect } from "@/components/ui/react-select";
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table";
import { Loading } from "@/components/ui/loading";
import {
  ChevronLeft,
  ChevronRight,
  MapPin,
  ShieldAlert,
  TriangleAlert,
} from "lucide-react";
import { cn } from "@/lib/utils";

function severityBadgeClass(sev: string): string {
  const u = sev.toUpperCase();
  if (u === "HIGH") {
    return "bg-red-50 text-red-800 border border-red-100";
  }
  if (u === "LOW") {
    return "bg-slate-100 text-slate-700 border border-slate-200";
  }
  return "bg-amber-50 text-amber-900 border border-amber-100";
}

function formatMetadata(meta: unknown): string {
  if (meta == null || meta === "") return "—";
  try {
    const s = JSON.stringify(meta);
    return s.length > 120 ? `${s.slice(0, 120)}…` : s;
  } catch {
    return "—";
  }
}

export default function SuspiciousActivityPage() {
  const { token } = useAuthToken();
  const { data: session } = useSession();
  const { data: profile } = useGetProfileQuery(undefined, { skip: !token });
  const permissionSource: PermissionSource =
    (session as { backendUser?: PermissionSource } | null)?.backendUser ?? profile ?? null;
  const canRead = hasPermission(
    permissionSource,
    "READ",
    "SUSPICIOUS_ACTIVITY",
  );

  const [page, setPage] = React.useState(1);
  const [typeFilter, setTypeFilter] = React.useState<string>("ALL");
  const [emailFilter, setEmailFilter] = React.useState("");
  const [ipFilter, setIpFilter] = React.useState("");
  const [userIdFilter, setUserIdFilter] = React.useState("");

  const [applied, setApplied] = React.useState({
    type: "ALL" as string,
    email: "",
    ip: "",
    userId: "",
  });

  const queryParams = React.useMemo(
    () => ({
      page,
      limit: 25,
      ...(applied.userId.trim() ? { userId: applied.userId.trim() } : {}),
      ...(applied.type !== "ALL" && applied.type.trim()
        ? { type: applied.type.trim() }
        : {}),
      ...(applied.email.trim() ? { email: applied.email.trim() } : {}),
      ...(applied.ip.trim() ? { ipAddress: applied.ip.trim() } : {}),
    }),
    [page, applied],
  );

  const { data, isLoading, isError, refetch } = useGetSuspiciousActivityQuery(
    queryParams,
    { skip: !canRead || !token },
  );

  const applyFilters = () => {
    setApplied({
      type: typeFilter,
      email: emailFilter,
      ip: ipFilter,
      userId: userIdFilter,
    });
    setPage(1);
  };

  const clearFilters = () => {
    setTypeFilter("ALL");
    setEmailFilter("");
    setIpFilter("");
    setUserIdFilter("");
    setApplied({ type: "ALL", email: "", ip: "", userId: "" });
    setPage(1);
  };

  if (!token || !canRead) {
    return (
      <div className="flex flex-col items-center justify-center min-h-[50vh] gap-4 p-8 text-center">
        <ShieldAlert className="size-12 text-muted-foreground" />
        <h1 className="text-lg font-semibold font-['Lexend']">
          Access restricted
        </h1>
        <p className="text-sm text-muted-foreground max-w-md">
          You need READ permission on Suspicious activity to view this page.
        </p>
      </div>
    );
  }

  if (isLoading) {
    return (
      <Loading
        layout="page"
        message="Loading suspicious activity…"
        className="min-h-[40vh]"
      />
    );
  }

  if (isError || !data) {
    return (
      <div className="p-8 text-center text-destructive text-sm">
        Failed to load suspicious activity. Try again later.
        <div className="mt-4">
          <Button type="button" variant="outline" size="sm" onClick={() => void refetch()}>
            Retry
          </Button>
        </div>
      </div>
    );
  }

  const rows = data.data;
  const { totalPages } = data;

  return (
    <div className="flex flex-col gap-6 p-4 md:p-6 animate-in fade-in duration-300">
      <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4">
        <div className="flex items-start gap-3">
          <div className="size-11 rounded-2xl bg-destructive/10 flex items-center justify-center shrink-0">
            <TriangleAlert className="size-5 text-destructive" />
          </div>
          <div>
            <h1 className="text-xl font-bold font-['Lexend'] tracking-tight">
              Suspicious activity
            </h1>
            <p className="text-sm text-muted-foreground mt-0.5 max-w-2xl">
              Failed logins, inactive account attempts, wrong passwords, and
              device or IP allowlist rejections. Each row captures IP, user
              agent, optional device token and MAC, and extra context in
              metadata.
            </p>
          </div>
        </div>
      </div>

      <div className="rounded-2xl border border-border/60 bg-card shadow-sm p-4 md:p-5 space-y-4">
        <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4">
          <div className="space-y-2">
            <Label className="text-xs font-medium text-muted-foreground">Event type</Label>
            <ReactSelect
              value={typeFilter}
              onValueChange={setTypeFilter}
              options={SUSPICIOUS_ACTIVITY_TYPE_OPTIONS.map((opt) => ({
                value: opt.value,
                label: opt.label,
              }))}
              placeholder="Type"
              aria-label="Event type"
              triggerClassName="h-9"
            />
          </div>
          <div className="space-y-2">
            <Label htmlFor="sa-email" className="text-xs font-medium text-muted-foreground">
              Email contains
            </Label>
            <Input
              id="sa-email"
              className="h-9"
              value={emailFilter}
              onChange={(e) => setEmailFilter(e.target.value)}
              placeholder="e.g. admin@"
            />
          </div>
          <div className="space-y-2">
            <Label htmlFor="sa-ip" className="text-xs font-medium text-muted-foreground">
              IP contains
            </Label>
            <Input
              id="sa-ip"
              className="h-9"
              value={ipFilter}
              onChange={(e) => setIpFilter(e.target.value)}
              placeholder="e.g. 192.168"
            />
          </div>
          <div className="space-y-2">
            <Label htmlFor="sa-user" className="text-xs font-medium text-muted-foreground">
              User ID
            </Label>
            <Input
              id="sa-user"
              className="h-9 font-mono text-xs"
              value={userIdFilter}
              onChange={(e) => setUserIdFilter(e.target.value)}
              placeholder="UUID"
            />
          </div>
        </div>
        <div className="flex flex-wrap gap-2">
          <Button type="button" size="sm" onClick={applyFilters}>
            Apply filters
          </Button>
          <Button type="button" size="sm" variant="outline" onClick={clearFilters}>
            Clear
          </Button>
        </div>
      </div>

      <div className="rounded-2xl border border-border/60 bg-card shadow-sm overflow-x-auto">
        <Table>
          <TableHeader>
            <TableRow className="hover:bg-transparent">
              <TableHead className="font-['Lexend'] whitespace-nowrap">When</TableHead>
              <TableHead className="font-['Lexend']">Severity</TableHead>
              <TableHead className="font-['Lexend'] min-w-[160px]">Type</TableHead>
              <TableHead className="font-['Lexend']">User</TableHead>
              <TableHead className="font-['Lexend']">Email</TableHead>
              <TableHead className="font-['Lexend']">IP</TableHead>
              <TableHead className="font-['Lexend'] min-w-[100px]">Device token</TableHead>
              <TableHead className="font-['Lexend']">MAC</TableHead>
              <TableHead className="font-['Lexend'] min-w-[120px]">Location</TableHead>
              <TableHead className="font-['Lexend'] min-w-[140px]">User agent</TableHead>
              <TableHead className="font-['Lexend'] min-w-[160px]">Metadata</TableHead>
            </TableRow>
          </TableHeader>
          <TableBody>
            {rows.length === 0 ? (
              <TableRow>
                <TableCell
                  colSpan={11}
                  className="text-center py-12 text-muted-foreground"
                >
                  No events match these filters.
                </TableCell>
              </TableRow>
            ) : (
              rows.map((row) => (
                <TableRow key={row.id}>
                  <TableCell className="text-sm text-muted-foreground whitespace-nowrap align-top">
                    {format(new Date(row.createdAt), "MMM d, yyyy · h:mm a")}
                  </TableCell>
                  <TableCell className="align-top">
                    <span
                      className={cn(
                        "text-xs font-semibold uppercase tracking-wide px-2 py-0.5 rounded-lg inline-block",
                        severityBadgeClass(row.severity),
                      )}
                    >
                      {row.severity}
                    </span>
                  </TableCell>
                  <TableCell className="align-top">
                    <code className="text-[11px] leading-snug bg-muted/60 px-2 py-1 rounded-md block break-all">
                      {row.type}
                    </code>
                  </TableCell>
                  <TableCell className="align-top max-w-[160px]">
                    <div className="flex flex-col gap-0.5">
                      <span className="font-medium text-sm truncate" title={row.user?.name ?? ""}>
                        {row.user?.name ?? "—"}
                      </span>
                      <span className="text-xs text-muted-foreground truncate" title={row.user?.email ?? ""}>
                        {row.user?.email ?? row.userId ?? "—"}
                      </span>
                    </div>
                  </TableCell>
                  <TableCell className="align-top max-w-[180px]">
                    <span className="text-sm truncate block" title={row.email ?? ""}>
                      {row.email ?? "—"}
                    </span>
                  </TableCell>
                  <TableCell className="align-top">
                    <code className="text-xs bg-muted/60 px-2 py-0.5 rounded-md whitespace-nowrap">
                      {row.ipAddress ?? "—"}
                    </code>
                  </TableCell>
                  <TableCell className="align-top max-w-[140px]">
                    <span
                      className="text-xs font-mono truncate block"
                      title={row.deviceToken ?? ""}
                    >
                      {row.deviceToken ? row.deviceToken : "—"}
                    </span>
                  </TableCell>
                  <TableCell className="align-top">
                    <code className="text-[11px] bg-muted/60 px-1.5 py-0.5 rounded">
                      {row.deviceMac ?? "—"}
                    </code>
                  </TableCell>
                  <TableCell className="align-top max-w-[200px]">
                    {row.location ? (
                      <span
                        className="flex items-start gap-1.5 text-xs text-muted-foreground"
                        title={row.location}
                      >
                        <MapPin className="size-3.5 shrink-0 mt-0.5 text-muted-foreground/70" />
                        <span className="line-clamp-2 leading-snug">{row.location}</span>
                      </span>
                    ) : (
                      <span className="text-xs text-muted-foreground/60">—</span>
                    )}
                  </TableCell>
                  <TableCell className="align-top max-w-[200px]">
                    <span
                      className="text-xs text-muted-foreground line-clamp-2"
                      title={row.userAgent ?? ""}
                    >
                      {row.userAgent ?? "—"}
                    </span>
                  </TableCell>
                  <TableCell className="align-top max-w-[220px]">
                    <span
                      className="text-[11px] font-mono text-muted-foreground break-all"
                      title={
                        typeof row.metadata === "object" && row.metadata !== null
                          ? JSON.stringify(row.metadata)
                          : ""
                      }
                    >
                      {formatMetadata(row.metadata)}
                    </span>
                  </TableCell>
                </TableRow>
              ))
            )}
          </TableBody>
        </Table>
      </div>

      {totalPages > 1 && (
        <div className="flex items-center justify-center gap-4">
          <Button
            type="button"
            variant="outline"
            size="sm"
            disabled={page <= 1}
            onClick={() => setPage((p) => Math.max(1, p - 1))}
          >
            <ChevronLeft className="size-4" />
          </Button>
          <span className="text-sm text-muted-foreground tabular-nums">
            Page {page} of {totalPages}
          </span>
          <Button
            type="button"
            variant="outline"
            size="sm"
            disabled={page >= totalPages}
            onClick={() => setPage((p) => Math.min(totalPages, p + 1))}
          >
            <ChevronRight className="size-4" />
          </Button>
        </div>
      )}
    </div>
  );
}
