import React, { useState, useEffect } from "react";
import { createUser, getAllRole } from "@/services/userService";
import { toast } from "react-toastify";
import useNavigate from "@/hooks/useNavigate";
import Layout from "../../Layout";
import CustomSelect from "../../components/common/CustomSelect";
import Link from "next/link";

export default function AddNewUser() {
  const navigate = useNavigate();
  const [loading, setLoading] = useState(false);
  const [roleLoading, setRoleLoading] = useState(true);
  const [roles, setRoles] = useState([]);
  const [errors, setErrors] = useState({});

  const [formData, setFormData] = useState({
    full_name: "",
    phone_number: "",
    email: "",
    organization_name: "",
    address: "",
    role_id: "",
    password: "",
    status: "available",
  });

  // Load all roles from API
  useEffect(() => {
    async function fetchRoles() {
      try {
        setRoleLoading(true);

        const res = await getAllRole();

        const formattedRoles =
          res.data?.map((r) => ({
            value: r.id.toString(),
            label: r.name,
          })) || [];

        setRoles(formattedRoles);
      } catch (err) {
        console.error("Failed to load roles", err);
        toast.error("Failed to load roles");
      } finally {
        setRoleLoading(false);
      }
    }
    fetchRoles();
  }, []);

  // const handleChange = (e) => {
  //   const { name, value } = e.target;
  //   setFormData((prev) => ({ ...prev, [name]: value }));
  // };

  const handleChange = (e) => {
    const { name, value } = e.target;

    if (name === "full_name") {
      const regex = /^[A-Za-z\s.'-]*$/;

      if (!regex.test(value)) {
        return;
      }
    }

    const formattedValue =
      name === "phone_number" ? formatUSPhone(value) : value;

    setFormData((prev) => ({
      ...prev,
      [name]: formattedValue,
    }));

    setErrors((prev) => ({
      ...prev,
      [name]: validateField(name, formattedValue),
    }));
  };

  const toUSPhoneE164 = (value) => {
    const digits = value.replace(/\D/g, "").slice(0, 10);
    if (digits.length !== 10) return "";

    return `${digits}`;
  };

  const handleSubmit = async (e) => {
    e.preventDefault();
    const validationErrors = {
      full_name: validateField("full_name", formData.full_name),
      email: validateField("email", formData.email),
      phone_number: validateField("phone_number", formData.phone_number),
      password: validateField("password", formData.password),
    };

    setErrors(validationErrors);

    if (Object.values(validationErrors).some(Boolean)) {
      return;
    }
    if (loading) return;

    if (!formData.full_name || !formData.email) {
      toast.warn("Full name and email are required!");
      return;
    }

    try {
      setLoading(true);
      const payload = {
        email: formData.email,
        password: formData.password,
        details: {
          full_name: formData.full_name,
          phone_number: toUSPhoneE164(formData.phone_number),
          organization_name: formData.organization_name,
          address: formData.address,
          status: formData.status,
        },
        roles: [parseInt(formData.role_id) || 1],
      };

      await createUser(payload);
      toast.success("User created successfully!");
      navigate("/user-management");
    } catch (err) {
      console.error("User creation failed:", err);
      if (err.response?.data) {
        const errors = err.response.data;
        const firstMessage = Object.values(errors)?.[0]?.[0];
        toast.error(firstMessage || "Failed to create user");
      } else {
        toast.error("Failed to create user");
      }
    } finally {
      setLoading(false);
    }
  };

  const validateField = (name, value) => {
    switch (name) {
      case "full_name":
        if (!value.trim()) return "Full name is required";

        return /^[A-Za-z\s.'-]+$/.test(value)
          ? ""
          : "Name can contain only letters";

      case "email":
        if (!value) return "Email is required";

        return /^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}$/.test(value)
          ? ""
          : "Please enter a valid email address";

      case "phone_number":
        if (!value) return "";

        return /^\(\d{3}\)\s\d{3}-\d{4}$/.test(value)
          ? ""
          : "Please enter a valid US phone number";

      case "password":
        if (!value) return "Password is required";

        return /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?#&^()_\-+=])[A-Za-z\d@$!%*?#&^()_\-+=]{8,}$/.test(
          value,
        )
          ? ""
          : "Minimum 8 chars with uppercase, lowercase, number & special character";

      default:
        return "";
    }
  };

  const formatUSPhone = (value) => {
    const digits = value.replace(/\D/g, "").slice(0, 10);

    if (digits.length <= 3) return digits;

    if (digits.length <= 6) {
      return `(${digits.slice(0, 3)}) ${digits.slice(3)}`;
    }

    return `(${digits.slice(0, 3)}) ${digits.slice(
      3,
      6,
    )}-${digits.slice(6, 10)}`;
  };

  const handleBlur = (e) => {
    const { name, value } = e.target;

    setErrors((prev) => ({
      ...prev,
      [name]: validateField(name, value),
    }));
  };

  return (
    <Layout title="Add New Team Member">
      <div className="dshboardwhtepnel">
        <div className="pagerlink">
          <ul>
            <li>
              <Link href="/dashboard">Dashboard</Link>
            </li>
            <li>Add Team Member</li>
          </ul>
        </div>

        <form className="dshboardcaseform" onSubmit={handleSubmit}>
          <h3>Add New Team Member</h3>
          <div className="row">
            {/* Full Name */}
            <div className="col-lg-4 col-sm-6">
              <div className="datafrm">
                <label>
                  Full Name <span className="text-danger">*</span>
                </label>
                <input
                  type="text"
                  name="full_name"
                  value={formData.full_name}
                  onChange={handleChange}
                  onBlur={handleBlur}
                  placeholder="Enter full name"
                />

                {errors.full_name && (
                  <small className="text-danger d-block mt-1">
                    {errors.full_name}
                  </small>
                )}
              </div>
            </div>

            {/* Phone Number */}
            <div className="col-lg-4 col-sm-6">
              <div className="datafrm">
                <label>Phone Number</label>
                <input
                  type="text"
                  name="phone_number"
                  value={formData.phone_number}
                  onChange={handleChange}
                  onBlur={handleBlur}
                  placeholder="(123) 456-7890"
                />

                {errors.phone_number && (
                  <small className="text-danger d-block mt-1">
                    {errors.phone_number}
                  </small>
                )}
              </div>
            </div>

            {/* Email */}
            <div className="col-lg-4 col-sm-6">
              <div className="datafrm">
                <label>
                  E-mail Address <span className="text-danger">*</span>
                </label>
                <input
                  type="email"
                  name="email"
                  value={formData.email}
                  onChange={handleChange}
                  onBlur={handleBlur}
                  placeholder="Enter e-mail address"
                />

                {errors.email && (
                  <small className="text-danger d-block mt-1">
                    {errors.email}
                  </small>
                )}
              </div>
            </div>

            {/* Organization */}
            <div className="col-lg-4 col-sm-6">
              <div className="datafrm">
                <label>Organization Name</label>
                <input
                  type="text"
                  name="organization_name"
                  value={formData.organization_name}
                  onChange={handleChange}
                  placeholder="Enter organization name"
                />
              </div>
            </div>

            {/* Address */}
            <div className="col-lg-4 col-sm-6">
              <div className="datafrm">
                <label>Address</label>
                <input
                  type="text"
                  name="address"
                  value={formData.address}
                  onChange={handleChange}
                  placeholder="Enter address"
                />
              </div>
            </div>

            {/* User Role */}
            <div className="col-lg-4 col-sm-6">
              <div className="datafrm">
                <label>Select User Role</label>

                {roleLoading ? (
                  <p>Loading roles...</p>
                ) : (
                  <CustomSelect
                    name="role_id"
                    value={formData.role_id}
                    onChange={handleChange}
                    placeholder="Select user role"
                    options={roles}
                  />
                )}
              </div>
            </div>

            {/* Password */}
            <div className="col-lg-4 col-sm-6">
              <div className="datafrm">
                <label>
                  Password <span className="text-danger">*</span>
                </label>
                <input
                  type="password"
                  name="password"
                  value={formData.password}
                  onChange={handleChange}
                  onBlur={handleBlur}
                  placeholder="Enter password"
                />

                {errors.password && (
                  <small className="text-danger d-block mt-1">
                    {errors.password}
                  </small>
                )}
              </div>
            </div>
            <div className="col-lg-4 col-sm-6">
              <div className="datafrm">
                <label>Select Status</label>
                <CustomSelect
                  name="status"
                  value={formData.status}
                  onChange={handleChange}
                  placeholder="Select status"
                  options={[
                    {
                      value: "available",
                      label: "Available",
                    },
                    {
                      value: "busy",
                      label: "Busy",
                    },
                  ]}
                />
              </div>
            </div>

            {/* Buttons */}
            <div className="col-12">
              <div className="datafrmbtn">
                <ul>
                  <li>
                    <button
                      type="button"
                      className="canselbtn"
                      onClick={() => navigate("/user-management")}
                    >
                      Cancel
                    </button>
                  </li>
                  <li>
                    <button type="submit" disabled={loading}>
                      {loading ? "Creating..." : "Create User"}
                    </button>
                  </li>
                </ul>
              </div>
            </div>
          </div>
        </form>
      </div>

      <div className="notepnel">
        <h3>Important Notes:</h3>
        <ul>
          <li>
            Email addresses are used for system notifications and communications
          </li>
          <li>All user data is encrypted and stored securely</li>
          <li>Users will need to be assigned roles after creation</li>
        </ul>
      </div>
    </Layout>
  );
}
