import React, { useState, useMemo, useEffect } from "react";
import { useNavigate } from "react-router-dom";
import Button from "../../../common/Button";
import UserStatusToggle from "../common/UserStatusToggle";
import Pagination from "../../../common/Pagination";
import "../../activitylog/styles/ActivityLogControls.css";
import "../styles/AllUsersTable.css";

const VIEW_MODES = { LIST: "list", CARD: "card" };
const ENTRIES_PER_PAGE_OPTIONS = [10, 25, 50, 100];
const DEFAULT_ENTRIES_PER_PAGE = 10;

const AllUsersTable = ({ users, loading, onStatusToggle, onExport, searchTerm = "", onSearchChange, viewMode = "list", onViewModeChange }) => {
  const navigate = useNavigate();
  const [currentPage, setCurrentPage] = useState(1);
  const [entriesPerPage, setEntriesPerPage] = useState(DEFAULT_ENTRIES_PER_PAGE);

  const handleEntriesPerPageChange = (e) => {
    setEntriesPerPage(Number(e.target.value));
    setCurrentPage(1);
  };

  const list = useMemo(() => (Array.isArray(users) ? users : []), [users]);
  const totalEntries = list.length;
  const totalPages = Math.max(1, Math.ceil(totalEntries / entriesPerPage));
  const paginatedUsers = useMemo(() => {
    const start = (currentPage - 1) * entriesPerPage;
    return list.slice(start, start + entriesPerPage);
  }, [list, currentPage, entriesPerPage]);

  useEffect(() => {
    if (currentPage > totalPages) setCurrentPage(1);
  }, [totalPages, currentPage]);

  return (
    <div className="tab-content active" id="allTab">
      <div className="table-section">
        <div className="table-header">
          <h2 className="table-header-title">All User Details</h2>
          <div className="table-controls">
            <div className="users-view-toggle" role="group" aria-label="View mode">
              <button
                type="button"
                className={`users-view-btn ${viewMode === VIEW_MODES.LIST ? "active" : ""}`}
                onClick={() => onViewModeChange?.(VIEW_MODES.LIST)}
                title="List view"
                aria-pressed={viewMode === VIEW_MODES.LIST}
              >
                <svg viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg" width="18" height="18">
                  <path d="M8 6H21M8 12H21M8 18H21M3 6H3.01M3 12H3.01M3 18H3.01" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" />
                </svg>
              </button>
              <button
                type="button"
                className={`users-view-btn ${viewMode === VIEW_MODES.CARD ? "active" : ""}`}
                onClick={() => onViewModeChange?.(VIEW_MODES.CARD)}
                title="Card view"
                aria-pressed={viewMode === VIEW_MODES.CARD}
              >
                <svg viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg" width="18" height="18">
                  <path d="M4 6C4 5.44772 4.44772 5 5 5H7C7.55228 5 8 5.44772 8 6V8C8 8.55228 7.55228 9 7 9H5C4.44772 9 4 8.55228 4 8V6Z" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" />
                  <path d="M16 6C16 5.44772 16.4477 5 17 5H19C19.5523 5 20 5.44772 20 6V8C20 8.55228 19.5523 9 19 9H17C16.4477 9 16 8.55228 16 8V6Z" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" />
                  <path d="M4 16C4 15.4477 4.44772 15 5 15H7C7.55228 15 8 15.4477 8 16V18C8 18.5523 7.55228 19 7 19H5C4.44772 19 4 18.5523 4 18V16Z" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" />
                  <path d="M16 16C16 15.4477 16.4477 15 17 15H19C19.5523 15 20 15.4477 20 16V18C20 18.5523 19.5523 19 19 19H17C16.4477 19 16 18.5523 16 18V16Z" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" />
                </svg>
              </button>
            </div>
            <div className="users-search-wrapper">
              <span className="users-search-icon" aria-hidden="true">
                <svg viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg" width="18" height="18">
                  <path
                    d="M21 21L15 15M17 10C17 13.866 13.866 17 10 17C6.13401 17 3 13.866 3 10C3 6.13401 6.13401 3 10 3C13.866 3 17 6.13401 17 10Z"
                    stroke="currentColor"
                    strokeWidth="2"
                    strokeLinecap="round"
                    strokeLinejoin="round"
                  />
                </svg>
              </span>
              <input
                type="search"
                className="users-search-input"
                placeholder="Search by name, email, ID, work area..."
                value={searchTerm}
                onChange={(e) => onSearchChange?.(e.target.value)}
                aria-label="Search users"
              />
            </div>
            <Button
              variant="export"
              onClick={onExport}
              title="Export to CSV"
              icon={
                <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>

        {!loading && list.length > 0 && (
          <div className="activity-log-controls-bar all-users-table-controls">
            <div className="activity-log-controls-left">
              <div className="show-entries">
                <label>Show</label>
                <select
                  className="entries-select"
                  value={entriesPerPage}
                  onChange={handleEntriesPerPageChange}
                  aria-label="Entries per page"
                >
                  {ENTRIES_PER_PAGE_OPTIONS.map((n) => (
                    <option key={n} value={n}>{n}</option>
                  ))}
                </select>
                <span>entries</span>
              </div>
            </div>
          </div>
        )}

        {viewMode === VIEW_MODES.LIST ? (
          <div className="table-container">
            <table className="user-table">
              <thead>
                <tr>
                  <th className="table-center">SI No</th>
                  <th className="table-center">Employee ID</th>
                  <th className="table-center">Name</th>
                  <th className="table-center">Email</th>
                  <th className="table-center">Work area</th>
                  <th className="table-center">Site</th>
                  <th className="table-center">Status</th>
                  <th className="table-center">Roles</th>
                  <th className="table-center">Action</th>
                </tr>
              </thead>
              <tbody>
                {paginatedUsers.length === 0 ? (
                  <tr>
                    <td colSpan="9" className="all-users-table-container">
                      No users found
                    </td>
                  </tr>
                ) : (
                  paginatedUsers.map((user, index) => (
                    <tr key={user.user_id}>
                      <td className="table-center">{(currentPage - 1) * entriesPerPage + index + 1}</td>
                      <td className="table-center">{user.employee_id || "-"}</td>
                      <td className="table-center">
                        {user.employee_name || "-"}
                      </td>
                      <td className="table-center">{user.email_id || "-"}</td>
                      <td className="table-center">
                        {user.department_name || "-"}
                      </td>
                      <td className="table-center">
                        {user.location_name || "-"}
                      </td>
                      <td className="table-center">
                        <UserStatusToggle
                          statusId={user.status_id}
                          onChange={() =>
                            onStatusToggle(user.user_id, user.status_id)
                          }
                          disabled={loading}
                        />
                      </td>
                      <td className="table-center">{user.roles || "-"}</td>
                      <td className="table-center">
                        <Button
                          variant="update"
                          onClick={() =>
                            navigate(`/user-profile/${user.user_id}`)
                          }
                        >
                          Update
                        </Button>
                      </td>
                    </tr>
                  ))
                )}
              </tbody>
            </table>
          </div>
        ) : (
          <div className="users-card-grid">
            {paginatedUsers.length === 0 ? (
              <div className="users-card-grid-empty">No users found</div>
            ) : (
              paginatedUsers.map((user, index) => (
                <div key={user.user_id} className="users-card">
                  <div className="users-card-header">
                    <span className="users-card-index">{(currentPage - 1) * entriesPerPage + index + 1}</span>
                    <UserStatusToggle
                      statusId={user.status_id}
                      onChange={() =>
                        onStatusToggle(user.user_id, user.status_id)
                      }
                      disabled={loading}
                    />
                  </div>
                  <div className="users-card-body">
                    <h3 className="users-card-name">{user.employee_name || "-"}</h3>
                    <p className="users-card-email">{user.email_id || "-"}</p>
                    <div className="users-card-meta">
                      <span className="users-card-meta-item">
                        <strong>ID:</strong> {user.employee_id || "-"}
                      </span>
                      <span className="users-card-meta-item">
                        <strong>Work area:</strong> {user.department_name || "-"}
                      </span>
                      <span className="users-card-meta-item">
                        <strong>Site:</strong> {user.location_name || "-"}
                      </span>
                      <span className="users-card-meta-item">
                        <strong>Roles:</strong> {user.roles || "-"}
                      </span>
                    </div>
                  </div>
                  <div className="users-card-footer">
                    <Button
                      variant="update"
                      onClick={() =>
                        navigate(`/user-profile/${user.user_id}`)
                      }
                    >
                      Update
                    </Button>
                  </div>
                </div>
              ))
            )}
          </div>
        )}

        {!loading && list.length > 0 && (
          <Pagination
            currentPage={currentPage}
            totalPages={totalPages}
            totalEntries={totalEntries}
            entriesPerPage={entriesPerPage}
            onPageChange={setCurrentPage}
          />
        )}
      </div>
    </div>
  );
};

export default AllUsersTable;
