"use client";

import { useState } from "react";
import { useLocaleStore } from "@/store/uiStore";
import { t } from "@/lib/locale";

type UserCreateFormValues = {
  username: string;
  password?: string;
  ldapDn?: string;
  enabled?: boolean;
  roleCodes: string[];
};

export default function UserCreateForm({
  disabled,
  onSubmit,
  authMode
}: {
  disabled: boolean;
  authMode: string;
  onSubmit: (payload: UserCreateFormValues) => Promise<void>;
}) {
  const [username, setUsername] = useState("");
  const [password, setPassword] = useState("");
  const [ldapDn, setLdapDn] = useState("");
  const [roleCodesInput, setRoleCodesInput] = useState("");
  const [enabled, setEnabled] = useState(true);
  const [loading, setLoading] = useState(false);
  const locale = useLocaleStore((s) => s.locale);
  const isLdap = authMode.toUpperCase() === "LDAP";

  const submit = async () => {
    if (disabled || !username || (!isLdap && !password)) return;
    setLoading(true);
    try {
      await onSubmit({
        username: username.trim(),
        password: isLdap ? undefined : password.trim(),
        ldapDn: isLdap && ldapDn.trim() ? ldapDn.trim() : undefined,
        enabled,
        roleCodes: roleCodesInput
          .split(",")
          .map((s) => s.trim())
          .filter(Boolean)
      });
      setUsername("");
      setPassword("");
      setLdapDn("");
      setRoleCodesInput("");
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="vstack gap-2">
      <input
        className="form-control"
        value={username}
        onChange={(e) => setUsername(e.target.value)}
        placeholder={t("username", locale)}
        disabled={disabled}
      />
      {!isLdap && (
        <input
          className="form-control"
          type="password"
          value={password}
          onChange={(e) => setPassword(e.target.value)}
          placeholder={t("password", locale)}
          disabled={disabled}
        />
      )}
      {isLdap && (
        <input
          className="form-control"
          value={ldapDn}
          onChange={(e) => setLdapDn(e.target.value)}
          placeholder="ldapDn"
          disabled={disabled}
        />
      )}
      <input
        className="form-control"
        value={roleCodesInput}
        onChange={(e) => setRoleCodesInput(e.target.value)}
        placeholder="roleCodes (comma separated)"
        disabled={disabled}
      />
      <label className="d-flex align-items-center gap-2">
        <input
          type="checkbox"
          checked={enabled}
          onChange={(e) => setEnabled(e.target.checked)}
          disabled={disabled}
        />
        {t("enabled", locale)}
      </label>
      <button className="btn btn-primary" type="button" onClick={submit} disabled={disabled || loading}>
        {loading ? t("submitting", locale) : t("create", locale)}
      </button>
    </div>
  );
}
