"use client";

import { useState } from "react";
import { useRouter } from "next/navigation";
import { Badge, Button, Card, ErrorBanner, Field, Input, Modal, PageHeader, Select } from "@/components/ui";
import { apiFetch, ApiClientError } from "@/lib/client-api";

interface UserRow {
  id: string;
  role: string;
  name: string;
  email: string | null;
  active: boolean;
  lastLoginAt: string | null;
  createdAt: string;
}

export default function UsersClient({ initial }: { initial: UserRow[] }) {
  const router = useRouter();
  const [open, setOpen] = useState(false);
  const [editOpen, setEditOpen] = useState<UserRow | null>(null);

  return (
    <div className="mx-auto max-w-5xl px-4 py-8">
      <PageHeader
        title="Users"
        description="Admins manage themselves and their operators here."
        actions={<Button onClick={() => setOpen(true)}>New user</Button>}
      />

      <Card>
        <table className="w-full text-sm">
          <thead className="bg-slate-50 text-left text-slate-600 border-b border-slate-200">
            <tr>
              <th className="px-4 py-2 font-medium">Name</th>
              <th className="px-4 py-2 font-medium">Role</th>
              <th className="px-4 py-2 font-medium">Email</th>
              <th className="px-4 py-2 font-medium">Last login</th>
              <th className="px-4 py-2 font-medium">Status</th>
              <th className="px-4 py-2"></th>
            </tr>
          </thead>
          <tbody>
            {initial.map((u) => (
              <tr key={u.id} className="border-b border-slate-100 last:border-0">
                <td className="px-4 py-3 font-medium">{u.name}</td>
                <td className="px-4 py-3">
                  <Badge tone={u.role === "admin" ? "blue" : "slate"}>{u.role}</Badge>
                </td>
                <td className="px-4 py-3 text-slate-600">{u.email ?? "—"}</td>
                <td className="px-4 py-3 text-slate-600">
                  {u.lastLoginAt ? new Date(u.lastLoginAt).toLocaleString() : "—"}
                </td>
                <td className="px-4 py-3">
                  <Badge tone={u.active ? "green" : "amber"}>{u.active ? "active" : "inactive"}</Badge>
                </td>
                <td className="px-4 py-3 text-right">
                  <Button variant="ghost" size="sm" onClick={() => setEditOpen(u)}>
                    Edit
                  </Button>
                </td>
              </tr>
            ))}
            {initial.length === 0 && (
              <tr>
                <td colSpan={6} className="px-4 py-10 text-center text-slate-500">
                  No users yet.
                </td>
              </tr>
            )}
          </tbody>
        </table>
      </Card>

      {open && <NewUserModal onClose={() => setOpen(false)} onSaved={() => router.refresh()} />}
      {editOpen && (
        <EditUserModal
          user={editOpen}
          onClose={() => setEditOpen(null)}
          onSaved={() => router.refresh()}
        />
      )}
    </div>
  );
}

function NewUserModal({ onClose, onSaved }: { onClose: () => void; onSaved: () => void }) {
  const [role, setRole] = useState<"admin" | "operator">("operator");
  const [name, setName] = useState("");
  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");
  const [pin, setPin] = useState("");
  const [busy, setBusy] = useState(false);
  const [error, setError] = useState<string | null>(null);

  async function submit(e: React.FormEvent) {
    e.preventDefault();
    setBusy(true);
    setError(null);
    try {
      const body = role === "admin" ? { role, name, email, password } : { role, name, pin };
      await apiFetch("/api/v1/users", { method: "POST", body: JSON.stringify(body) });
      onSaved();
      onClose();
    } catch (err) {
      setError(err instanceof ApiClientError ? err.message : "Failed to create user");
    } finally {
      setBusy(false);
    }
  }

  return (
    <Modal
      open
      onClose={onClose}
      title="New user"
      footer={
        <>
          <Button variant="secondary" onClick={onClose} disabled={busy}>
            Cancel
          </Button>
          <Button type="submit" form="new-user-form" disabled={busy}>
            {busy ? "Creating…" : "Create"}
          </Button>
        </>
      }
    >
      <form id="new-user-form" onSubmit={submit} className="space-y-4">
        <Field label="Role" required>
          <Select value={role} onChange={(e) => setRole(e.target.value as "admin" | "operator")}>
            <option value="operator">Operator</option>
            <option value="admin">Admin</option>
          </Select>
        </Field>
        <Field label="Name" required>
          <Input value={name} onChange={(e) => setName(e.target.value)} required maxLength={200} />
        </Field>
        {role === "admin" ? (
          <>
            <Field label="Email" required>
              <Input type="email" value={email} onChange={(e) => setEmail(e.target.value)} required />
            </Field>
            <Field label="Password" required hint="At least 8 characters.">
              <Input
                type="password"
                value={password}
                onChange={(e) => setPassword(e.target.value)}
                minLength={8}
                required
              />
            </Field>
          </>
        ) : (
          <Field label="PIN" required hint="Exactly 4 digits. Share this with the operator.">
            <Input
              inputMode="numeric"
              pattern="\d{4}"
              maxLength={4}
              value={pin}
              onChange={(e) => setPin(e.target.value.replace(/\D/g, ""))}
              required
            />
          </Field>
        )}
        <ErrorBanner message={error} />
      </form>
    </Modal>
  );
}

function EditUserModal({
  user,
  onClose,
  onSaved,
}: {
  user: UserRow;
  onClose: () => void;
  onSaved: () => void;
}) {
  const [name, setName] = useState(user.name);
  const [email, setEmail] = useState(user.email ?? "");
  const [password, setPassword] = useState("");
  const [pin, setPin] = useState("");
  const [active, setActive] = useState(user.active);
  const [busy, setBusy] = useState(false);
  const [error, setError] = useState<string | null>(null);

  async function submit(e: React.FormEvent) {
    e.preventDefault();
    setBusy(true);
    setError(null);
    const body: Record<string, unknown> = {};
    if (name !== user.name) body.name = name;
    if (active !== user.active) body.active = active;
    if (user.role === "admin") {
      if (email && email !== user.email) body.email = email;
      if (password) body.password = password;
    } else {
      if (pin) body.pin = pin;
    }
    try {
      if (Object.keys(body).length > 0) {
        await apiFetch(`/api/v1/users/${user.id}`, { method: "PATCH", body: JSON.stringify(body) });
      }
      onSaved();
      onClose();
    } catch (err) {
      setError(err instanceof ApiClientError ? err.message : "Failed to update user");
    } finally {
      setBusy(false);
    }
  }

  async function deactivate() {
    if (!confirm(`Deactivate ${user.name}? Their sessions will be revoked immediately.`)) return;
    setBusy(true);
    setError(null);
    try {
      await apiFetch(`/api/v1/users/${user.id}`, { method: "DELETE" });
      onSaved();
      onClose();
    } catch (err) {
      setError(err instanceof ApiClientError ? err.message : "Failed to deactivate");
      setBusy(false);
    }
  }

  return (
    <Modal
      open
      onClose={onClose}
      title={`Edit ${user.name}`}
      footer={
        <>
          {user.active && (
            <Button variant="danger" size="sm" onClick={deactivate} disabled={busy}>
              Deactivate
            </Button>
          )}
          <div className="flex-1" />
          <Button variant="secondary" onClick={onClose} disabled={busy}>
            Cancel
          </Button>
          <Button type="submit" form="edit-user-form" disabled={busy}>
            {busy ? "Saving…" : "Save"}
          </Button>
        </>
      }
    >
      <form id="edit-user-form" onSubmit={submit} className="space-y-4">
        <Field label="Name">
          <Input value={name} onChange={(e) => setName(e.target.value)} />
        </Field>
        {user.role === "admin" ? (
          <>
            <Field label="Email">
              <Input type="email" value={email} onChange={(e) => setEmail(e.target.value)} />
            </Field>
            <Field label="New password" hint="Leave blank to keep current password.">
              <Input
                type="password"
                value={password}
                onChange={(e) => setPassword(e.target.value)}
                minLength={password.length > 0 ? 8 : undefined}
              />
            </Field>
          </>
        ) : (
          <Field label="New PIN" hint="Leave blank to keep current PIN. Exactly 4 digits.">
            <Input
              inputMode="numeric"
              pattern="\d{4}"
              maxLength={4}
              value={pin}
              onChange={(e) => setPin(e.target.value.replace(/\D/g, ""))}
            />
          </Field>
        )}
        <label className="flex items-center gap-2 text-sm">
          <input type="checkbox" checked={active} onChange={(e) => setActive(e.target.checked)} />
          <span>Active</span>
        </label>
        <ErrorBanner message={error} />
      </form>
    </Modal>
  );
}
