import React from "react";
import { useRouter } from "next/navigation";
import { IEditUserForm, EditUserField } from "../User.interfaces";
import { editUser } from "@/services/roles.services";
import { IUser } from "../../Pages/Admin/Users/interfaces";
import "./EditUser.scss";

const EditUser = ({ user }: { user: IUser }) => {
  const router = useRouter();
  const { username, last_name, email, groups, phone } = user;
  const [form, setForm] = React.useState<IEditUserForm>({
    firstName: username || "",
    lastName: last_name || "",
    email: email || "",
    role: roles[0] || "",
    phone: phone || "",
    groups: groups || [],
    merchants: merchants || [],
    jobTitle: jobTitle || "",
    username: username || "",
  });

  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: "",
      groups: [],
      merchants: [],
      jobTitle: "",
      username: "",
    });
  };

  const handleSubmit = async (e: React.FormEvent<HTMLFormElement>) => {
    e.preventDefault();

    try {
      await editUser(user.id, form);
      router.refresh(); // <- refreshes the page (SSR re-runs)
      // eslint-disable-next-line @typescript-eslint/no-explicit-any
    } catch (err: any) {
      console.log(err.message || "Error creating role");
      // setError(err.message || "Error creating role");
    }
  };

  return (
    <form className="edit-user" onSubmit={handleSubmit}>
      <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;
