import { useState, useEffect } from "react";
import { useNavigate } from "react-router-dom";
import api from "../api/client";
import { useAuth } from "../auth/AuthContext";
import SearchBar from "../components/SearchBar";
import ConfirmDialog from "../components/ConfirmDialog";

const STATUS_OPTIONS = ["", "active", "blocked"];

export default function UserList() {
  const [users, setUsers] = useState([]);
  const [total, setTotal] = useState(0);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState("");
  const [search, setSearch] = useState("");
  const [statusFilter, setStatusFilter] = useState("");
  const [deleteTarget, setDeleteTarget] = useState(null);
  const [hoveredRow, setHoveredRow] = useState(null);
  const navigate = useNavigate();
  const { hasPermission } = useAuth();
  const canEdit = hasPermission("app_users", "edit");

  const fetchUsers = async () => {
    setLoading(true);
    setError("");
    try {
      const params = new URLSearchParams();
      if (search) params.set("search", search);
      if (statusFilter) params.set("status", statusFilter);
      const qs = params.toString();
      const data = await api.get(`/users${qs ? `?${qs}` : ""}`);
      setUsers(data.users);
      setTotal(data.total);
    } catch (err) {
      setError(err.message);
    } finally {
      setLoading(false);
    }
  };

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

  const handleDelete = async () => {
    if (!deleteTarget) return;
    try {
      await api.delete(`/users/${deleteTarget.id}`);
      setDeleteTarget(null);
      fetchUsers();
    } catch (err) {
      setError(err.message);
      setDeleteTarget(null);
    }
  };

  return (
    <div>
      <div className="flex items-center justify-between mb-6">
        <h1 className="text-2xl font-bold" style={{ color: "var(--text-heading)" }}>User Management</h1>
        <div className="flex items-center gap-3">
          <span className="text-sm whitespace-nowrap" style={{ color: "var(--text-muted)" }}>
            {total} {total === 1 ? "user" : "users"}
          </span>
          {canEdit && (
            <button
              onClick={() => navigate("/users/new")}
              className="px-4 py-2 text-sm rounded-md hover:opacity-90 transition-colors cursor-pointer"
              style={{ backgroundColor: "var(--btn-primary)", color: "var(--text-white)" }}
            >
              Add User
            </button>
          )}
        </div>
      </div>

      <div className="mb-4 flex flex-wrap gap-3 items-center">
        <SearchBar
          onSearch={setSearch}
          placeholder="Search by name, email, phone, or UID..."
          style={{ flex: "1 1 200px", minWidth: 200 }}
        />
        <select
          value={statusFilter}
          onChange={(e) => setStatusFilter(e.target.value)}
          className="px-3 py-2 rounded-md text-sm cursor-pointer border"
          style={{
            backgroundColor: "var(--bg-card)",
            color: "var(--text-primary)",
            borderColor: "var(--border-primary)",
          }}
        >
          <option value="">All Status</option>
          {STATUS_OPTIONS.filter(Boolean).map((s) => (
            <option key={s} value={s}>
              {s.charAt(0).toUpperCase() + s.slice(1)}
            </option>
          ))}
        </select>
      </div>

      {error && (
        <div
          className="text-sm rounded-md p-3 mb-4 border"
          style={{
            backgroundColor: "var(--danger-bg)",
            borderColor: "var(--danger)",
            color: "var(--danger-text)",
          }}
        >
          {error}
        </div>
      )}

      {loading ? (
        <div className="text-center py-8" style={{ color: "var(--text-muted)" }}>Loading...</div>
      ) : users.length === 0 ? (
        <div
          className="rounded-lg p-8 text-center text-sm border"
          style={{
            backgroundColor: "var(--bg-card)",
            borderColor: "var(--border-primary)",
            color: "var(--text-muted)",
          }}
        >
          No users found.
        </div>
      ) : (
        <div
          className="rounded-lg overflow-hidden border"
          style={{
            backgroundColor: "var(--bg-card)",
            borderColor: "var(--border-primary)",
          }}
        >
          <div className="overflow-x-auto">
            <table className="w-full text-sm">
              <thead>
                <tr style={{ backgroundColor: "var(--bg-primary)", borderBottom: "1px solid var(--border-primary)" }}>
                  <th className="px-4 py-3 text-left font-medium w-10" style={{ color: "var(--text-secondary)" }}>Status</th>
                  <th className="px-4 py-3 text-left font-medium" style={{ color: "var(--text-secondary)" }}>Name</th>
                  <th className="px-4 py-3 text-left font-medium" style={{ color: "var(--text-secondary)" }}>Email</th>
                  <th className="px-4 py-3 text-left font-medium" style={{ color: "var(--text-secondary)" }}>Phone</th>
                  <th className="px-4 py-3 text-left font-medium" style={{ color: "var(--text-secondary)" }}>Title</th>
                  <th className="px-4 py-3 text-left font-medium" style={{ color: "var(--text-secondary)" }}>Last Active</th>
                  {canEdit && (
                    <th className="px-4 py-3 text-left font-medium w-24" style={{ color: "var(--text-secondary)" }} />
                  )}
                </tr>
              </thead>
              <tbody>
                {users.map((user, index) => (
                  <tr
                    key={user.id}
                    onClick={() => navigate(`/users/${user.id}`)}
                    className="cursor-pointer"
                    style={{
                      borderBottom: index < users.length - 1 ? "1px solid var(--border-primary)" : "none",
                      backgroundColor: hoveredRow === user.id ? "var(--bg-card-hover)" : index % 2 === 1 ? "var(--bg-row-alt)" : "transparent",
                    }}
                    onMouseEnter={() => setHoveredRow(user.id)}
                    onMouseLeave={() => setHoveredRow(null)}
                  >
                    <td className="px-4 py-3">
                      <span
                        className="px-2 py-0.5 text-xs rounded-full"
                        style={
                          user.status === "blocked"
                            ? { backgroundColor: "var(--danger-bg)", color: "var(--danger-text)" }
                            : user.status === "active"
                            ? { backgroundColor: "var(--success-bg)", color: "var(--success-text)" }
                            : { backgroundColor: "var(--bg-card-hover)", color: "var(--text-muted)" }
                        }
                      >
                        {user.status || "unknown"}
                      </span>
                    </td>
                    <td className="px-4 py-3 font-medium" style={{ color: "var(--text-heading)" }}>
                      {user.display_name || "Unnamed User"}
                    </td>
                    <td className="px-4 py-3" style={{ color: "var(--text-primary)" }}>
                      {user.email || "-"}
                    </td>
                    <td className="px-4 py-3" style={{ color: "var(--text-primary)" }}>
                      {user.phone_number || "-"}
                    </td>
                    <td className="px-4 py-3" style={{ color: "var(--text-primary)" }}>
                      {user.userTitle || "-"}
                    </td>
                    <td className="px-4 py-3 text-xs" style={{ color: "var(--text-muted)" }}>
                      {user.lastActive || "-"}
                    </td>
                    {canEdit && (
                      <td className="px-4 py-3">
                        <div
                          className="flex gap-2"
                          onClick={(e) => e.stopPropagation()}
                        >
                          <button
                            onClick={() => navigate(`/users/${user.id}/edit`)}
                            className="hover:opacity-80 text-xs cursor-pointer"
                            style={{ color: "var(--text-link)" }}
                          >
                            Edit
                          </button>
                          <button
                            onClick={() => setDeleteTarget(user)}
                            className="hover:opacity-80 text-xs cursor-pointer"
                            style={{ color: "var(--danger)" }}
                          >
                            Delete
                          </button>
                        </div>
                      </td>
                    )}
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </div>
      )}

      <ConfirmDialog
        open={!!deleteTarget}
        title="Delete User"
        message={`Are you sure you want to delete "${deleteTarget?.display_name || "this user"}" (${deleteTarget?.email || ""})? This action cannot be undone.`}
        onConfirm={handleDelete}
        onCancel={() => setDeleteTarget(null)}
      />
    </div>
  );
}
