import React, { useState, useEffect } from "react";
import { useNavigate } from "react-router-dom";
import axiosInstance from "../utils/axiosConfig";
import {
  USERS_URL,
  DEPARTMENTS_URL,
  COUNTRY_URL,
  LOCATIONS_URL,
  ROLES_URL,
} from "../utils/config";

const UserCreate = () => {
  const navigate = useNavigate();
  const [activeTab, setActiveTab] = useState("all");
  const [formData, setFormData] = useState({
    employee_id: "",
    employee_name: "",
    email_id: "",
    phonenumber: "",
    department_id: "",
    country_id: "",
    location_id: "",
    password: "",
    role_ids: [],
  });
  const [departments, setDepartments] = useState([]);
  const [countries, setCountries] = useState([]);
  const [locations, setLocations] = useState([]);
  const [roles, setRoles] = useState([]);
  const [users, setUsers] = useState([]);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState(null);
  const [roleDropdownOpen, setRoleDropdownOpen] = useState(false);
  const [loadingRoles, setLoadingRoles] = useState(true);
  const [showPopup, setShowPopup] = useState(false);
  const [popupMessage, setPopupMessage] = useState("");

  useEffect(() => {
    const fetchData = async () => {
      try {
        setLoadingRoles(true);
        const [deptRes, countryRes, rolesRes, usersRes] = await Promise.all([
          axiosInstance.get(DEPARTMENTS_URL),
          axiosInstance.get(COUNTRY_URL),
          axiosInstance.get(ROLES_URL),
          axiosInstance.get(USERS_URL),
        ]);

        if (deptRes.data.success) setDepartments(deptRes.data.data || []);
        if (countryRes.data.success) setCountries(countryRes.data.data || []);

        // Fetch roles from ROLES_URL API
        if (rolesRes.data.success) {
          const rolesData = rolesRes.data.data || [];
          console.log("Roles fetched from API:", rolesData);
          setRoles(rolesData);
        } else {
          console.error("Roles API response not successful:", rolesRes.data);
        }

        if (usersRes.data.success) setUsers(usersRes.data.data || []);
      } catch (err) {
        console.error("Error fetching data:", err);
        console.error("Roles API Error:", err.response?.data || err.message);
        setError("Failed to load form data");
      } finally {
        setLoadingRoles(false);
      }
    };
    fetchData();
  }, []);

  // Fetch locations when country is selected
  useEffect(() => {
    const fetchLocationsByCountry = async () => {
      if (!formData.country_id) {
        setLocations([]);
        return;
      }

      try {
        const response = await axiosInstance.get(
          `${LOCATIONS_URL}/country/${formData.country_id}`
        );
        if (response.data.success) {
          setLocations(response.data.data || []);
        }
      } catch (err) {
        console.error("Error fetching locations by country:", err);
        setLocations([]);
      }
    };

    fetchLocationsByCountry();
  }, [formData.country_id]);

  // Refresh users list when switching to "All Users" tab
  useEffect(() => {
    const fetchUsers = async () => {
      if (activeTab === "all") {
        try {
          const usersRes = await axiosInstance.get(USERS_URL);
          if (usersRes.data.success) {
            setUsers(usersRes.data.data || []);
          }
        } catch (err) {
          console.error("Error fetching users:", err);
        }
      }
    };

    fetchUsers();
  }, [activeTab]);

  // Close dropdown when clicking outside
  useEffect(() => {
    const handleClickOutside = (event) => {
      const roleDropdown = event.target.closest("[data-role-dropdown]");
      if (roleDropdownOpen && !roleDropdown) {
        setRoleDropdownOpen(false);
      }
    };
    if (roleDropdownOpen) {
      document.addEventListener("mousedown", handleClickOutside);
    }
    return () => {
      document.removeEventListener("mousedown", handleClickOutside);
    };
  }, [roleDropdownOpen]);

  const handleChange = (e) => {
    const { name, value } = e.target;
    setFormData((prev) => {
      // If country changes, clear location_id
      if (name === "country_id") {
        return { ...prev, [name]: value, location_id: "" };
      }
      return { ...prev, [name]: value };
    });
  };

  const handleRoleToggle = (roleId) => {
    setFormData((prev) => {
      const roleIdNum = parseInt(roleId);
      const isSelected = prev.role_ids.includes(roleIdNum);
      return {
        ...prev,
        role_ids: isSelected
          ? prev.role_ids.filter((id) => id !== roleIdNum)
          : [...prev.role_ids, roleIdNum],
      };
    });
  };

  const handleSubmit = async (e) => {
    e.preventDefault();
    setLoading(true);
    setError(null);

    // Validate required fields
    if (
      !formData.employee_id ||
      !formData.employee_name ||
      !formData.email_id ||
      !formData.password ||
      formData.role_ids.length === 0
    ) {
      setError("Please fill in all required fields");
      setLoading(false);
      return;
    }

    try {
      const response = await axiosInstance.post(USERS_URL, {
        employee_id: formData.employee_id,
        status_id: 1, // Default to Active (1)
        employee_name: formData.employee_name,
        email_id: formData.email_id,
        phonenumber: formData.phonenumber || null,
        department_id: formData.department_id
          ? parseInt(formData.department_id)
          : null,
        location_id: formData.location_id
          ? parseInt(formData.location_id)
          : null,
        password: formData.password,
        role_ids: formData.role_ids,
      });

      if (response.data.success) {
        setPopupMessage("User created successfully!");
        setShowPopup(true);
        clearForm();
        // Refresh users list if on "All Users" tab
        if (activeTab === "all") {
          const usersRes = await axiosInstance.get(USERS_URL);
          if (usersRes.data.success) setUsers(usersRes.data.data || []);
        }
      }
    } catch (err) {
      setError(err.response?.data?.message || "Failed to create user");
      console.error("Error creating user:", err);
    } finally {
      setLoading(false);
    }
  };

  const clearForm = () => {
    setFormData({
      employee_id: "",
      employee_name: "",
      email_id: "",
      phonenumber: "",
      department_id: "",
      country_id: "",
      location_id: "",
      password: "",
      role_ids: [],
    });
    setError(null);
  };

  const handleToggleUserStatus = async (userId, currentStatusId) => {
    // Toggle status: 1 (Active) -> 2 (Inactive), 2 (Inactive) -> 1 (Active)
    const statusId = Number(currentStatusId) || 1;
    const newStatusId = statusId === 1 ? 2 : 1;
    const statusText = newStatusId === 1 ? "activated" : "deactivated";

    try {
      setLoading(true);
      const response = await axiosInstance.put(`${USERS_URL}/${userId}`, {
        status_id: newStatusId,
      });

      if (response.data.success) {
        setPopupMessage('User deleted successfully!');
        setShowPopup(true);
        // Refresh users list
        const usersRes = await axiosInstance.get(USERS_URL);
        if (usersRes.data.success) {
          setUsers(usersRes.data.data || []);
        }
      }
    } catch (err) {
      setError(err.response?.data?.message || 'Failed to delete user');
      console.error('Error deleting user:', err);
    } finally {
      setLoading(false);
    }
  };

  return (
    <>
      {/* Success Popup */}
      {showPopup && (
        <div
          style={{
            position: "fixed",
            top: 0,
            left: 0,
            right: 0,
            bottom: 0,
            backgroundColor: "rgba(0, 0, 0, 0.5)",
            display: "flex",
            justifyContent: "center",
            alignItems: "center",
            zIndex: 10000,
            animation: "fadeIn 0.3s ease-in",
          }}
          onClick={() => setShowPopup(false)}
        >
          <div
            style={{
              backgroundColor: "#fff",
              borderRadius: "0.75rem",
              padding: "2rem",
              maxWidth: "400px",
              width: "90%",
              boxShadow: "0 10px 25px rgba(0, 0, 0, 0.2)",
              animation: "slideUp 0.3s ease-out",
              position: "relative",
            }}
            onClick={(e) => e.stopPropagation()}
          >
            <button
              onClick={() => setShowPopup(false)}
              style={{
                position: "absolute",
                top: "1rem",
                right: "1rem",
                background: "none",
                border: "none",
                fontSize: "1.5rem",
                cursor: "pointer",
                color: "#4d4d4f",
                padding: "0",
                width: "30px",
                height: "30px",
                display: "flex",
                alignItems: "center",
                justifyContent: "center",
                borderRadius: "50%",
                transition: "background-color 0.2s",
              }}
              onMouseEnter={(e) =>
                (e.currentTarget.style.backgroundColor = "#f0f0f0")
              }
              onMouseLeave={(e) =>
                (e.currentTarget.style.backgroundColor = "transparent")
              }
            >
              ×
            </button>
            <div style={{ textAlign: "center", marginTop: "1rem" }}>
              <div
                style={{
                  width: "60px",
                  height: "60px",
                  borderRadius: "50%",
                  backgroundColor: "#4CAF50",
                  display: "flex",
                  alignItems: "center",
                  justifyContent: "center",
                  margin: "0 auto 1.5rem",
                  animation: "scaleIn 0.3s ease-out",
                }}
              >
                <svg
                  viewBox="0 0 24 24"
                  fill="none"
                  xmlns="http://www.w3.org/2000/svg"
                  style={{ width: "36px", height: "36px", color: "#fff" }}
                >
                  <path
                    d="M20 6L9 17L4 12"
                    stroke="currentColor"
                    strokeWidth="2"
                    strokeLinecap="round"
                    strokeLinejoin="round"
                  />
                </svg>
              </div>
              <h3
                style={{
                  margin: "0 0 1rem 0",
                  fontSize: "1.5rem",
                  color: "#333",
                  fontWeight: "600",
                }}
              >
                Success!
              </h3>
              <p
                style={{
                  margin: "0 0 2rem 0",
                  fontSize: "1rem",
                  color: "#4d4d4f",
                  lineHeight: "1.5",
                }}
              >
                {popupMessage}
              </p>
              <button
                onClick={() => setShowPopup(false)}
                style={{
                  backgroundColor: "#4CAF50",
                  color: "#fff",
                  border: "none",
                  borderRadius: "0.5rem",
                  padding: "0.75rem 2rem",
                  fontSize: "1rem",
                  cursor: "pointer",
                  fontWeight: "500",
                  transition: "background-color 0.2s",
                  width: "100%",
                }}
                onMouseEnter={(e) =>
                  (e.currentTarget.style.backgroundColor = "#45a049")
                }
                onMouseLeave={(e) =>
                  (e.currentTarget.style.backgroundColor = "#4CAF50")
                }
              >
                OK
              </button>
            </div>
          </div>
        </div>
      )}

      <style>{`
        @keyframes fadeIn {
          from { opacity: 0; }
          to { opacity: 1; }
        }
        @keyframes slideUp {
          from {
            transform: translateY(20px);
            opacity: 0;
          }
          to {
            transform: translateY(0);
            opacity: 1;
          }
        }
        @keyframes scaleIn {
          from {
            transform: scale(0);
          }
          to {
            transform: scale(1);
          }
        }
      `}</style>

      <div className="tab-navigation">
        <button
          className={`tab-btn ${activeTab === "all" ? "active" : ""}`}
          onClick={() => setActiveTab("all")}
          data-tab="all"
        >
          <svg
            viewBox="0 0 24 24"
            fill="none"
            xmlns="http://www.w3.org/2000/svg"
          >
            <path
              d="M17 21V19C17 17.9391 16.5786 16.9217 15.8284 16.1716C15.0783 15.4214 14.0609 15 13 15H5C3.93913 15 2.92172 15.4214 2.17157 16.1716C1.42143 16.9217 1 17.9391 1 19V21"
              stroke="currentColor"
              strokeWidth="2"
              strokeLinecap="round"
              strokeLinejoin="round"
            />
            <path
              d="M9 11C11.2091 11 13 9.20914 13 7C13 4.79086 11.2091 3 9 3C6.79086 3 5 4.79086 5 7C5 9.20914 6.79086 11 9 11Z"
              stroke="currentColor"
              strokeWidth="2"
              strokeLinecap="round"
              strokeLinejoin="round"
            />
            <path
              d="M23 21V19C22.9993 18.1137 22.7044 17.2528 22.1614 16.5523C21.6184 15.8519 20.8581 15.3516 20 15.13"
              stroke="currentColor"
              strokeWidth="2"
              strokeLinecap="round"
              strokeLinejoin="round"
            />
            <path
              d="M16 3.13C16.8604 3.35031 17.623 3.85071 18.1676 4.55232C18.7122 5.25392 19.0078 6.11683 19.0078 7.005C19.0078 7.89317 18.7122 8.75608 18.1676 9.45768C17.623 10.1593 16.8604 10.6597 16 10.88"
              stroke="currentColor"
              strokeWidth="2"
              strokeLinecap="round"
              strokeLinejoin="round"
            />
          </svg>
          <span>All Users</span>
        </button>
        <button
          className={`tab-btn ${activeTab === "create" ? "active" : ""}`}
          onClick={() => setActiveTab("create")}
          data-tab="create"
        >
          <svg
            viewBox="0 0 24 24"
            fill="none"
            xmlns="http://www.w3.org/2000/svg"
          >
            <path
              d="M16 21V5C16 4.46957 15.7893 3.96086 15.4142 3.58579C15.0391 3.21071 14.5304 3 14 3H10C9.46957 3 8.96086 3.21071 8.58579 3.58579C8.21071 3.96086 8 4.46957 8 5V21"
              stroke="currentColor"
              strokeWidth="2"
              strokeLinecap="round"
              strokeLinejoin="round"
            />
            <path
              d="M16 7H20C20.5304 7 21.0391 7.21071 21.4142 7.58579C21.7893 7.96086 22 8.46957 22 9V19C22 19.5304 21.7893 20.0391 21.4142 20.4142C21.0391 20.7893 20.5304 21 20 21H4C3.46957 21 2.96086 20.7893 2.58579 20.4142C2.21071 20.0391 2 19.5304 2 19V9C2 8.46957 2.21071 7.96086 2.58579 7.58579C2.96086 7.21071 3.46957 7 4 7H8"
              stroke="currentColor"
              strokeWidth="2"
              strokeLinecap="round"
              strokeLinejoin="round"
            />
            <path
              d="M12 11V17M9 14H15"
              stroke="currentColor"
              strokeWidth="2"
              strokeLinecap="round"
              strokeLinejoin="round"
            />
          </svg>
          <span>Create User</span>
        </button>
      </div>

      {activeTab === "create" && (
        <div className="tab-content active" id="createTab">
          <div className="form-section">
            <div className="form-header">
              <h1 style={{ margin: 0, padding: 0 }}>User Create</h1>
              <button
                className="close-btn"
                onClick={() => navigate("/dashboard")}
              >
                <svg
                  viewBox="0 0 24 24"
                  fill="none"
                  xmlns="http://www.w3.org/2000/svg"
                >
                  <path
                    d="M18 6L6 18M6 6L18 18"
                    stroke="currentColor"
                    strokeWidth="2"
                    strokeLinecap="round"
                    strokeLinejoin="round"
                  />
                </svg>
              </button>
            </div>

            <form className="user-form" onSubmit={handleSubmit}>
              {error && (
                <div
                  style={{
                    padding: "0.75rem",
                    marginBottom: "1rem",
                    backgroundColor: "#fef2f2",
                    color: "#f21b23",
                    borderRadius: "0.5rem",
                    fontSize: "0.9rem",
                  }}
                >
                  {error}
                </div>
              )}
              <div className="form-grid">
                <div className="form-column">
                  <div className="input-group">
                    <label htmlFor="employee_id" className="input-label">
                      Employee ID <span style={{ color: "red" }}>*</span>
                    </label>
                    <input
                      type="text"
                      id="employee_id"
                      name="employee_id"
                      className="input-field"
                      placeholder="e.g., EMP004"
                      value={formData.employee_id}
                      onChange={handleChange}
                      required
                    />
                  </div>
                  <div className="input-group">
                    <label htmlFor="employee_name" className="input-label">
                      Employee Name <span style={{ color: "red" }}>*</span>
                    </label>
                    <input
                      type="text"
                      id="employee_name"
                      name="employee_name"
                      className="input-field"
                      placeholder="Full Name"
                      value={formData.employee_name}
                      onChange={handleChange}
                      required
                    />
                  </div>
                  <div className="input-group">
                    <label htmlFor="email_id" className="input-label">
                      Email ID <span style={{ color: "red" }}>*</span>
                    </label>
                    <input
                      type="email"
                      id="email_id"
                      name="email_id"
                      className="input-field"
                      placeholder="Email Address"
                      value={formData.email_id}
                      onChange={handleChange}
                      required
                    />
                  </div>
                  <div className="input-group">
                    <label htmlFor="phonenumber" className="input-label">
                      Phone Number
                    </label>
                    <input
                      type="tel"
                      id="phonenumber"
                      name="phonenumber"
                      className="input-field"
                      placeholder="Phone Number"
                      value={formData.phonenumber}
                      onChange={handleChange}
                    />
                  </div>
                  <div className="input-group">
                    <label htmlFor="password" className="input-label">
                      Password <span style={{ color: "red" }}>*</span>
                    </label>
                    <input
                      type="password"
                      id="password"
                      name="password"
                      className="input-field"
                      placeholder="Password"
                      value={formData.password}
                      onChange={handleChange}
                      required
                    />
                  </div>
                </div>
                <div className="form-column">
                  <div className="input-group">
                    <label htmlFor="department_id" className="input-label">
                      Department
                    </label>
                    <select
                      id="department_id"
                      name="department_id"
                      className="input-field select-field"
                      value={formData.department_id}
                      onChange={handleChange}
                    >
                      <option value="">Select Department</option>
                      {departments.map((dept) => (
                        <option
                          key={dept.department_id}
                          value={dept.department_id}
                        >
                          {dept.department_name}
                        </option>
                      ))}
                    </select>
                  </div>
                  <div className="input-group">
                    <label htmlFor="country_id" className="input-label">
                      Country
                    </label>
                    <select
                      id="country_id"
                      name="country_id"
                      className="input-field select-field"
                      value={formData.country_id}
                      onChange={handleChange}
                    >
                      <option value="">Select Country</option>
                      {countries.map((country) => (
                        <option
                          key={country.country_id}
                          value={country.country_id}
                        >
                          {country.country_name}
                        </option>
                      ))}
                    </select>
                  </div>
                  <div className="input-group">
                    <label htmlFor="location_id" className="input-label">
                      Location
                    </label>
                    <select
                      id="location_id"
                      name="location_id"
                      className="input-field select-field"
                      value={formData.location_id}
                      onChange={handleChange}
                      disabled={!formData.country_id || locations.length === 0}
                    >
                      <option value="">
                        {!formData.country_id
                          ? "Select Location"
                          : locations.length === 0
                          ? "No location is available"
                          : "Select Location"}
                      </option>
                      {locations.map((loc) => (
                        <option key={loc.location_id} value={loc.location_id}>
                          {loc.location_name}
                        </option>
                      ))}
                    </select>
                  </div>
                  <div className="input-group">
                    <label htmlFor="role_ids" className="input-label">
                      Roles <span style={{ color: "red" }}>*</span>
                    </label>
                    <div style={{ position: "relative" }} data-role-dropdown>
                      <div
                        className="input-field select-field"
                        style={{
                          cursor: "pointer",
                          display: "flex",
                          justifyContent: "space-between",
                          alignItems: "center",
                          padding: "0.75rem",
                        }}
                        onClick={() => setRoleDropdownOpen(!roleDropdownOpen)}
                      >
                        <span
                          style={{
                            color:
                              formData.role_ids.length === 0 ? "#999" : "#000",
                          }}
                        >
                          {loadingRoles
                            ? "Loading roles..."
                            : formData.role_ids.length === 0
                            ? "Select Roles"
                            : formData.role_ids.length === 1
                            ? roles.find(
                                (r) => r.role_id === formData.role_ids[0]
                              )?.role_name ||
                              `${formData.role_ids.length} role selected`
                            : `${formData.role_ids.length} roles selected`}
                        </span>
                        <svg
                          viewBox="0 0 24 24"
                          fill="none"
                          xmlns="http://www.w3.org/2000/svg"
                          style={{
                            width: "20px",
                            height: "20px",
                            transform: roleDropdownOpen
                              ? "rotate(180deg)"
                              : "rotate(0deg)",
                            transition: "transform 0.3s",
                          }}
                        >
                          <path
                            d="M6 9L12 15L18 9"
                            stroke="currentColor"
                            strokeWidth="2"
                            strokeLinecap="round"
                            strokeLinejoin="round"
                          />
                        </svg>
                      </div>
                      {roleDropdownOpen && (
                        <div
                          style={{
                            position: "absolute",
                            top: "100%",
                            left: 0,
                            right: 0,
                            backgroundColor: "#fff",
                            border: "1px solid #ddd",
                            borderRadius: "0.5rem",
                            marginTop: "0.25rem",
                            maxHeight: "200px",
                            overflowY: "auto",
                            zIndex: 1000,
                            boxShadow: "0 4px 6px rgba(0, 0, 0, 0.1)",
                          }}
                        >
                          {loadingRoles ? (
                            <div
                              style={{
                                padding: "0.75rem",
                                color: "#999",
                                textAlign: "center",
                              }}
                            >
                              Loading roles...
                            </div>
                          ) : roles.length === 0 ? (
                            <div style={{ padding: "0.75rem", color: "#999" }}>
                              No roles available. Please check the API
                              connection.
                            </div>
                          ) : (
                            roles.map((role) => (
                              <label
                                key={role.role_id}
                                style={{
                                  display: "flex",
                                  alignItems: "center",
                                  gap: "0.5rem",
                                  padding: "0.75rem",
                                  cursor: "pointer",
                                  borderBottom: "1px solid #f0f0f0",
                                  transition: "background-color 0.2s",
                                }}
                                onClick={(e) => e.stopPropagation()}
                                onMouseEnter={(e) =>
                                  (e.currentTarget.style.backgroundColor =
                                    "#e5e5e5")
                                }
                                onMouseLeave={(e) =>
                                  (e.currentTarget.style.backgroundColor =
                                    "transparent")
                                }
                              >
                                <input
                                  type="checkbox"
                                  checked={formData.role_ids.includes(
                                    role.role_id
                                  )}
                                  onChange={() =>
                                    handleRoleToggle(role.role_id)
                                  }
                                  style={{
                                    cursor: "pointer",
                                    width: "18px",
                                    height: "18px",
                                  }}
                                />
                                <span style={{ flex: 1 }}>
                                  {role.role_name}
                                </span>
                                {role.description && (
                                  <span
                                    style={{
                                      fontSize: "0.85rem",
                                      color: "#4d4d4f",
                                    }}
                                  >
                                    ({role.description})
                                  </span>
                                )}
                              </label>
                            ))
                          )}
                        </div>
                      )}
                    </div>
                  </div>
                </div>
              </div>
              <div className="form-actions">
                <button
                  type="button"
                  className="btn-secondary"
                  onClick={clearForm}
                  disabled={loading}
                >
                  Clear Form
                </button>
                <button
                  type="submit"
                  className="btn-primary"
                  disabled={loading}
                >
                  {loading ? "Creating..." : "Submit"}
                </button>
              </div>
            </form>
          </div>
        </div>
      )}

      {activeTab === "all" && (
        <div className="tab-content active" id="allTab">
          <div className="table-section">
            <div className="table-header">
              <h2 style={{ margin: 0, padding: 0 }}>All User Details</h2>
              <div className="table-controls">
                <button
                  className="btn-export"
                  onClick={() => alert("Export functionality")}
                  title="Export to CSV"
                >
                  <svg
                    viewBox="0 0 24 24"
                    fill="none"
                    xmlns="http://www.w3.org/2000/svg"
                  >
                    <path
                      d="M21 15V19C21 19.5304 20.7893 20.0391 20.4142 20.4142C20.0391 20.7893 19.5304 21 19 21H5C4.46957 21 3.96086 20.7893 3.58579 20.4142C3.21071 20.0391 3 19.5304 3 19V15"
                      stroke="currentColor"
                      strokeWidth="2"
                      strokeLinecap="round"
                      strokeLinejoin="round"
                    />
                    <path
                      d="M7 10L12 15L17 10M12 15V3"
                      stroke="currentColor"
                      strokeWidth="2"
                      strokeLinecap="round"
                      strokeLinejoin="round"
                    />
                  </svg>
                  Export CSV
                </button>
              </div>
            </div>
            <div className="table-container">
              <table className="user-table">
                <thead>
                  <tr>
                    <th style={{ textAlign: "center" }}>SI No</th>
                    <th style={{ textAlign: "center" }}>Employee ID</th>
                    <th style={{ textAlign: "center" }}>Name</th>
                    <th style={{ textAlign: "center" }}>Email</th>
                    <th style={{ textAlign: "center" }}>Department</th>
                    <th style={{ textAlign: "center" }}>Location</th>
                    <th style={{ textAlign: "center" }}>Status</th>
                    <th style={{ textAlign: "center" }}>Roles</th>
                    <th style={{ textAlign: "center" }}>Action</th>
                  </tr>
                </thead>
                <tbody>
                  {users.length === 0 ? (
                    <tr>
                      <td
                        colSpan="9"
                        style={{ textAlign: "center", padding: "2rem" }}
                      >
                        No users found
                      </td>
                    </tr>
                  ) : (
                    users.map((user, index) => (
                      <tr key={user.user_id}>
                        <td style={{ textAlign: "center" }}>{index + 1}</td>
                        <td style={{ textAlign: "center" }}>
                          {user.employee_id || "-"}
                        </td>
                        <td style={{ textAlign: "center" }}>
                          {user.employee_name || "-"}
                        </td>
                        <td style={{ textAlign: "center" }}>
                          {user.email_id || "-"}
                        </td>
                        <td style={{ textAlign: "center" }}>
                          {user.department_name || "-"}
                        </td>
                        <td style={{ textAlign: "center" }}>
                          {user.location_name || "-"}
                        </td>
                        <td style={{ textAlign: "center" }}>
                          <div
                            style={{
                              display: "flex",
                              alignItems: "center",
                              justifyContent: "center",
                              gap: "0.75rem",
                            }}
                          >
                            <label
                              style={{
                                position: "relative",
                                display: "inline-block",
                                width: "36px",
                                height: "18px",
                                cursor: loading ? "not-allowed" : "pointer",
                              }}
                            >
                              <input
                                type="checkbox"
                                checked={Number(user.status_id) === 1}
                                onChange={() =>
                                  handleToggleUserStatus(
                                    user.user_id,
                                    Number(user.status_id) || 1
                                  )
                                }
                                disabled={loading}
                                style={{
                                  opacity: 0,
                                  width: 0,
                                  height: 0,
                                }}
                              />
                              <span
                                style={{
                                  position: "absolute",
                                  top: 0,
                                  left: 0,
                                  right: 0,
                                  bottom: 0,
                                  backgroundColor:
                                    Number(user.status_id) === 1
                                      ? "#4CAF50"
                                      : "#ccc",
                                  borderRadius: "9px",
                                  transition: "background-color 0.3s",
                                }}
                              />
                              <span
                                style={{
                                  position: "absolute",
                                  width: "14px",
                                  height: "14px",
                                  borderRadius: "50%",
                                  backgroundColor: "#fff",
                                  top: "2px",
                                  left:
                                    Number(user.status_id) === 1
                                      ? "calc(100% - 16px)"
                                      : "2px",
                                  transition: "left 0.3s",
                                  boxShadow: "0 2px 4px rgba(0,0,0,0.2)",
                                }}
                              />
                            </label>
                            <span
                              style={{
                                fontSize: "0.875rem",
                                color:
                                  Number(user.status_id) === 1
                                    ? "#4CAF50"
                                    : "#4d4d4f",
                                fontWeight: "500",
                                minWidth: "60px",
                              }}
                            >
                              {Number(user.status_id) === 1
                                ? "Active"
                                : "Inactive"}
                            </span>
                          </div>
                        </td>
                        <td style={{ textAlign: "center" }}>
                          {user.roles || "-"}
                        </td>
                        <td style={{ textAlign: "center" }}>
                          <button
                            className="action-btn btn-update"
                            onClick={() =>
                              navigate(`/user-profile/${user.user_id}`)
                            }
                          >
                            Update
                          </button>
                        </td>
                      </tr>
                    ))
                  )}
                </tbody>
              </table>
            </div>
          </div>
        </div>
      )}
    </>
  );
};

export default UserCreate;
