import React, { useState, useEffect } from "react";
import axiosInstance from "../../../utils/axiosConfig";
import { USERS_URL } from "../../../utils/config";
import AllUsersTable from "./pages/AllUsersTable";
import SuccessPopup from "../../common/SuccessPopup";
import "./styles/UsersList.css";

const UsersList = () => {
  const [users, setUsers] = useState([]);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState(null);
  const [showPopup, setShowPopup] = useState(false);
  const [popupMessage, setPopupMessage] = useState("");
  const [searchTerm, setSearchTerm] = useState("");
  const [viewMode, setViewMode] = useState("list"); // "list" | "card"

  const fetchUsers = async () => {
    try {
      setLoading(true);
      setError(null);
      const response = await axiosInstance.get(USERS_URL);
      if (response.data.success && Array.isArray(response.data.data)) {
        setUsers(response.data.data);
      } else {
        setUsers([]);
      }
    } catch (err) {
      console.error("Error fetching users:", err);
      setError("Failed to load users. Please try again.");
      setUsers([]);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchUsers();
  }, []);

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

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

      if (response.data.success) {
        setPopupMessage(`User ${statusText} successfully!`);
        setShowPopup(true);
        await fetchUsers();
      } else {
        setError(response.data.message || `Failed to ${statusText} user`);
      }
    } catch (err) {
      setError(err.response?.data?.message || `Failed to ${statusText} user`);
      console.error(`Error ${statusText} user:`, err);
    } finally {
      setLoading(false);
    }
  };

  const handleExport = () => {
    alert("Export functionality");
  };

  const filteredUsers = users.filter((user) => {
    const term = searchTerm.toLowerCase().trim();
    if (!term) return true;
    const searchableFields = [
      user.employee_name,
      user.email_id,
      user.employee_id,
      user.department_name,
      user.location_name,
      user.roles,
    ]
      .filter(Boolean)
      .map((v) => String(v).toLowerCase());
    return searchableFields.some((field) => field.includes(term));
  });

  return (
    <>
      <SuccessPopup
        show={showPopup}
        message={popupMessage}
        onClose={() => setShowPopup(false)}
      />

      <div className="users-list-container">
        {error && (
          <div className="users-list-error">
            {error}
          </div>
        )}

        <AllUsersTable
          users={filteredUsers}
          loading={loading}
          onStatusToggle={handleToggleUserStatus}
          onExport={handleExport}
          searchTerm={searchTerm}
          onSearchChange={setSearchTerm}
          viewMode={viewMode}
          onViewModeChange={setViewMode}
        />
      </div>
    </>
  );
};

export default UsersList;
