import React from "react";
import "./editUser.scss";

// Union type for form field names
export type EditUserField =
  | "firstName"
  | "lastName"
  | "email"
  | "role"
  | "phone";

interface IEditUserForm {
  firstName: string;
  lastName: string;
  email: string;
  role: string;
  phone: string;
}

const EditUser = () => {
  const [form, setForm] = React.useState<IEditUserForm>({
    firstName: "",
    lastName: "",
    email: "",
    role: "",
    phone: "",
  });

  const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const name = e.target.name as EditUserField;
    const value = e.target.value;
    if (name === "phone") {
      const filtered = value.replace(/[^0-9+\-\s()]/g, "");
      setForm((prev) => ({
        ...prev,
        phone: filtered,
      }));
    } else {
      setForm((prev) => ({
        ...prev,
        [name]: value,
      }));
    }
  };

  const handleResetForm = () => {
    setForm({
      firstName: "",
      lastName: "",
      email: "",
      role: "",
      phone: "",
    });
  };

  return (
    <form className="edit-user">
      <input
        type="text"
        placeholder="First Name"
        name="firstName"
        value={form.firstName}
        onChange={handleChange}
      />
      <input
        type="text"
        placeholder="Last Name"
        name="lastName"
        value={form.lastName}
        onChange={handleChange}
      />
      <input
        type="email"
        placeholder="Email"
        name="email"
        value={form.email}
        onChange={handleChange}
      />
      <input
        type="text"
        placeholder="Role"
        name="role"
        value={form.role}
        onChange={handleChange}
      />
      <input
        type="tel"
        placeholder="Phone"
        name="phone"
        value={form.phone}
        maxLength={15}
        pattern="[0-9+\-\s()]*"
        onChange={handleChange}
        inputMode="tel"
        autoComplete="tel"
      />
      <div className="edit-user__button-container">
        <button type="submit">Save</button>
        <button type="button" onClick={handleResetForm}>
          Clear
        </button>
      </div>
    </form>
  );
};

export default EditUser;
