import CustomSelect from "@/components/common/CustomSelect";
import { createUserWithCase, getAllRole } from "@/services/userService";
import React, { useEffect, useState } from "react";
import { toast } from "react-toastify";

const AddTeamMemberModal = ({ show, onClose, caseId, onCreated }) => {
  const [loading, setLoading] = useState(false);
  const [roleLoading, setRoleLoading] = useState(true);
  const [roles, setRoles] = useState([]);

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

  useEffect(() => {
    if (!show) return;

    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();
  }, [show]);

  // Reset form whenever the modal is opened fresh
  useEffect(() => {
    if (show) {
      setFormData({
        full_name: "",
        phone_number: "",
        email: "",
        organization_name: "",
        address: "",
        role_id: "",
        password: "",
      });
      setErrors({
        full_name: "",
        email: "",
        phone_number: "",
        password: "",
      });
    }
  }, [show]);

  const formatUSPhone = (value) => {
    const digits = value.replace(/\D/g, "").slice(0, 10);
    if (digits.length === 0) return "";
    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)}`;
  };

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

  const validateField = (name, value) => {
    let error = "";

    if (name === "full_name") {
      if (!value || value.trim().length < 2) {
        error = "Full name must be at least 2 characters";
      }
    }

    if (name === "email") {
      const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
      if (!value || !emailRegex.test(value)) {
        error = "Enter a valid email address";
      }
    }

    if (name === "phone_number") {
      if (value) {
        const digitsOnly = value.replace(/\D/g, "");
        const phoneRegex = /^[0-9]{10,11}$/;

        if (!phoneRegex.test(digitsOnly)) {
          error = "Enter valid US phone number";
        }
      }
    }

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

    return error;
  };

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

    let updatedValue = value;
    if (name === "full_name") {
      updatedValue = value.replace(/[^a-zA-Z\s]/g, "");
    }

    if (name === "phone_number") {
      updatedValue = formatUSPhone(value);
    }

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

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

  const handleRoleChange = (selectedOption) => {
    setFormData((prev) => ({
      ...prev,
      role_id: selectedOption.target.value,
    }));
  };

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

    if (loading) return;

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

    try {
      setLoading(true);

      const payload = {
        case_id: Number(caseId),
        email: formData.email,
        password: formData.password,
        roles: [Number(1)],

        details: {
          full_name: formData.full_name,
          phone_number: toUSPhoneE164(formData.phone_number),
          organization_name: formData.organization_name,
          address: formData.address,
          status: "available",
        },
      };

      await createUserWithCase(payload);

      toast.success("User created successfully!");

      if (onCreated) {
        await onCreated();
      }

      onClose();
    } catch (err) {
      console.error("User creation failed:", err);

      if (err.response?.data) {
        const data = err.response.data;

        let message = "Failed to create user";

        if (data.details && typeof data.details === "object") {
          const firstKey = Object.keys(data.details)[0];
          message = data.details[firstKey]?.[0] || message;
        } else if (typeof data === "object") {
          const firstValue = Object.values(data)?.[0];

          if (Array.isArray(firstValue)) {
            message = firstValue?.[0];
          } else if (typeof firstValue === "string") {
            message = firstValue;
          }
        }

        toast.error(message);
      } else {
        toast.error("Failed to create user");
      }
    } finally {
      setLoading(false);
    }
  };

  if (!show) return null;

  return (
    <div className="modal fade show" style={{ display: "block" }}>
      <div className="modal-dialog modal-lg modal-dialog-centered">
        <div className="modal-content editProfilepopup">
          <div className="modal-header mb-3">
            <div className="d-block">
              <h5 className="modal-title">Add Team Member</h5>
              <p>Add a new Analyst, Attorney, or Paralegal to this case.</p>
            </div>
            <button
              type="button"
              className="btn-close"
              onClick={onClose}
            ></button>
          </div>

          <div className="modal-body">
            <form id="addTeamMemberForm" onSubmit={handleSubmit}>
              <div className="row">
                {/* Full Name */}
                <div className="col-md-6 mb-3">
                  <label className="d-block text-start">
                    Full Name <span className="text-danger">*</span>
                  </label>
                  <input
                    type="text"
                    className="form-control"
                    name="full_name"
                    value={formData.full_name}
                    onChange={handleChange}
                    placeholder="Enter full name"
                    required
                  />
                  {errors.full_name && (
                    <small className="text-danger">{errors.full_name}</small>
                  )}
                </div>

                {/* Phone Number */}
                <div className="col-md-6 mb-3">
                  <label className="d-block text-start">Phone Number</label>
                  <input
                    type="tel"
                    className="form-control"
                    name="phone_number"
                    value={formData.phone_number}
                    onChange={handleChange}
                    placeholder="(123) 456-7890"
                    maxLength={14}
                  />
                  {errors.phone_number && (
                    <small className="text-danger">{errors.phone_number}</small>
                  )}
                </div>

                {/* Email */}
                <div className="col-md-6 mb-3">
                  <label className="d-block text-start">
                    Email <span className="text-danger">*</span>
                  </label>
                  <input
                    type="email"
                    className="form-control"
                    name="email"
                    value={formData.email}
                    onChange={handleChange}
                    placeholder="Enter e-mail address"
                    required
                  />
                  {errors.email && (
                    <small className="text-danger">{errors.email}</small>
                  )}
                </div>

                {/* Organization */}
                <div className="col-md-6 mb-3">
                  <label className="d-block text-start">
                    Organization Name
                  </label>
                  <input
                    type="text"
                    className="form-control"
                    name="organization_name"
                    value={formData.organization_name}
                    onChange={handleChange}
                    placeholder="Enter organization name"
                  />
                </div>

                {/* Address */}
                <div className="col-md-12 mb-3">
                  <label className="d-block text-start">Address</label>
                  <input
                    type="text"
                    className="form-control"
                    name="address"
                    value={formData.address}
                    onChange={handleChange}
                    placeholder="Enter address"
                  />
                </div>

                {/* User Role */}
                {/* <div className="col-md-6 mb-3 text-start">
                  <label className="d-block text-start">Select User Role</label>

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

                {/* Password */}
                <div className="col-md-6 mb-3">
                  <label className="d-block text-start">
                    Password <span className="text-danger">*</span>
                  </label>
                  <input
                    type="password"
                    className="form-control"
                    name="password"
                    value={formData.password}
                    onChange={handleChange}
                    placeholder="Enter password"
                    required
                  />
                  {errors.password && (
                    <small className="text-danger">{errors.password}</small>
                  )}
                </div>
              </div>
            </form>
          </div>

          <div className="modal-footer justify-content-between">
            <button
              className="btn btn-light"
              onClick={onClose}
              disabled={loading}
            >
              Cancel
            </button>
            <button
              className="btn btn-primary"
              type="submit"
              form="addTeamMemberForm"
              disabled={loading}
            >
              {loading ? "Creating..." : "Create User"}
            </button>
          </div>
        </div>
      </div>
    </div>
  );
};

export default AddTeamMemberModal;
