/* ============================================================
   MaintenanceOS — Admin Components
   Supporting components for admin dashboard
   ============================================================ */

// Activity Log Component
function ActivityLog({ activity }) {
  const { getUserById } = window.ADMIN_HELPERS;
  const [filter, setFilter] = useState("all");

  const filteredActivity = activity.filter(act => {
    if (filter === "all") return true;
    return act.action.startsWith(filter);
  });

  return (
    <div>
      <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 24 }}>
        <div>
          <h2 style={{ marginBottom: 4 }}>Activity Log</h2>
          <p style={{ color: "var(--text-muted)" }}>System and user activity across the platform</p>
        </div>
        <select
          value={filter}
          onChange={(e) => setFilter(e.target.value)}
          style={{
            padding: "8px 12px", borderRadius: "var(--radius-sm)",
            border: "1px solid var(--border)", background: "var(--bg)"
          }}
        >
          <option value="all">All Activity</option>
          <option value="user">User Actions</option>
          <option value="workorder">Work Orders</option>
          <option value="asset">Assets</option>
          <option value="system">System Events</option>
        </select>
      </div>

      <div className="card">
        <div style={{ padding: "0 24px" }}>
          {filteredActivity.map((act, index) => {
            const user = getUserById(act.userId);
            const isLast = index === filteredActivity.length - 1;

            return (
              <div key={act.id} style={{
                display: "flex", gap: 16, padding: "20px 0",
                borderBottom: isLast ? "none" : "1px solid var(--border)",
                position: "relative"
              }}>
                {/* Timeline dot */}
                <div style={{
                  width: 32, height: 32, borderRadius: "50%",
                  background: getActivityColor(act.action),
                  display: "flex", alignItems: "center", justifyContent: "center",
                  position: "relative", zIndex: 1
                }}>
                  <Icon name={getActivityIcon(act.action)} size={14} color="white" />
                </div>

                {/* Timeline line */}
                {!isLast && (
                  <div style={{
                    position: "absolute", left: 15, top: 52, bottom: -20,
                    width: 2, background: "var(--border)"
                  }} />
                )}

                {/* Content */}
                <div style={{ flex: 1 }}>
                  <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-start", marginBottom: 4 }}>
                    <div style={{ fontWeight: 600 }}>{user?.name || "System"}</div>
                    <div style={{ fontSize: 13, color: "var(--text-muted)" }}>
                      {new Date(act.timestamp).toLocaleString()}
                    </div>
                  </div>
                  <div style={{ color: "var(--text-muted)", marginBottom: 8 }}>
                    {act.details}
                  </div>
                  <div style={{ display: "flex", gap: 12, fontSize: 12, color: "var(--text-faint)" }}>
                    <span>Action: {act.action}</span>
                    <span>IP: {act.ip}</span>
                  </div>
                </div>
              </div>
            );
          })}
        </div>
      </div>
    </div>
  );
}

// System Health Component
function SystemHealth() {
  const healthData = {
    server: {
      cpu: 23,
      memory: 68,
      disk: 45,
      network: 12
    },
    database: {
      connections: 45,
      maxConnections: 100,
      queryTime: 1.2,
      storage: 78
    },
    performance: {
      responseTime: 245,
      throughput: 1250,
      errorRate: 0.02,
      uptime: 99.94
    }
  };

  return (
    <div>
      <div style={{ marginBottom: 24 }}>
        <h2 style={{ marginBottom: 4 }}>System Health</h2>
        <p style={{ color: "var(--text-muted)" }}>Real-time system performance and resource monitoring</p>
      </div>

      <div className="grid-2" style={{ marginBottom: 32 }}>
        {/* Server Resources */}
        <div className="card">
          <div className="card-header">
            <h3>Server Resources</h3>
            <span className="badge badge-success">Healthy</span>
          </div>
          <div className="card-content">
            <ResourceMeter label="CPU Usage" value={healthData.server.cpu} unit="%" />
            <ResourceMeter label="Memory" value={healthData.server.memory} unit="%" />
            <ResourceMeter label="Disk Usage" value={healthData.server.disk} unit="%" />
            <ResourceMeter label="Network I/O" value={healthData.server.network} unit="MB/s" />
          </div>
        </div>

        {/* Database Health */}
        <div className="card">
          <div className="card-header">
            <h3>Database Health</h3>
            <span className="badge badge-success">Optimal</span>
          </div>
          <div className="card-content">
            <div className="metric-row">
              <span>Active Connections</span>
              <span>{healthData.database.connections} / {healthData.database.maxConnections}</span>
            </div>
            <div className="metric-row">
              <span>Avg Query Time</span>
              <span>{healthData.database.queryTime}ms</span>
            </div>
            <div className="metric-row">
              <span>Storage Used</span>
              <span>{healthData.database.storage}%</span>
            </div>
            <div className="metric-row">
              <span>Cache Hit Rate</span>
              <span>96.5%</span>
            </div>
          </div>
        </div>
      </div>

      {/* Performance Metrics */}
      <div className="card">
        <div className="card-header">
          <h3>Performance Metrics</h3>
        </div>
        <div className="card-content">
          <div className="grid-4">
            <PerformanceMetric
              label="Response Time"
              value={`${healthData.performance.responseTime}ms`}
              status="good"
              threshold="< 500ms"
            />
            <PerformanceMetric
              label="Throughput"
              value={`${healthData.performance.throughput}/min`}
              status="good"
              threshold="> 1000/min"
            />
            <PerformanceMetric
              label="Error Rate"
              value={`${healthData.performance.errorRate}%`}
              status="excellent"
              threshold="< 0.1%"
            />
            <PerformanceMetric
              label="Uptime"
              value={`${healthData.performance.uptime}%`}
              status="excellent"
              threshold="> 99.9%"
            />
          </div>
        </div>
      </div>
    </div>
  );
}

// User Detail Modal
function UserDetailModal({ user, onClose }) {
  const role = window.ADMIN_DATA.USER_ROLES[user.role];

  return (
    <div className="modal-overlay" onClick={onClose}>
      <div className="modal" onClick={e => e.stopPropagation()} style={{ maxWidth: 600, width: "90%" }}>
        <div className="modal-header">
          <h2>User Details</h2>
          <button onClick={onClose} className="btn-icon">
            <Icon name="x" size={20} />
          </button>
        </div>

        <div className="modal-content">
          <div style={{ display: "flex", gap: 24, marginBottom: 32 }}>
            <div className="avatar" style={{
              width: 80, height: 80, borderRadius: 16,
              background: "var(--surface-3)", display: "flex",
              alignItems: "center", justifyContent: "center",
              fontWeight: 600, fontSize: 28
            }}>
              {user.initials}
            </div>
            <div style={{ flex: 1 }}>
              <h3 style={{ marginBottom: 8 }}>{user.name}</h3>
              <p style={{ color: "var(--text-muted)", marginBottom: 12 }}>{user.email}</p>
              <span className="badge" style={{
                background: role.color + "20",
                color: role.color,
                fontWeight: 600
              }}>
                {role.name}
              </span>
            </div>
          </div>

          <div className="grid-2">
            <div>
              <h4 style={{ marginBottom: 16 }}>Basic Information</h4>
              <div className="info-list">
                <div className="info-item">
                  <label>Phone</label>
                  <span>{user.phone}</span>
                </div>
                <div className="info-item">
                  <label>Department</label>
                  <span>{user.department}</span>
                </div>
                <div className="info-item">
                  <label>Status</label>
                  <span className={`badge badge-${user.status}`}>
                    {user.status === "active" ? "Active" : "Inactive"}
                  </span>
                </div>
                <div className="info-item">
                  <label>Last Login</label>
                  <span>{window.ADMIN_HELPERS.formatLastLogin(user.lastLogin)}</span>
                </div>
              </div>
            </div>

            <div>
              <h4 style={{ marginBottom: 16 }}>Permissions</h4>
              <div style={{ maxHeight: 200, overflowY: "auto" }}>
                {role.permissions.map((perm, index) => (
                  <div key={index} style={{
                    padding: "6px 12px", marginBottom: 4,
                    background: "var(--surface-2)", borderRadius: "var(--radius-sm)",
                    fontSize: 13, fontFamily: "var(--font-mono)"
                  }}>
                    {perm}
                  </div>
                ))}
              </div>
            </div>
          </div>
        </div>

        <div className="modal-footer">
          <button className="btn">Edit User</button>
          <button className="btn btn-danger">Delete User</button>
        </div>
      </div>
    </div>
  );
}

// Create User Modal
function CreateUserModal({ onClose }) {
  const [formData, setFormData] = useState({
    name: "",
    email: "",
    role: "technician",
    department: "",
    phone: "",
    facilities: []
  });

  const handleSubmit = (e) => {
    e.preventDefault();
    // Handle user creation
    console.log("Creating user:", formData);
    onClose();
  };

  return (
    <div className="modal-overlay" onClick={onClose}>
      <div className="modal" onClick={e => e.stopPropagation()} style={{ maxWidth: 500 }}>
        <div className="modal-header">
          <h2>Add New User</h2>
          <button onClick={onClose} className="btn-icon">
            <Icon name="x" size={20} />
          </button>
        </div>

        <form onSubmit={handleSubmit}>
          <div className="modal-content">
            <div className="form-group">
              <label>Full Name</label>
              <input
                type="text"
                value={formData.name}
                onChange={(e) => setFormData({...formData, name: e.target.value})}
                required
              />
            </div>

            <div className="form-group">
              <label>Email Address</label>
              <input
                type="email"
                value={formData.email}
                onChange={(e) => setFormData({...formData, email: e.target.value})}
                required
              />
            </div>

            <div className="grid-2">
              <div className="form-group">
                <label>Role</label>
                <select
                  value={formData.role}
                  onChange={(e) => setFormData({...formData, role: e.target.value})}
                >
                  {Object.entries(window.ADMIN_DATA.USER_ROLES).map(([roleId, role]) => (
                    <option key={roleId} value={roleId}>{role.name}</option>
                  ))}
                </select>
              </div>

              <div className="form-group">
                <label>Department</label>
                <input
                  type="text"
                  value={formData.department}
                  onChange={(e) => setFormData({...formData, department: e.target.value})}
                />
              </div>
            </div>

            <div className="form-group">
              <label>Phone Number</label>
              <input
                type="tel"
                value={formData.phone}
                onChange={(e) => setFormData({...formData, phone: e.target.value})}
              />
            </div>
          </div>

          <div className="modal-footer">
            <button type="button" onClick={onClose} className="btn">Cancel</button>
            <button type="submit" className="btn btn-primary">Create User</button>
          </div>
        </form>
      </div>
    </div>
  );
}

// Helper Components
function ResourceMeter({ label, value, unit }) {
  const getColor = (val) => {
    if (val > 80) return "var(--red-500)";
    if (val > 60) return "var(--orange-500)";
    return "var(--green-500)";
  };

  return (
    <div style={{ marginBottom: 16 }}>
      <div style={{ display: "flex", justifyContent: "space-between", marginBottom: 8 }}>
        <span style={{ fontSize: 14, fontWeight: 500 }}>{label}</span>
        <span style={{ fontSize: 14, fontWeight: 600 }}>{value}{unit}</span>
      </div>
      <div style={{ height: 6, background: "var(--surface-2)", borderRadius: 3, overflow: "hidden" }}>
        <div style={{
          width: `${value}%`,
          height: "100%",
          background: getColor(value),
          transition: "width 0.3s ease"
        }} />
      </div>
    </div>
  );
}

function PerformanceMetric({ label, value, status, threshold }) {
  const statusColors = {
    excellent: "var(--green-500)",
    good: "var(--blue-500)",
    warning: "var(--orange-500)",
    critical: "var(--red-500)"
  };

  return (
    <div style={{ textAlign: "center", padding: 16 }}>
      <div style={{ fontSize: 24, fontWeight: 700, color: statusColors[status], marginBottom: 4 }}>
        {value}
      </div>
      <div style={{ fontWeight: 600, marginBottom: 8 }}>{label}</div>
      <div style={{ fontSize: 12, color: "var(--text-muted)" }}>
        Target: {threshold}
      </div>
    </div>
  );
}

// Helper functions
function getActivityColor(action) {
  if (action.startsWith("user")) return "var(--blue-500)";
  if (action.startsWith("workorder")) return "var(--green-500)";
  if (action.startsWith("asset")) return "var(--orange-500)";
  if (action.startsWith("system")) return "var(--purple-500)";
  return "var(--text-muted)";
}

function getActivityIcon(action) {
  if (action.includes("login")) return "logIn";
  if (action.includes("created")) return "plus";
  if (action.includes("updated")) return "edit";
  if (action.includes("completed")) return "check";
  if (action.includes("deleted")) return "trash";
  return "activity";
}

// Export components
window.ActivityLog = ActivityLog;
window.SystemHealth = SystemHealth;
window.UserDetailModal = UserDetailModal;
window.CreateUserModal = CreateUserModal;