"use client";

import * as React from "react";
import { useRouter } from "next/navigation";
import { toast } from "sonner";
import { KeyRound, LogOut, ShieldCheck, ShieldOff, Smartphone } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Card, CardHeader, CardContent } from "@/components/ui/card";
import { DescriptionList } from "@/components/ui/page-header";
import { useConfirm } from "@/components/ui/confirm";
import { SessionsList } from "./worker-controls";
import { revokeAllSessions } from "@/lib/actions/workers";
import { fmtDateTime, relativeTime } from "@/lib/dates";

/** Worker security card: sessions, devices, 2FA, password age, sign-out-all. */
export function WorkerSecurityPanel({ worker, sessions, canManage, timezone }: { worker: { id: string; twoFactorEnabled: boolean; passwordChangedAt: string | null; lastLoginAt: string | null; lastSeenAt: string | null; failedLogins7d: number; devices: string[] }; sessions: React.ComponentProps<typeof SessionsList>["sessions"]; canManage: boolean; timezone: string }) {
  const router = useRouter();
  const confirm = useConfirm();
  const [busy, setBusy] = React.useState(false);
  const live = sessions.filter((s) => !s.revokedAt);
  async function signOutAll() {
    const { ok, reason } = await confirm({ title: "Sign out of all devices?", description: `${live.length} active session${live.length === 1 ? "" : "s"} will be revoked. The worker must sign in again everywhere.`, destructive: true, requireReason: true, confirmLabel: "Sign out all" });
    if (!ok) return;
    setBusy(true);
    const r = await revokeAllSessions(worker.id, reason ?? undefined);
    setBusy(false);
    if (!r.ok) return toast.error(r.error);
    toast.success(`${r.data.count} session${r.data.count === 1 ? "" : "s"} revoked`);
    router.refresh();
  }
  const pwAge = worker.passwordChangedAt ? Math.round((Date.now() - new Date(worker.passwordChangedAt).getTime()) / 86_400_000) : null;
  return (
    <div className="grid gap-4 lg:grid-cols-3">
      <Card>
        <CardHeader title="Account security" />
        <CardContent>
          <DescriptionList
            cols={1}
            items={[
              { label: "Two-factor authentication", value: worker.twoFactorEnabled ? <span className="flex items-center gap-1.5 text-positive-600"><ShieldCheck className="size-4" /> Enabled</span> : <span className="flex items-center gap-1.5 text-warning-600"><ShieldOff className="size-4" /> Not enabled</span> },
              { label: "Password last changed", value: worker.passwordChangedAt ? <span className={pwAge != null && pwAge > 180 ? "text-warning-600" : ""}><KeyRound className="mr-1 inline size-3.5 text-fg-subtle" />{relativeTime(worker.passwordChangedAt)}{pwAge != null && pwAge > 180 ? " · consider a reset" : ""}</span> : "Unknown (never changed since creation)" },
              { label: "Last login", value: fmtDateTime(worker.lastLoginAt, timezone) },
              { label: "Last activity", value: fmtDateTime(worker.lastSeenAt, timezone) },
              { label: "Failed logins (7 days)", value: <span className={worker.failedLogins7d >= 3 ? "font-semibold text-negative-600" : ""}>{worker.failedLogins7d}</span> },
              { label: "Known devices", value: worker.devices.length ? <span className="flex flex-wrap gap-1">{worker.devices.map((d) => <span key={d} className="rounded-full bg-surface-2 px-2 py-0.5 text-2xs"><Smartphone className="mr-1 inline size-3" />{d}</span>)}</span> : "—" },
            ]}
          />
        </CardContent>
      </Card>
      <Card className="lg:col-span-2">
        <CardHeader
          title="Active sessions"
          description={`${live.length} device${live.length === 1 ? "" : "s"} signed in · real heartbeat-based presence`}
          action={
            canManage && live.length ? (
              <Button size="sm" variant="destructive" loading={busy} onClick={signOutAll}>
                <LogOut /> Sign out all devices
              </Button>
            ) : null
          }
        />
        <CardContent>
          <SessionsList sessions={sessions} canRevoke={canManage} />
        </CardContent>
      </Card>
    </div>
  );
}
