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 ROLE_OPTIONS = ["", "sysadmin", "admin", "editor", "user"];

const ROLE_COLORS = {
  sysadmin: { bg: "var(--danger-bg)", text: "var(--danger-text)" },
  admin: { bg: "#3b2a0a", text: "#f6ad55" },
  editor: { bg: "var(--badge-blue-bg)", text: "var(--badge-blue-text)" },
  user: { bg: "var(--bg-card-hover)", text: "var(--text-muted)" },
};

function RoleBadge({ role }) {
  const colors = ROLE_COLORS[role] || ROLE_COLORS.user;
  return (
    <span
      className="px-2 py-0.5 text-xs rounded-full capitalize"
      style={{ backgroundColor: colors.bg, color: colors.text }}
    >
      {role}
    </span>
  );
}

export default function StaffList() {
  const [staff, setStaff] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState("");
  const [search, setSearch] = useState("");
  const [roleFilter, setRoleFilter] = useState("");
  const [deleteTarget, setDeleteTarget] = useState(null);
  const navigate = useNavigate();
  const { user } = useAuth();

  const fetchStaff = async () => {
    setLoading(true);
    setError("");
    try {
      const params = new URLSearchParams();
      if (search) params.set("search", search);
      if (roleFilter) params.set("role", roleFilter);
      const qs = params.toString();
      const data = await api.get(`/staff${qs ? `?${qs}` : ""}`);
      setStaff(data.staff);
    } catch (err) {
      setError(err.message);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchStaff();
  }, [search, roleFilter]);

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

  const canDeleteStaff = (staffMember) => {
    if (staffMember.id === user?.sub) return false;
    if (user?.role === "admin" && staffMember.role === "sysadmin") return false;
    return true;
  };

  const canEditStaff = (staffMember) => {
    if (user?.role === "admin" && staffMember.role === "sysadmin") return false;
    return true;
  };

  const selectClass = "px-3 py-2 rounded-md text-sm cursor-pointer border";
  const selectStyle = {
    backgroundColor: "var(--bg-card)",
    color: "var(--text-primary)",
    borderColor: "var(--border-primary)",
  };

  return (
    <div>
      <div className="flex items-center justify-between mb-6">
        <h1 className="text-2xl font-bold" style={{ color: "var(--text-heading)" }}>Staff</h1>
        <button
          onClick={() => navigate("/settings/staff/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 Staff
        </button>
      </div>

      <div className="mb-4 space-y-3">
        <SearchBar onSearch={setSearch} placeholder="Search by name or email..." />
        <div className="flex flex-wrap gap-3 items-center">
          <select value={roleFilter} onChange={(e) => setRoleFilter(e.target.value)} className={selectClass} style={selectStyle}>
            <option value="">All Roles</option>
            {ROLE_OPTIONS.filter(Boolean).map((r) => (
              <option key={r} value={r}>{r.charAt(0).toUpperCase() + r.slice(1)}</option>
            ))}
          </select>
          <span className="text-sm" style={{ color: "var(--text-muted)" }}>
            {staff.length} {staff.length === 1 ? "member" : "members"}
          </span>
        </div>
      </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>
      ) : staff.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 staff members 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" 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)" }}>Role</th>
                  <th className="px-4 py-3 text-left font-medium" style={{ color: "var(--text-secondary)" }}>Status</th>
                  <th className="px-4 py-3 text-left font-medium w-24" style={{ color: "var(--text-secondary)" }} />
                </tr>
              </thead>
              <tbody>
                {staff.map((member) => (
                  <tr
                    key={member.id}
                    onClick={() => navigate(`/settings/staff/${member.id}`)}
                    className="cursor-pointer transition-colors"
                    style={{ borderBottom: "1px solid var(--border-secondary)" }}
                    onMouseEnter={(e) => (e.currentTarget.style.backgroundColor = "var(--bg-card-hover)")}
                    onMouseLeave={(e) => (e.currentTarget.style.backgroundColor = "transparent")}
                  >
                    <td className="px-4 py-3">
                      <span className="font-medium" style={{ color: "var(--text-heading)" }}>{member.name}</span>
                    </td>
                    <td className="px-4 py-3" style={{ color: "var(--text-primary)" }}>{member.email}</td>
                    <td className="px-4 py-3"><RoleBadge role={member.role} /></td>
                    <td className="px-4 py-3">
                      <span
                        className="px-2 py-0.5 text-xs rounded-full"
                        style={
                          member.is_active
                            ? { backgroundColor: "var(--success-bg)", color: "var(--success-text)" }
                            : { backgroundColor: "var(--danger-bg)", color: "var(--danger-text)" }
                        }
                      >
                        {member.is_active ? "Active" : "Inactive"}
                      </span>
                    </td>
                    <td className="px-4 py-3">
                      <div className="flex gap-2" onClick={(e) => e.stopPropagation()}>
                        {canEditStaff(member) && (
                          <button
                            onClick={() => navigate(`/settings/staff/${member.id}/edit`)}
                            className="hover:opacity-80 text-xs cursor-pointer"
                            style={{ color: "var(--text-link)" }}
                          >
                            Edit
                          </button>
                        )}
                        {canDeleteStaff(member) && (
                          <button
                            onClick={() => setDeleteTarget(member)}
                            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 Staff Member"
        message={`Are you sure you want to delete "${deleteTarget?.name}" (${deleteTarget?.email})? This action cannot be undone.`}
        onConfirm={handleDelete}
        onCancel={() => setDeleteTarget(null)}
      />
    </div>
  );
}
