"use client";

import React, { useState } from "react";
import { useRouter } from "next/navigation";
import "./AddUser.scss";
import { addUser } from "@/services/roles.services";
import { IEditUserForm } from "../User.interfaces";

interface AddUserFormProps {
  onSuccess?: () => void;
}

const AddUserForm: React.FC<AddUserFormProps> = ({ onSuccess }) => {
  const router = useRouter();
  const [form, setForm] = useState<IEditUserForm>({
    firstName: "",
    lastName: "",
    email: "",
    phone: "",
    role: "",
  });

  const [error, setError] = useState("");
  const [loading, setLoading] = useState(false);

  const handleChange = (
    e: React.ChangeEvent<HTMLInputElement | HTMLSelectElement>
  ) => {
    const { name, value } = e.target;
    setForm((prev) => ({ ...prev, [name]: value }));
  };

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

    if (!form.firstName || !form.lastName || !form.email || !form.role) {
      setError("Please fill in all required fields.");
      return;
    }

    try {
      setLoading(true);
      setError("");

      await addUser(form);
      if (onSuccess) onSuccess();
      router.refresh(); // <- refreshes the page (SSR re-runs)
      // eslint-disable-next-line @typescript-eslint/no-explicit-any
    } catch (err: any) {
      setError(err.message || "Something went wrong.");
    } finally {
      setLoading(false);
    }
  };

  return (
    <form className="add-user" onSubmit={handleSubmit}>
      <input
        name="firstName"
        placeholder="First Name"
        value={form.firstName}
        onChange={handleChange}
        required
      />
      <input
        name="lastName"
        placeholder="Last Name"
        value={form.lastName}
        onChange={handleChange}
        required
      />
      <input
        name="email"
        type="email"
        placeholder="Email"
        value={form.email}
        onChange={handleChange}
        required
      />
      <input
        name="phone"
        placeholder="Phone (optional)"
        value={form.phone}
        onChange={handleChange}
      />
      <select
        name="role"
        value={form.role}
        onChange={handleChange}
        required
        className="add-user__select"
      >
        <option value="">Select Role</option>
        <option value="ROLE_IIN">ROLE_IIN</option>
        <option value="ROLE_RULES_ADMIN">ROLE_RULES_ADMIN</option>
        <option value="ROLE_FIRST_APPROVER">ROLE_FIRST_APPROVER</option>
      </select>

      {error && <div style={{ color: "red", width: "100%" }}>{error}</div>}

      <div className="add-user__button-container">
        <button type="submit" disabled={loading}>
          {loading ? "Adding..." : "Add User"}
        </button>
      </div>
    </form>
  );
};

export default AddUserForm;
