"use client";

import { useState } from "react";
import { Button, Card } from "@/components/ui";
import { Field, inputClass } from "@/components/ui/form";
import { createUserAction, resetUserPasswordAction, revokeUserSessionsAction, setUserStatusAction, unlockUserAction } from "@/lib/actions/platform";
import { StatusLine, useRun } from "./use-run";

export function NewUser() {
  const { pending, msg, errors, run } = useRun();
  const [v, setV] = useState({ name: "", email: "", password: "" });
  const set = (p: Partial<typeof v>) => setV((x) => ({ ...x, ...p }));
  return (
    <Card className="mb-4 space-y-3 p-4">
      <h2 className="text-sm font-semibold">New account</h2>
      <p className="text-sm text-muted-foreground">Choose a strong initial password and share it through a secure channel. The person should change it under My profile after the first sign-in. Access to websites is granted separately.</p>
      <div className="grid gap-3 sm:grid-cols-3">
        <Field id="nu-name" label="Name" error={errors.name}><input id="nu-name" className={inputClass} maxLength={120} value={v.name} onChange={(e) => set({ name: e.target.value })} /></Field>
        <Field id="nu-email" label="Email" error={errors.email}><input id="nu-email" type="email" autoComplete="off" className={inputClass} value={v.email} onChange={(e) => set({ email: e.target.value })} /></Field>
        <Field id="nu-pw" label="Initial password" help="At least 12 characters" error={errors.password}><input id="nu-pw" type="password" autoComplete="new-password" className={inputClass} value={v.password} onChange={(e) => set({ password: e.target.value })} /></Field>
      </div>
      <Button disabled={pending || !v.name || !v.email || !v.password} onClick={() => run(() => createUserAction(v), () => setV({ name: "", email: "", password: "" }))}>Create account</Button>
      <StatusLine msg={msg} />
    </Card>
  );
}

export function UserActions({ userId, name, status, locked, self }: { userId: string; name: string; status: string; locked: boolean; self: boolean }) {
  const { pending, msg, errors, run } = useRun();
  const [reset, setReset] = useState(false);
  const [pw, setPw] = useState("");
  if (self) return <span className="text-xs text-muted-foreground">This is you</span>;
  return (
    <div className="space-y-2">
      <div className="flex flex-wrap gap-1">
        {status === "ACTIVE" ? (
          <Button variant="secondary" disabled={pending} aria-label={`Suspend ${name}`} onClick={() => run(() => setUserStatusAction(userId, "SUSPENDED"))}>Suspend</Button>
        ) : (
          <Button variant="secondary" disabled={pending} aria-label={`Reactivate ${name}`} onClick={() => run(() => setUserStatusAction(userId, "ACTIVE"))}>Reactivate</Button>
        )}
        {locked ? <Button variant="secondary" disabled={pending} aria-label={`Unlock ${name}`} onClick={() => run(() => unlockUserAction(userId))}>Unlock</Button> : null}
        <Button variant="ghost" disabled={pending} aria-label={`Sign ${name} out everywhere`} onClick={() => run(() => revokeUserSessionsAction(userId))}>Sign out</Button>
        <Button variant="ghost" disabled={pending} aria-label={`Reset password for ${name}`} onClick={() => setReset((r) => !r)}>Reset password</Button>
      </div>
      {reset ? (
        <div className="flex items-end gap-2">
          <Field id={`rp-${userId}`} label={`New password for ${name}`} error={errors.password} className="flex-1"><input id={`rp-${userId}`} type="password" autoComplete="new-password" className={inputClass} value={pw} onChange={(e) => setPw(e.target.value)} /></Field>
          <Button variant="danger" disabled={pending || pw.length < 12} onClick={() => run(() => resetUserPasswordAction(userId, { password: pw }), () => { setPw(""); setReset(false); })}>Set</Button>
        </div>
      ) : null}
      <StatusLine msg={msg} />
    </div>
  );
}
