"use client";

import { useState } from "react";
import { useRouter } from "next/navigation";
import { Avatar } from "@/components/ui/Avatar";
import { Icon } from "@/components/ui/Icon";
import { confirmDialog, alertDialog } from "@/components/ui/Dialog";
import {
  createUserAction,
  updateUserAction,
  setUserRolesAction,
  setUserBlockedAction,
  resetUserPasswordAction,
  deleteUserAction,
} from "@/lib/admin/actions";
import type { AdminUser } from "@/lib/admin/queries";

type Role = { id: string; name: string };

const STATUS_LABEL: Record<string, string> = {
  ACTIVE: "Aktiv",
  INVITED: "Eingeladen",
  SUSPENDED: "Gesperrt",
};
const statusLabel = (s: string) => STATUS_LABEL[s] ?? s;

export function UsersManager({ users, roles }: { users: AdminUser[]; roles: Role[] }) {
  const router = useRouter();
  const [editing, setEditing] = useState<AdminUser | "new" | null>(null);
  const people = users.map((u) => ({ id: u.id, name: u.name }));

  const showPassword = async (email: string, password: string) => {
    await alertDialog({
      title: "Zugangsdaten erstellt",
      message: `${email}\nPasswort: ${password}\n\nDie Willkommens-E-Mail wurde versendet (bzw. bei fehlendem SMTP in der Server-Konsole ausgegeben).`,
      confirmLabel: "Verstanden",
    });
  };

  const onReset = async (u: AdminUser) => {
    if (!(await confirmDialog({ title: "Passwort zurücksetzen?", message: `Für ${u.name} wird ein neues Passwort generiert und per E-Mail gesendet.`, confirmLabel: "Zurücksetzen" }))) return;
    const res = await resetUserPasswordAction(u.id);
    if (res.error) await alertDialog({ title: "Fehler", message: res.error, danger: true });
    else if (res.password) await showPassword(u.email, res.password);
  };

  const onBlock = async (u: AdminUser) => {
    const blocked = u.status !== "SUSPENDED";
    if (blocked && !(await confirmDialog({ title: "Nutzer sperren?", message: `${u.name} kann sich danach nicht mehr anmelden.`, confirmLabel: "Sperren", danger: true }))) return;
    const res = await setUserBlockedAction(u.id, blocked);
    if (res.error) await alertDialog({ title: "Nicht möglich", message: res.error, danger: true });
    else router.refresh();
  };

  const onDelete = async (u: AdminUser) => {
    if (!(await confirmDialog({ title: "Nutzer löschen?", message: `${u.name} (${u.email}) wird dauerhaft entfernt.`, danger: true }))) return;
    const res = await deleteUserAction(u.id);
    if (res.error) await alertDialog({ title: "Nicht möglich", message: res.error, danger: true });
    else router.refresh();
  };

  return (
    <>
      <section className="card" data-reveal>
        <div className="mb-4 flex items-center justify-between">
          <div>
            <h2>Nutzer &amp; Team</h2>
            <p className="text-muted text-xs mt-0.5">{users.length} Konten · Rollen, Vorgesetzte &amp; Urlaubstage</p>
          </div>
          <button className="btn btn-primary btn-sm" onClick={() => setEditing("new")}>
            <Icon name="plus" size={15} /> Nutzer anlegen
          </button>
        </div>

        <div className="table-wrap">
          <table className="data">
            <thead>
              <tr>
                <th>Name</th>
                <th>Rollen</th>
                <th>Vorgesetzte(r)</th>
                <th>Urlaub</th>
                <th>Status</th>
                <th className="col-actions">Aktionen</th>
              </tr>
            </thead>
            <tbody>
              {users.map((u) => (
                <tr key={u.id}>
                  <td>
                    <div className="flex items-center gap-2.5">
                      <Avatar name={u.name} src={u.avatarUrl} size={32} />
                      <div className="min-w-0">
                        <div className="font-bold">{u.name}</div>
                        <div className="text-muted text-xs">{u.email}</div>
                      </div>
                    </div>
                  </td>
                  <td>
                    <div className="flex flex-wrap gap-1">
                      {u.roleNames.length ? u.roleNames.map((r, i) => <span key={i} className="badge">{r}</span>) : <span className="text-muted text-xs">—</span>}
                    </div>
                  </td>
                  <td className="text-muted text-sm">{u.supervisorName ?? "—"}</td>
                  <td className="text-sm font-bold">{u.vacationDaysPerYear} T.</td>
                  <td>
                    <span className="status-badge" data-status={u.status}>
                      <span className="status-badge-dot" />
                      {statusLabel(u.status)}
                    </span>
                  </td>
                  <td className="col-actions">
                    <div className="row-actions">
                      <button className="icon-btn" style={{ width: 30, height: 30 }} title="Bearbeiten" onClick={() => setEditing(u)}>
                        <Icon name="edit" size={15} />
                      </button>
                      <button className="icon-btn" style={{ width: 30, height: 30 }} title="Passwort zurücksetzen" onClick={() => onReset(u)}>
                        <Icon name="key" size={15} />
                      </button>
                      <button className="icon-btn" style={{ width: 30, height: 30 }} title={u.status === "SUSPENDED" ? "Entsperren" : "Sperren"} onClick={() => onBlock(u)}>
                        <Icon name={u.status === "SUSPENDED" ? "check" : "lock"} size={15} />
                      </button>
                      <button className="icon-btn" style={{ width: 30, height: 30 }} title="Löschen" onClick={() => onDelete(u)}>
                        <Icon name="trash" size={15} />
                      </button>
                    </div>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </section>

      {editing ? (
        <UserDrawer
          user={editing === "new" ? null : editing}
          roles={roles}
          people={people}
          onClose={() => setEditing(null)}
          onCreated={showPassword}
        />
      ) : null}
    </>
  );
}

function UserDrawer({
  user,
  roles,
  people,
  onClose,
  onCreated,
}: {
  user: AdminUser | null;
  roles: Role[];
  people: { id: string; name: string }[];
  onClose: () => void;
  onCreated: (email: string, password: string) => Promise<void>;
}) {
  const router = useRouter();
  const isNew = !user;
  const [name, setName] = useState(user?.name ?? "");
  const [email, setEmail] = useState(user?.email ?? "");
  const [jobTitle, setJobTitle] = useState(user?.jobTitle ?? "");
  const [roleIds, setRoleIds] = useState<string[]>(user?.roleIds ?? []);
  const [supervisorId, setSupervisorId] = useState(user?.supervisorId ?? "");
  const [vacationDays, setVacationDays] = useState(user?.vacationDaysPerYear ?? 30);
  const [saving, setSaving] = useState(false);
  const [error, setError] = useState<string | null>(null);

  const toggleRole = (id: string) =>
    setRoleIds((r) => (r.includes(id) ? r.filter((x) => x !== id) : [...r, id]));

  const save = async () => {
    setSaving(true);
    setError(null);
    if (isNew) {
      const res = await createUserAction({ name, email, jobTitle, roleIds, supervisorId: supervisorId || null, vacationDaysPerYear: vacationDays });
      setSaving(false);
      if (res.error) return setError(res.error);
      onClose();
      if (res.password) await onCreated(email.trim().toLowerCase(), res.password);
      router.refresh();
    } else {
      const res = await updateUserAction(user!.id, { name, email, jobTitle, supervisorId: supervisorId || null, vacationDaysPerYear: vacationDays });
      if (!res.error) await setUserRolesAction(user!.id, roleIds);
      setSaving(false);
      if (res.error) return setError(res.error);
      onClose();
      router.refresh();
    }
  };

  return (
    <div className="drawer-overlay" onMouseDown={(e) => e.target === e.currentTarget && onClose()}>
      <div className="drawer animate-in">
        <div className="mb-5 flex items-center justify-between">
          <span className="eyebrow">{isNew ? "Neuer Nutzer" : "Nutzer bearbeiten"}</span>
          <button className="btn btn-ghost btn-sm" onClick={onClose} aria-label="Schließen">
            <Icon name="close" size={16} />
          </button>
        </div>

        {error ? <p className="field-error mb-3">{error}</p> : null}

        <div className="flex flex-col gap-4">
          <div className="field">
            <label className="label">Name</label>
            <input className="input" value={name} onChange={(e) => setName(e.target.value)} placeholder="Vor- und Nachname" />
          </div>
          <div className="field">
            <label className="label">E-Mail</label>
            <input className="input" value={email} onChange={(e) => setEmail(e.target.value)} placeholder="name@avaria.media" />
          </div>
          <div className="field">
            <label className="label">Position (optional)</label>
            <input className="input" value={jobTitle} onChange={(e) => setJobTitle(e.target.value)} placeholder="z. B. Content Operations" />
          </div>

          <div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
            <div className="field">
              <label className="label">Vorgesetzte(r) / Chef</label>
              <select className="select" value={supervisorId} onChange={(e) => setSupervisorId(e.target.value)}>
                <option value="">— Keine(r) —</option>
                {people.filter((p) => p.id !== user?.id).map((p) => (
                  <option key={p.id} value={p.id}>{p.name}</option>
                ))}
              </select>
            </div>
            <div className="field">
              <label className="label">Urlaubstage / Jahr</label>
              <input type="number" min={0} max={365} className="input" value={vacationDays} onChange={(e) => setVacationDays(Number(e.target.value))} />
            </div>
          </div>

          {!isNew ? (
            <div className="field">
              <label className="label">Status (automatisch)</label>
              <span className="status-badge" data-status={user!.status}>
                <span className="status-badge-dot" />
                {statusLabel(user!.status)}
              </span>
            </div>
          ) : null}

          <div className="field">
            <label className="label">Rollen</label>
            <div className="flex flex-wrap gap-2">
              {roles.map((r) => (
                <button key={r.id} type="button" className="pill" data-active={roleIds.includes(r.id)} onClick={() => toggleRole(r.id)}>
                  {r.name}
                  {roleIds.includes(r.id) ? <Icon name="check" size={13} /> : null}
                </button>
              ))}
            </div>
          </div>

          {isNew ? (
            <p className="text-muted text-xs">
              Ein Passwort wird automatisch erzeugt und dem Nutzer per Willkommens-E-Mail gesendet.
            </p>
          ) : null}
        </div>

        <div className="form-footer">
          <span />
          <div className="flex items-center gap-2">
            <button className="btn btn-ghost" onClick={onClose} disabled={saving}>Abbrechen</button>
            <button className="btn btn-primary" onClick={save} disabled={saving || !name.trim() || !email.trim()}>
              {saving ? "Speichern …" : isNew ? "Anlegen & E-Mail senden" : "Speichern"}
            </button>
          </div>
        </div>
      </div>
    </div>
  );
}
